Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Playing Audio from a File

Author: Marco Dinacci -- Published? true -- FormatLanguage: W

Problem:

You want to play an audio file stored on the device.

Solution:

Create and configure properly a MediaPlayer and a MediaController, provide the path of the audio file to play and enjoy the music.

Discussion:

Playing an audio file is as easy as setting up a MediaPlayer and a MediaController.

First create a new activity that implements the MediaPlayerControl interface.

public class PlayAudioActivity extends Activity implements MediaPlayerControl {
        private MediaController mMediaController;
        private MediaPlayer mMediaPlayer;
        private Handler mHandler = new Handler();

In the onCreate method we create and configure a MediaPlayer and a MediaController. The first is the object that perform the typical operations on an audio file like playing, pausing and seeking. The second is a view containing the buttons that launch the just mentioned operations through our MediaPlayerControl class.

Let's see the onCreate code:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mMediaPlayer = new MediaPlayer();
        mMediaController = new MediaController(this);
        mMediaController.setMediaPlayer(PlayAudioActivity.this);
        mMediaController.setAnchorView(findViewById(R.id.audioView));
        
        String audioFile = "" ; 
        try {
            mMediaPlayer.setDataSource(audioFile);
            mMediaPlayer.prepare();
        } catch (IOException e) {
            Log.e("PlayAudioDemo", "Could not open file " + audioFile + " for playback.", e);
        }
        
        mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                    mHandler.post(new Runnable() {
                            public void run() {
                                    mMediaController.show(10000);
                                    mMediaPlayer.start();
                            }
                    });
            }
        });
    }

In addition to configuring our MediaController and MediaPlayer we create an anonymous OnPreparedListener in order to start the player only when the media source is ready for playback.

Remember to cleanup the media player when the Activity is destroyed.

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMediaPlayer.stop();
        mMediaPlayer.release();
    }

At last we implement the MediaPlayerControl interface. The code is very straightforward:

    
    @Override
    public boolean canPause() {
        return true;
    }

    @Override
    public boolean canSeekBackward() {
        return false;
    }

    @Override
    public boolean canSeekForward() {
        return false;
    }

    @Override    
    public int getBufferPercentage() {
        int percentage = (mMediaPlayer.getCurrentPosition() * 100) / mMediaPlayer.getDuration();
        
        return percentage;
    }

    @Override
    public int getCurrentPosition() {
        return mMediaPlayer.getCurrentPosition();
    }

    @Override
    public int getDuration() {
        return mMediaPlayer.getDuration();
    }

    @Override
    public boolean isPlaying() {
        return mMediaPlayer.isPlaying();
    }

    @Override
    public void pause() {
        if(mMediaPlayer.isPlaying())
            mMediaPlayer.pause();
    }

    @Override
    public void seekTo(int pos) {
        mMediaPlayer.seekTo(pos);
    }

    @Override
    public void start() {
        mMediaPlayer.start();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mMediaController.show();
        
        return false;
    }
}

As a final touch we override the onTouchEvent in order to show the MediaController buttons when the user click on the screen.

Since we create our MediaController programmatically, the layout is very simple:

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

Download:

The source code for this project can be downloaded from http://db.tt/jEUv7qq0.
Cesz 2014-10-24 15:47:36.8 Hi! I'm new in Android Development so I have a doubt about your code: How do I have to make the UI? What is an AudioController? and, Why I can't test it on my phone? Sorry, but I still don't understand a lot of things on this..... and sorry (again) if my English isn't good, I'm mexican haha! :D Thanks!