Android 3.0 Application Development: Multimedia Management


Android 3.0 Application Development Cookbook

Android 3.0 Application Development Cookbook

Over 70 working recipes covering every aspect of Android development

        Read more about this book      

(For more resources on Android, see here.)



Very few successful applications are completely silent or have only static graphics, and in order that Android developers take full advantage of the advanced multimedia capabilities of today's smartphones, the system provides the package, which contains many useful classes.

The MediaPlayer class allows the playback of both audio and video from raw resources, files, and network streams, and the MediaRecorder class makes it possible to record both sound and images.

Android also offers ways to manipulate sounds and create interactive effects through the use of the SoundPool class, which allows us to not only bend the pitch of our sounds but also to play more than one at a time.


Playing an audio file from within an application

One of the first things that we may want to do with regards to multimedia is play back an audio file. Android provides the class for us and this makes playback and most media related functions remarkably simple.

In this recipe we will create a simple media player that will play a single audio file.

Getting ready

Before we start this project we will need an audio file for playback. Android can decode audio with any of the following file extensions:

  • .3GP
  • .MP4
  • .M4A
  • .MP3
  • .OGG
  • .WAV

There are also quite a few MIDI file formats that are acceptable but have not been included here as their use is less common and their availability often depends on whether a device is running the standard Android platform or a specific vendor extension.

Before you start this exercise create or find a short sound sample in one of the given formats. We used a five second Ogg Vorbis file and called it my_sound_file.ogg.

