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

Playing Audio Without Interaction

In Chapter: Multimedia
Author: Ian Darwin ('idarwin')
Published? true
FormatLanguage: WikiFormat


You want to play an audio file with no interaction.


All you need to play a file with no interaction (e.g., not user-settable volume, pause, etc. controls) is to create a MediaPlayer for the file, and call its start() method.


This is the simplest way to play a sound file. In contrast with the recipe Playing audio from a file, this version offers the user no controls to interact with the sound. You should therefore usually offer at least a "stop" or "cancel" button, especially if the audio file is or might be long. If you're just playing a short sound effect within your application, no such control is needed.

You must have a MediaPlayer created for your file. The audio file may be on the SD Card or it may be in your application's res/raw directory. If the sound file is part of your application, store it under res/raw. Suppose it is in res/raw/alarm_sound.3gp. Then the reference to it s R.raw.alarm_sound, and you can play it as follows:

MediaPlayer player = MediaPlayer.create(this, R.raw.alarm_sound);

In the SD Card case, use the following invocation:

MediaPlayer player = new MediaPlayer();

There is also a convenience routine, MediaPlayer.create(Context, URI) that can be used; in all cases, create() calls prepare() for you.

To control the play from within your application, you can call the relevant methods such as player.stop(), player.pause(), etc. If you want to reuse a player after stopping it, you must call prepare() again.

To be notified when the audio is finished, use an OnCompletionListener:

player.setOnCompletionListener(new OnCompletionListener() {
         public void onCompletion(MediaPlayer mp) {
                         "Media Play Complete", Toast.LENGTH_SHORT).show();

When you are truly done with any MediaPlayer instance, you should call its release() method to free up memory, or you will run out of resources if you are creating a lot of MediaPlayer objects.

See Also:

To really use the MediaPlayer effectively you should understand its various states and transitions, as this will help you to understand what methods are valid. There is a complete state diagram for the MediaPlayer at [1].


The source code for this project can be downloaded from http://projects.darwinsys.com/MediaPlayerDemo..tgz .


The source code for this project is in the Android Cookbook repository, http://github.com/IanDarwin/Android-Cookbook-Examples/tree/master/MediaPlayerDemo.