Pr.Pg Next Pg

Adding Music with MediaPlayer tutorials

Adding Music

  • We can add music to our activity, i.e, when the activity opens we can a sound or a music to play.

  • This feature is especially usefull when we are dealing with games.

  • This article explains how to add music to any Android App using Media Player provided by Android SDK Library.

  • In general, the media sources can be: Local resources, Internal URIs, such as one you might obtain from a Content Resolver, External URLs (streaming).

  • Our interest is in using local resources.

  • So save your application's music fie in /res/raw directory.The various supported music audio files are as follows:
    MP3, MIDI, WAV, MP4, MP4A, 3GP, FLAC, ADTS Raw AAC (.aac decode only).

  • MediaPlayer class can be used to control playback of audio/video files and streams.


Adding Music with the MediaPlayer

  • To add the background music to our application, we have to make a MediaPlayer object.

  • In our example we will add the background music for our MainActivity and stop the music as soon as the user moves to a new Activity.

  • We first add the music file which we have to add to our application in the res > raw folder.

  • We then make an declare an a reference of MediaPlayer in the MainActvity class so that the same reference can be used by the entire class which wouldn’t have been the case had we declared it inside a method.

  • Since we want to start the music as soon our MainActivity is started, we use the create() method.

  • The create() method is a convenience method to create a MediaPlayer for a given resource id.

  • We give the resource id as the id of the song which we have added to our resources in the raw folder.

  • We then start the music using the start() method on the object.

  • We add the following statements to the code.




song = MediaPlayer.create(MainActivity.this, R.raw.test_song);



  • In our example, the name of the file is test_song.mp3.

  • This song will keep playing as the song is not over even after clicking the back button.

  • The MediaPlayer services keep running in the background.

  • Inorder to close the playback before the next activity we can use various methods to stop the MediaPlayer just before the finish() method.

  • In our example we use the release() method.

  • This method will make the object unavailable that is destroy the object.


Pr.Pg border                                              Next Pg