How to do it...

  1. Start up a new Android project in Eclipse and create a new folder: res/raw.
  2. Place the sound file that you just prepared in this folder. In this example we refer to it as my_sound_file.
  3. Using either the Graphical Layout or the main.xml panel edit the file res/layout/main.xml to contain three buttons, as seen in the following screenshot:

    Android 3.0 Application Development Cookbook

  4. Call these buttons play_button, pause_button and stop_button.
  5. In the Java activity code declare a MediaPlayer in the onCreate() method:

    public void onCreate(Bundle state) {
    final MediaPlayer mPlayer;

  6. Associate the buttons we added in step 3 with Java variables by adding the following lines to onCreate():

    Button playButton =
    (Button) findViewById(;
    Button pauseButton =
    (Button) findViewById(;
    Button stopButton =
    (Button) findViewById(;

  7. We need a click listener for our play button. This also can be defined from within onCreate():

    playButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    mPlayer = MediaPlayer.create(this, R.raw.my_sound_file);

  8. Next add a listener for the pause button as follows:

    pauseButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {

  9. Finally, include a listener for the stop button:

    stopButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {

  10. Now run this code on an emulator or your handset and test each of the buttons.

How it works...

The MediaPlayer class provides some useful functions and the use of start(), pause(), stop(), and setLooping() should be clear. However, if you are thinking that calling MediaPlayer.create(context, ID) every time the start button is pressed is overkill, you would be correct. This is because once stop() has been called on the MediaPlayer, the media needs to be reset and prepared (with reset() and prepare()) before start() can be called again. Fortunately MediaPlayer.create() also calls prepare() so that the first time we play an audio file we do not have to worry about this.

The lifecycle of the MediaPlayer is not always straightforward and the order in which it takes on various states is best explained diagrammatically:

Android 3.0 Application Development Cookbook

Otherwise, MediaPlayer has lots of useful methods such as isPlaying(), which will return a Boolean telling us whether our file is being played or not, or getDuration() and getCurrentPosition(), which inform us of how long the sample is and how far through it we are. There are also some useful hooks that we can employ using MediaPlayer and the most commonly used are onCompletionListener() and onErrorListener().

There's more...

We are not restricted to playing back raw resources. We can also playback local files or even stream audio.

Playing back a file or a stream

Use the MediaPlayer.setDataSource(String) method to play an audio file or stream. In the case of streaming audio this will need to be a URL representing a media file that is capable of being played progressively, and you will need to prepare the media player each time it runs:

MediaPlayer player = new MediaPlayer();
player.setDataSource("string value of your file path or URL");

It is essential to surround setDataSource() with a try/catch clause in case the source does not exist when dealing with removable or online media.


Playing back video from external memory

The MediaPlayer class that we met in the previous recipe works for video in the same manner that it does for audio and so as not to make this task a near copy of the last, here we will look at how to play back video files stored on an SD card using the VideoView object.

Getting ready

This recipe requires a video file for our application to playback. Android can decode H.263, H.264 and MPEG-4 files; generally speaking this means files with .3gp and .mp4 file extensions. For platforms since 3.0 (API level 11) it is also possible to manage H.264 AVC files.

Find a short video clip in one of these compatible formats and save it on the SD card of your handset. Alternatively you can create an emulator with an SD card enabled and push your video file onto it. This can be done easily through Eclipse's DDMS perspective from the File Explorer tab:

Android 3.0 Application Development Cookbook

In this example we called our video file my_video.3gp.



        Read more about this book      

(For more resources on Android, see here.)


How to do it...

  1. Start a new project in Eclipse and navigate to the main.xml file. Replace the prepared TextView with the following VideoView:

    android:id="@+id/video_view" />

  2. Associate this view with a Java variable in the usual manner from within the onCreate() method:

    public void onCreate(Bundle state) {
    VideoView view =
    (VideoView) findViewById(;

  3. Directly underneath this, set a path to our video with this line:

    + "/myvideo.3gp");

  4. Now add a command to play the video:
  5. Run this code on your handset or emulator. The video will play as soon as the application starts:

    Android 3.0 Application Development Cookbook

How it works...

We have not encountered the VideoView object before but nevertheless it is very similar to the View subclasses. However, it also implements the MediaController.MediaPlayerControl class and this gives us access to some of the useful methods that we used with the MediaPlayer earlier in the article such as isPlaying(), getDuration(), and getCurrentPosition(), and like other views it has an onTouchEvent(MotionEvent) callback which can prove very useful.

For Android platforms 3.0 onwards it has been possible to run HTTP live streaming sessions by passing an M3U playlist URL to the media framework.

There's more...

When it comes to adding common media controls such as play, pause and seek, Android provides a very handy little widget in the form of the MediaPlayerControl interface that can be accessed through the android.widget.MediaController class, and which automatically synchronizes with the active media and floats above it.

Android 3.0 Application Development Cookbook

Adding a MediaPlayerControl to a view

A MediaPlayerControl can be created with something along the lines of:

myPlayerControl = new MediaController.MediaPlayerControl()

This will necessitate the implementing of several methods that give us further control over the widget's appearance and behavior.

Once defined, we can apply the widget to our media using:


We can also select which view it hovers over with:


The media player control will take care of when it appears by itself. To force it to be displayed use, where int is the number of milliseconds to display the controls and a value of 0 will cause the widget to display as long as the related view is visible, regardless of whether media is playing or not.


Playing multiple sounds with a SoundPool

Android provides an extremely useful audio tool in the form of the class. This class allows us to play more than one sound at a time and to adjust the pitch and stereo placement of these sounds programmatically. Here we will create a SoundPool that will play three sound files simultaneously.

Getting ready

You will need three audio files to complete this exercise. Find three short samples in one of the compatible formats, ideally noises that will not sound unpleasant when played together. Here we have used Ogg Vorbis files and named them sound1, sound2, and sound3.

How to do it...

  1. Start up a new Android project in Eclipse and create a new folder called raw inside the res folder.
  2. Place the three sound files you selected earlier inside res/raw.
  3. As a class-wide field in the main Java activity code, declare and assign a new SoundPool as follows:

    SoundPool pool =
    new SoundPool(3, AudioManager.STREAM_MUSIC, 0);

  4. We will have our sounds play as the activity starts and use a hash map as a simple index. Amend the onCreate() method to match the one found here:

    public void onCreate(Bundle state) {
    HashMap<Integer, Integer> map = null;
    map.put(1, pool.load(this, R.raw.sound1, 1));
    map.put(2, pool.load(this, R.raw.sound2, 1));
    map.put(3, pool.load(this, R.raw.sound3, 1));
    for (int i = 1; i < 4; i++) {, 0.8f, 0.2f, 1, 0, 1.0f);

  5. SoundPools need to be shut down when they are no longer needed, so add an onPause() method and include the following lines:

    public void onPause() {
    pool = null;

  6. This is all the code we need to play back our samples. Run the project on your handset or emulator in the usual way.

How it works...

The main object of interest in this task is the SoundPool. We constructed it with three int values. The first number tells the system about the maximum number of sounds that we wish to play at any one time, and is not limited.

The second argument is a constant member of AudioManager and is used to select the type of sound we want. Here we chose STREAM_MUSIC but there are others available and some of the most commonly used include STREAM_ALARM and STREAM_RING.

The final value represents the desired audio quality. However, as of Android 3.1, it still has not been implemented and so is left as zero.

The method is self explanatory in function and the purpose of each of the six required parameters is explained in the following list:

  • int - the index of the sound.
  • float - the left volume, between 0 and 1.
  • float - the right volume.
  • int - the priority. This is for situations where the number of played sounds exceeds the maximum, with higher numbers having higher priority.
  • int - sets the number of times the sound should loop. Set to -1 to loop indefinitely. This can be halted with SoundPool.stop().
  • float - the speed of the file's playback. Set at 2.0 to double the speed and 0.5 to halve it.

It is this last parameter to adjust the pitch of our sounds that demonstrates what is perhaps the most useful function of the SoundPool class. This can be applied to create Doppler-like effects in games or to save on memory by using a single resource to produce several notes. Another advantage of the way that SoundPools work is the way that they cut down on latency by preparing the samples during construction.

It is worth noting that although we used raw resources as our audio source it is perfectly possible and just as simple to use files from any available source.


In this article we saw how to play a variety of media such as audio and video.

Further resources on this subject:

You've been reading an excerpt of:

Android 3.0 Application Development Cookbook

Explore Title