ArticlesBlog

How to Play a Sound File Using the MediaPlayer Class – Android Studio Tutorial

How to Play a Sound File Using the MediaPlayer Class – Android Studio Tutorial


Hey, guys. In this video we will learn
how to use the MediaPlayer class to
play a local sound file We can pause it We can resume it And we can stop it I already made a video about the
SoundPool class, which is better when you want to play
multiple short sound clips whereas the MediaPlayer class is better
for longer sound files, like music You can find the SoundPool video in
the info card box in the top right corner of this video And I will put a link to the source code
of this example into the description box Okay, let’s start So we want to play a local sound file For this we first have to go into our
“app” folder here “res” Right click on “res” and create a new “Android
resource directory” From this drop-down menu here we choose
“raw” Keep the name as it is and click on “OK” Now we have this “raw” folder and in
here we paste our sound file I go ahead and paste an .mp3 file,
which I prepared And now we can use this to play it in our app So now let’s make some changes to our
layout file and add these 3 buttons So we delete this TextView here And let’s change this to a LinearLayout which we give the orientation “vertical” And a gravity of “center”, so the
buttons are in the middle Now in here we put our 3 buttons “wrap_content” width and height
for all of them We set the text of the first one to “Play” And we don’t give it an id, instead we
give it an “onClick” attribute To call the method directly And the method we will call will have the
name “play” Now we copy this for the other 2 buttons We change this to “Pause” We will call the “pause” method Change this to “Stop” And call the “stop” method That’s all for our layout So now let’s switch over to our
MainActivity.java file At the top we create a variable for our
media player So we write “MediaPlayer” (android.media) Let’s call it “player” And let’s create our 3 methods which we
called from our XML file They have to be public void
the first one was “play” And we have to pass a View which we call “v”,
because we call it from our XML file otherwise our app will crash Before we take care of this method, we
create the other 2 methods the same way “public void pause (View v)” and “public void stop(View v)” Now, creating a media player and playing
a sound file with it is pretty easy The tricky part is releasing the media
player properly, because the media player takes up system
resources and it’s good practice to release it
as soon as we don’t need it anymore So, instead of creating it in our
onCreate() method We will create our media player in our
play() method So we only create it, when we actually
want to play something Here we check “if (player)==null” Because if it’s already created we
don’t want to create a new one So if it’s null We take “player==MediaPlayer”
with capital ‘M’ “.create” here we have to pass a context and our sound file which we can find
under “R.raw.” and the name of the file. Which is
“song” in this case It’s also important to release the media
player before creating a new one Otherwise we create more and more media
players, while still holding onto the old one and this way use up more and more
system resources So we always have to make sure to hold
onto only one instance of our media player And now outside of this “if” statement
here we call player.start() Because we want to start it no matter if
we just created it or not So we press “play”, we create a media
player, if we don’t have one yet and
then we start it Now let’s take care of the pause()
method here Here we check “if (player !=null)” In this case we want to call player.pause()
It’s pretty simple When we paused it and then call “start” on it,
it will resume where we paused it. And now our onStop() method In here we don’t only want to stop our
media player We also want to release it to free up
the system resources So I create a separate method for
that Because we don’t only want to release
our media player in the stop() method, but also in other places So we call this “private void stopPlayer()” And in here again we check
“if (player !=null)” then we call player.release() to release the resources And we set our “player” variable to null Let’s also put a Toast message in here, so we see when we actually release our
media player With “Toast.makeText()” We pass “this” for the context “MediaPlayer released”,
Toast.LENGTH_SHORT).show() So when we click the “stop” button we
could call player.stop(), but this would not release the system
resources So for a simple playback, like we do it
in our example here it’s better to release it instead So we don’t call stop(), instead we
call our own stopPlayer() method And now instead of holding onto our
MediaPlayer instance We release it and then create a new one
the next time we press “play” because we set our player to null But as said, we don’t only call this
method in our stop() method but also, when our media player
finished a song For this we go into our play() method Into this if-statement here again We take our “player” variable And call “.setOnCompletionListener()” on it And we pass a
“new MediaPlayer.OnCompletionListener()” And we get this onCompletion() method In here again, we call our
stopPlayer() method and release the media player
because it’s done And one more place where we want to release it:
We go all the way to the bottom And override our onStop() method here “protected void onStop()” and below
“super.onStop()” we also call our stopPlayer() method So as soon as we leave our app, we stop
and release our media player If we want to keep background music
running while our app is not opened we have to create a service for that And I will make a video on that in the
future as well But in this simple example we stop our
player when we leave our app This whole releasing part is a bit
tricky, but it’s really better to release the
media player as soon as you stop playing music with it And it’s also really encouraged in the
official documentation So that’s it for our code. Now let’s
test it So when we press “play” we start our
music Now it’s paused, and when I press “play”
again it should resume where we paused it And “stop” stops it and releases the
media player When we play it and then leave our app
it will be released as well Okay As said, I will also make a video about
how to keep the music playing when we leave our app So make sure to subscribe to not miss that And if this video was helpful, please
leave a like Take care.

