Playing music/sound on Android project


Playing a sound or music in Android is very easy to do. It consists using mostly the MediaPlayer class.

I will base this tutorial on the Android Service tutorial I did. Using MediaPlayer as a service is very common. For this tutorial, I will only use methods that will get you started, I won’t go over all the methods this class has.

Let’s break down everything piece by piece:

  1. start(): calling this will start playing your sound
  2. prepare(): prepares the player for playback, synchronously. After setting the datasource and the display surface, you need to either call prepare() or prepareAsync(). For files, it is OK to call prepare(), which blocks until MediaPlayer is ready for playback.
  3. setDataSource(AssetFileDescriptor): you need to play something, and this method takes in a AssetFileDescriptor that will set the data source to use for playing
    1. Depending on where you have your mp3 file stored, I stored mines in the asset folder of my Android project. You can declare and initialize an AssetFileDescriptor like so:
      1. AssetFileDescriptor fd = this.getAssets().openFd(“yoursong.mp3”);
  4. setVolume(): see here: https://developer.android.com/reference/android/media/MediaPlayer.html#setVolume(float,float)
  5. setAudioStreamType(): sets the kind of sound to be played (stream), you specify using AudioManager like so: AudioManager.STREAM_MUSIC     or      AudioManager.STREAM_ALARM
  6. isPlaying(): returns true or false whether or not a sound is still currently playing
  7. The order of calls to play a song: new MediaPlayer() -> setAudioStream() -> setDataSource() -> prepare() -> start()
  8. You can override MediaPlayer.OnCompletionListener to listen for when the sound is done playing

Here’s some sample code I’ve provided of using MediaPlayer as a service to play songs/sounds. Notice how I’ve implemented MediaPlayer.OnCompletionListener and MediaPlayer.OnPreparedListener. I store my mp3 file in my assets folder of my Android project.

public class SoundService extends Service implements MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener
{
	private MediaPlayer mediaPlayer;
	private AssetFileDescriptor asfd;

	@Override
	public void onCreate()
	{
		super.onCreate();
		mediaPlayer = new MediaPlayer();
		mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		//set the listeners for onprepared and oncompletion

		mediaPlayer.setOnCompletionListener(this);
	}
	
	@Override
	public void onCompletion(MediaPlayer mp)
	{
		stopSelf(); //stop the service if we're done playing a song
	}
	@Override
	public void onPrepared(MediaPlayer mp)
	{
		mp.start();
	}
	public void playSound()
	{
		try
		{
			asfd = this.getAssets().openFd("song.mp3");
		} 
		catch (IOException e)
		{

			e.printStackTrace();
		}
		
		try
		{
			mediaPlayer.setDataSource(asfd.getFileDescriptor(), asfd.getStartOffset(), asfd.getLength());
		} 
		catch (Exception e)
		{
			e.printStackTrace();
		}
		try
		{
			mediaPlayer.prepare();
		} 
		catch (IllegalStateException | IOException e)
		{
			e.printStackTrace();
		}
		mediaPlayer.setVolume(1.0f, 1.0f);
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) 
	{
		super.onStartCommand(intent, flags, startId);
		if (!mediaPlayer.isPlaying()) 
    	{
    		playSound();
    		onPrepared(mediaPlayer);
    	}
	    return START_STICKY;
	}
	public void onDestroy() 
	{
	    if (mediaPlayer.isPlaying()) 
	    {
	    	mediaPlayer.stop();
	    }
	    mediaPlayer.release();
	  }
	@Override
	public IBinder onBind(Intent intent)
	{
		return null;
	}
}

Android MediaPlayer state diagram

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s