Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to handle Media with Android

In this tutorial, we will illustrate the usage of the Android media API for playing and recording sound. All is based on Eclipse, Java and Android 4.0.3 (Ice Cream Sandwich).

In this tutorial we will talk about:

  • Android Sound and Media
  • Playing sound

Android offers two vital API's for playing sounds, the first being via the SoundPool class and the other one via theMediaPlayer class.

SoundPool can be deployed for small audio clips that can repeat sounds and play several sounds at the same time. But make sure that the size does exceed more than 1 MB when the sound files are played with SoundPool. SoundPool does load the file asynchronously and as far as Android API8 is concerned, it is possible to verify if the loading is complete with the help of aOnLoadCompleteListener.

Different audio streams are supported by Android to serve varying purposes. A specific audio steam could be controlled by configuring a phone volume button, example can be of a call where the volume button permits to increase or decrease the caller volume. We can set the button to control the sound media stream by setting the audio type in your application in the following manner:

context.setVolumeControlStream(AudioManager.STREAM_MUSIC);

MediaRecorder

The android.media.MediaRecorder class can be utilized so as to record audio and video. In order to make use of MediaRecorder, one requires setting the source device and the format.

Adding to the Media library

One can incorporate new Media to the Android media library. With the help of Intent, one can easily tell the media application on the device for the availability of the new content. Let us see the same with the help of the following code.

Listing 1: Availability of the new content

// Add new file to your media library
ContentValues values = new ContentValues(4);
long current = System.currentTimeMillis();
values.put(MediaStore.Audio.Media.TITLE, "audio" + audiofile.getName());
values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/3gpp");
values.put(MediaStore.Audio.Media.DATA, audiofile.getAbsolutePath());
ContentResolver contentResolver = getContentResolver();

Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Uri newUri = contentResolver.insert(base, values);

// Notifiy the media application on the device
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newUri));

Tutorial: Play sounds via SoundPool

Let us come with an application that starts playing a sound once the display is touched by the finger. We will create an Android project by the name of "mrbool.android.soundpool" with an Activity called PlaySound.

Let alter the layout main.xml to the following.

Listing 2: main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Click on the screen to start playing" >
    </TextView>

</LinearLayout>

Now the next step is to put the sound file into your "res/raw" folder under the name "sound1.ogg".

This needs to create the subsequent code for your activity.

Listing 3: subsequent code

package mrbool.android.soundpool;

import android.app.Activity;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class PlaySound extends Activity implements OnTouchListener {
  private SoundPool soundPool;
  private int soundID;
  boolean loaded = false;

  
/** Called when the activity is first created. */

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    View view = findViewById(R.id.textView1);
    view.setOnTouchListener(this);
    // Set the hardware buttons to control the music
    this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
    // Load the sound
    soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
    soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
      @Override
      public void onLoadComplete(SoundPool soundPool, int sampleId,
          int status) {
        loaded = true;
      }
    });
    soundID = soundPool.load(this, R.raw.sound1, 1);

  }

  @Override
  public boolean onTouch(View v, MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
      // Getting the user sound settings
      AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
      float actualVolume = (float) audioManager
          .getStreamVolume(AudioManager.STREAM_MUSIC);
      float maxVolume = (float) audioManager
          .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
      float volume = actualVolume / maxVolume;
      // Is the sound loaded already?
      if (loaded) {
        soundPool.play(soundID, volume, volume, 1, 0, 1f);
        Log.e("Test", "Played sound");
      }
    }
    return false;
  }
}

Touching the activity now should play the sound. The current volume setting will be used.

Tutorial: Record media via MediaRecorder

Let us now create an application that will start playing a sound once the display is touched by the finger. We will be creating an Android project by the name of "mrbool.android.media.soundrecording" with an Activity called RecordSound.

We will now add the permission to the AndroidManifest.xml file so as write to the SD card and to record audio data.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 <uses-permission android:name="android.permission.RECORD_AUDIO" />

Let’s alter the layout main.xml as below:

Listing 4: main.xml updated.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Recording"
        android:onClick="startRecording" />

    <Button
        android:id="@+id/stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop Recording" 
        android:enabled="false"
         android:onClick="stopRecording"
        />

</LinearLayout>

Pressing the "Start Recording" button will start recording the sound. Recording will be stopped on pressing the stop recording button, and the file will be added to your media library.

Conclusion

The tutorial was focussed around the process to play the sound and record the media on accessing the Android display screen by the finger.



I am a software developer from India with hands on experience on java, html for over 5 years.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login