Comments (82)

  1. As always, a great video!

  2. Thanks
    How use 5 sound file show by listview for play like this

  3. how to share this …. make a share button that we can share the audio file in whats app,gmail,facebook etc.

  4. love me some music
    thanx man , good one

  5. Hi there, I am a really really really beginner in Android Studio. I found that your tutorial and explain are FREAKING helpful and beginner friendly, because your tutorial is based on the latest android studio version. Could you make some tutorial about getting last known location? Thx.

  6. nice tutorial. could you please make an FM or AM radio streaming app that can still play music even when the phone is locked, I mean the controls are still visible in your phones backbround or notification panel. thank you

  7. i had a problem with my new app project (build it for my kids) and i hope somone will help me with it.

    on my app , i had a nine diffrents buttons. for any button i had diffrent sound.

    if you press the "bird button" then you can hear a bird voice twitt, if you press the "dog button" you will hear a dog voice… i set sound for all the nine buttons and when i press one of them i can hear the sound nice as i want.

    but(!), if i press one of the button and imidiattly after that i press on another botton,i hear the voice together (for exsmple if i press dog button and one second after the i press the cat button, i hear the dog and the cat voise togther..)

    jost wondring if you can help me so set it up.. if i press one butten i can hear a button voice. but if i press another button, the previusly sound will stop (not pause- stop) and i can hear only the last voice button that i press. public class animals extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.activity_animals );

    final MediaPlayer birdMP = MediaPlayer.create(this,R.raw.bird);
    final MediaPlayer catMP = MediaPlayer.create(this,R.raw.cat);
    final MediaPlayer chickenMP = MediaPlayer.create(this,R.raw.chicken);
    final MediaPlayer cowMP = MediaPlayer.create(this,R.raw.cow);
    final MediaPlayer dogMP = MediaPlayer.create(this,R.raw.dog);
    final MediaPlayer elephentMP = MediaPlayer.create(this,R.raw.elephent);
    final MediaPlayer horseMP = MediaPlayer.create(this,R.raw.horse);
    final MediaPlayer sheepMP = MediaPlayer.create(this,R.raw.sheep);
    final MediaPlayer wolfMP = MediaPlayer.create(this,R.raw.wolf);

    final Button Btnbird = (Button)this.findViewById( R.id.Btnbird );
    final Button Btncat = (Button)this.findViewById( R.id.Btncat );
    final Button Btnchicken = (Button)this.findViewById( R.id.Btnchicken );
    final Button Btncow = (Button)this.findViewById( R.id.Btncow );
    final Button Btndog = (Button)this.findViewById( R.id.Btndog );
    final Button Btnhelf = (Button)this.findViewById( R.id.Btnhelf );
    final Button Btnhurse = (Button)this.findViewById( R.id.Btnhurse );
    final Button Btnsheep = (Button)this.findViewById( R.id.Btnsheep );
    final Button Btnwolf = (Button)this.findViewById( R.id.Btnwolf );

    Btnbird.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick(View v) {

    catMP.stop();
    chickenMP.stop();
    cowMP.stop();
    dogMP.stop();
    elephentMP.stop();
    horseMP.stop();
    sheepMP.stop();
    wolfMP.stop();
    birdMP.start();

    }

    } );

    Btncat.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    birdMP.stop();
    chickenMP.stop();
    cowMP.stop();
    dogMP.stop();
    elephentMP.stop();
    horseMP.stop();
    sheepMP.stop();
    wolfMP.stop();
    catMP.start();

    }
    } );

    Btnchicken.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    catMP.stop();
    birdMP.stop();
    cowMP.stop();
    dogMP.stop();
    elephentMP.stop();
    horseMP.stop();
    sheepMP.stop();
    wolfMP.stop();
    chickenMP.start();

    }
    } );
    Btncow.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    catMP.stop();
    chickenMP.stop();
    birdMP.stop();
    dogMP.stop();
    elephentMP.stop();
    horseMP.stop();
    sheepMP.stop();
    wolfMP.stop();
    cowMP.start();

    }
    } );
    Btndog.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    catMP.stop();
    chickenMP.stop();
    birdMP.stop();
    cowMP.stop();
    elephentMP.stop();
    horseMP.stop();
    sheepMP.stop();
    wolfMP.stop();
    dogMP.start();

    }
    } );
    Btnhelf.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    catMP.stop();
    chickenMP.stop();
    birdMP.stop();
    dogMP.stop();
    cowMP.stop();
    horseMP.stop();
    sheepMP.stop();
    wolfMP.stop();
    elephentMP.start();

    }
    } );
    Btnhurse.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    catMP.stop();
    chickenMP.stop();
    birdMP.stop();
    dogMP.stop();
    elephentMP.stop();
    cowMP.stop();
    sheepMP.stop();
    wolfMP.stop();
    horseMP.start();

    }
    } );
    Btnsheep.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    catMP.stop();
    chickenMP.stop();
    birdMP.stop();
    dogMP.stop();
    elephentMP.stop();
    horseMP.stop();
    cowMP.stop();
    wolfMP.stop();
    sheepMP.start();

    }
    } );
    Btnwolf.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    catMP.stop();
    chickenMP.stop();
    birdMP.stop();
    dogMP.stop();
    elephentMP.stop();
    horseMP.stop();
    sheepMP.stop();
    cowMP.stop();
    wolfMP.start();

    }
    } );

    findViewById( R.id.back ).setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick(View v) {

    Intent intent = new Intent(animals.this,MainActivity.class );
    startActivity( intent );

    }

    } );

    }

  8. Thank you for your detailed video, I am a beginner, I am trying to develop a app with sound and text. I have 5 activities. I put a button in main activity which will go to 2nd act. in 2nd there is a sound and textview. when I click the button it goes to 2nd act and play sound and in 2nd act if I press the button it should stop the sound and goes to 3rd activity and play. I put the codes accordingly, it stop 2nd act sound and goes to 3rd act but 3rd act sound does not play. I need your help.

  9. hi, could you pull this sample one step further by resetting the app to use mediafiles in our phone?
    when we download a track or mp3 it actually has an album picture .. how we can grab that kind of infors from a media file ?

  10. Your videos are always so helpful! Thank You!

  11. it saying that the file name must end with .xml or .png

  12. Hi
    I have a problem.
    When I want to put a sound file in the raw "folder" Android studio always regognieses it as a Text file.
    can someone help me?

  13. what if i want to stop the music mid play and press start to start from the beginning?

  14. Helpful always very nice

  15. whenever I click play the app crashes. Can anyone help me with this?

  16. thanks its good tutorial.. but how make play sound button in page 1 and stop sound button in page 2? stop button will stop sound from play button page 1, pls help

  17. how did you put media player and emulator side by side , are you using genymotion??plzz tell me i am a beginner

  18. Thank you for your excellent and simple explanation

  19. thank you … can we add multiple pause buttons instead of one at specified times in the file.

  20. awesome bro love you

  21. You are GOD sir. How did you learn to code?

  22. You made Coding so simple! Sir we love you..

  23. Bhai subscriber ke lia accha idea hai apna apna no do whatsup group banata hu jisse sab log 1 dusre ka like share and subscribe karenge mera 9820517985 hai believe na ho to msg kar sakte ho☺👌

  24. Thanks for the tutorial
    Do not tell me how to make the button "Next song" " Back song"&&&

  25. sprich lieber deutsch dein English hört sich nicht so toll an.

  26. Would you please make a tutorial about recording

  27. All My Android Class Tasks Covered By You 😁💕💕💕
    Thanks Very Much 💕👌

  28. Thank for your tutorial.
    Hi, i have a problem and i don't know why.
    i do the same with you but when i run, app was cracked.
    Can you help me?

  29. If you leave your activity and go to other apps, how to continue playing media in background, can you make a video about that?

  30. Did you make any video showing how to play multiple sounds on click of multiple buttons using mediaplayer? Actually I need to learn it.

  31. Cool. It also seems a completion listener callback is only available here, as opposed to SoundPool.

  32. In just 7.5 minutes you actually showed the basics of MediaPlayer, carring not only about "how to make it work", but about releasing resources as well. That's probably one of the most useful tutorials on Android development I've ever seen. Exactly what I needed to get started.

  33. I can't use this code

    R.raw.filename

    I am having an error, saying that cannot resolve raw.

    I already add Android Resource Directory
    then choose raw
    then copy and paste the file in raw folder

    still I get an error.

  34. You didn't say that the file name should be in lower case 🙁

  35. Im getting "Problem while parsing the package" problem. Please help me.

  36. I've been struggling with SoundPool as it doesn't play music for longer than 5 sec. Now I know how to use Mediaplayer instead, thank you!

  37. can we have multiple audio tracks with next/prev btns and seek bar.plzzzzzzzzz.

  38. Thank you! That was helpful man!

  39. Thx man… BTW I like GERMAN Accent 🌚

  40. Really nice videos, they are very helpful. One question Why do you always choose Linear layout ?

  41. if the mediaplayer already exists and the song is playing why do we need the if statement to check if there is mediaplayer

  42. Hello this tutorial is really great. Please I need your help, how can I add slow event for any videos to play in slow motion?

  43. give me sound file

  44. Hey can you please tell me how play media file during call and mute mic?

  45. Hi, great video!
    I have question: In your code, what will happen if the user press Play button while the media is playing? player.start() method is outside the if statement in your play() method and I think it will try to start the song again.

  46. Is there a way to set the mediaPlayer to replay the previous iteration?

  47. how to do this with 20 different audio files in the same layout? using id on the button?

  48. Can we integrate a file manager inside the app so the user with a press of a button opes up the file manager, browses and picks an audio file from the folders to be played by the MediaPlayer?

  49. Ty man, this is awesome

  50. When trying to play the sound, I get this E/MediaPlayer: Should have subtitle controller already set, Any help please

  51. you are the best

  52. Awesome video 🙂

  53. Have you tried setting PlayBacKParams?

  54. Sir after raw name i write music name but this is not show and get error

  55. you are the best. thank you man

  56. If we stop music player multiple times, isn't that going to cause NullPointerException, because MediaPlayer.create() method can return null? And if i am right, is there a way around this?

  57. Thanks for the video. It was very helpful!

  58. Can you do a tutorial for requesting and releasing AudioFocus?

  59. Eror:method stop in class mainactivity
    Required View
    Found no arguments
    Dll

  60. Hi, thanks for your videos, can you please make a video about How to Play a Sound File list Using exoplayer? thanks

  61. Thank you very much! Clear and simple, just what I needed

  62. This is useless. You should teach people to load MediaFiles and do this actions in a Service Class.

  63. could you please give me the link for the next lesson (the services)

  64. HI, I want to thank you for this insightful and good video. Thanks to you I just built my first App. I am an English teacher and I want to put tracks in an App. Can you also show (if you haven't done yet) switching between pages. EG

  65. mega interessant, danke und thank you ;o)

  66. cool ist nebenbei das man dem Button die Click-Funktion schon im xml-File zuweisen kann, dann braucht man nicht "umständlich" den ClickListener erstellen und zuweisen (also fast wie in C# und WPF)

  67. Is there any problem if we use Stop method directly?

  68. hello
    bro my mp3 file has saved as text file can u help me to change the file pls !!!!

  69. Dam i love your WORK BRO
    You Great at this THINGS
    LOVE YOU

  70. The channel is my main support for my android course in school

  71. When i press the play button i got no sound! Please Help Me!

  72. Your tutorial is great. Hoping you can help me get past one last hurdle. With this code I'm trying to play a 5 min song. It stops at almost exactly 1 min.

  73. @Coding in Flow Great tutorial! How can I use the speakers on the back of the smartphone?

  74. You are the best teacher I have ever seen.

  75. Nothing happens when i click 'play' button, but 'stop' toast works fine

  76. hello, why do you change constraint to relative layout?

  77. Super Bro nice video
    And you can add the video coding Bro????

  78. Thank you
    very much.

  79. i record my my own music, i create regular sound files, mp3 and wav- is there no simple way to just copy the files to my phone(which I can do now) and play them with the "music" app that came with my phone ? – I cant believe how complicated this is. the "music" app does not see or scan media files I moved onto my phone. I dont want my media files uploaded to google or spotify I just want my phone to act like an mp3 player for local files. Help? I don't want to write code to do this either

Comment here