Recipe Choosing and Playing Back Audio Files

The MediaRecorder and MediaPlayer classes are used to record and play back either audio or video. This recipe focuses on audio, and the usage is straightforward. For playback, the steps are

1. Create an instance of the MediaPlayer: MediaPlayer m_mediaPlayer = new MediaPlayer();

2. Specify the source of media. It can be created from a raw resource: m_mediaPlayer = MediaPlayer.create(this, R.raw.my_music);

Another option is to set as a file from the filesystem (which then also needs a prepare statement):

m_mediaPlayer.setDataSource(path); m_mediaPlayer.prepare();

In any case, these statements need to be surrounded by a try-catch block because the specified resource might not exist.

3. Start playback of the audio: m_mediaPlayer.start();

4. When the playback is done, stop the MediaPlayer and release the instance to free up resources:

m_mediaPlayer.stop(); m_mediaPlayer.release(); This recipe utilizes the same ListFiles activity shown in Listing 6.3 and 6.4 to create a selectable list of audio files to choose from for playback. It is assumed that audio files are in the /sdcard/music/ directory of the Android device, but this is configurable.

When the ListFiles activity returns a file, it is initialized as the MediaPlayer media source, and the method startMP() is called.This starts the MediaPlayer and sets the button text to show "Pause." Similarly, the pauseMP() method pauses the MediaPlayer and sets the button text to show "Play." At any time, the user can click the button to pause or continue the playback of the music.

In general, the MediaPlayer creates its own background thread and does not pause when the main activity pauses.This is reasonable behavior for a music player, but in general, the developer might want control over this.Therefore, for illustration purposes, in this recipe, the music playback is paused and resumed along with the main activity by overriding the onPause() and onResume() methods.This is shown in Listing 6.6.

Listing 6.6 src/com/cookbook/audio_ex/ package com.cookbook.audio_ex;

import; import android.content.Intent; import;

import android.os.Bundle; import android.os.Environment; import android.view.View; import android.widget.Button;

public class AudioExamples extends Activity { static final String MUSIC_DIR = "/music/";

Button playPauseButton;

private MediaPlayer m_mediaPlayer;

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);


playPauseButton = (Button) findViewById(; m_mediaPlayer= new MediaPlayer();

String MusicDir = Environment.getExternalStorageDirectory() â– getAbsolutePath() + MUSIC_DIR;

//Show a list of Music files to choose Intent i = new Intent(this, ListFiles.class); i.putExtra("directory", MusicDir); startActivityForResult(i,0);

playPauseButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) {

if(m_mediaPlayer.isPlaying()) {

//stop and give option to start again pauseMP(); } else {


^Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == 0 && resultCode==RESULT_OK) {

String tmp = data.getExtras().getString("clickedFile");

m_mediaPlayer.setDataSource(tmp); m_mediaPlayer.prepare(); } catch (Exception e) { e.printStackTrace();


playPauseButton.setText("Play"); m_mediaPlayer.pause();

m_mediaPlayer.start(); playPauseButton.setText("Pause");

boolean needToResume = false;

^Override protected void onPause() {

if(m_mediaPlayer != null && m_mediaPlayer.isPlaying()) { needToResume = true; pauseMP();


^Override protected void onResume() { super.onResume();

if(needToResume && m_mediaPlayer != null) { startMP();

The associated main XML layout with the play/pause button is shown in Listing 6.7.

Listing 6.7 res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:id="@+id/play_pause" android:text="Play" android:textSize="20sp" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>

Character Building Thought Power

Character Building Thought Power

Character-Building Thought Power by Ralph Waldo Trine. Ralph draws a distinct line between bad and good habits. In this book, every effort is made by the writer to explain what comprises good habits and why every one needs it early in life. It draws the conclusion that habits nurtured in early life concretize into impulses in future for the good or bad of the subject.

Get My Free Ebook

Post a comment