5 min read

Android 3.0 Application Development Cookbook

Android 3.0 Application Development Cookbook

Over 70 working recipes covering every aspect of Android development

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 android.media 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 android.media.MediaPlayer 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:

    @Override
    public void onCreate(Bundle state) {
    super.onCreate(state);
    setContentView(R.layout.main);
    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(R.id.play_button);
    Button pauseButton =
    (Button) findViewById(R.id.pause_button);
    Button stopButton =
    (Button) findViewById(R.id.stop_button);

    
    
  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);
    mPlayer.setLooping(true);
    mPlayer.start();
    }
    });

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

    pauseButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    mPlayer.pause();
    }
    });

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

    stopButton.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    mPlayer.stop();
    mPlayer.reset();
    }
    });

    
    
  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”);
player.prepare();
player.start();


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.

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here