9. Android MediaPlayer Example | Adding Music to Our Apps

This entry is part 9 of 40 in the series Android Basics

Using MediaPlayer for AndroidUsing Android’s MediaPlayer to Add Sound:

This Android MediaPlayer example we will add some music to our splash activity, and learn about the scope of variables. If you are just looking for Android example of the MediaPlayer Class, this tutorial be a perfect example. However, if you have no experience with Android development and no programming experience, but you want to develop your own apps, I’d recommend starting at the first lesson in this series. If you don’t have any sounds to play around with, you can download some of ours within the resources section at the bottom of this example. Let’s get to it!


Android MediaPlayer Video Example



MediaPlayer Example

All applications should be required to include music and cool sounds. Music is what makes the world go round, right? Well, be thankful, because this awesome tutorial will teach you all about the Android MediaPlayer class. The MediaPlayer class is exactly what we need to handle playing music within our Android applications. Before we jump into the example, I just want to specify that there are two ways to play music and sounds within Android. For music, such as music playing in the background of a game, music that needs to be looped, or any type of music that is generally longer than a second, you will want to use MediaPlayer. For sounds or sound effects, such as, the “Phew”ing of a spaceship shooting bullets, you will want to use SoundPool. We cover SoundPool in a future tutorial. This tutorial is for MediaPlayer.

Ok, now that we have a clear understanding on what we are trying to do (play some music for our SplashScreen activity), let’s see an example of how this is done. I’ll explain the details in a moment.

MediaPlayer music = MediaPlayer.create(YourClassName.this, R.raw.logo_music);
music.start();

As you can see, it’s pretty straight-forward. First we need to create a “raw” folder within the resources of our Android project. This folder is where we will store all of our sounds, music, and other raw resources. Again, make sure the files you include in this folder are all lowercase, otherwise we will have a build error and our R.java file will blow up.

Android is a bit iffy when it comes to file types of audio files. For example, some .WAV files will work and others won’t. The general consensus recommends using only .OGG files for your Android applications, but if you ever plan on releasing your game on iOS, or some other platform, feel free to use .MP3 files. Just avoid anything that isn’t on this list from the Android developer’s page.

Http://developers.android.com/dfadsfasdfasdfas

Here’s a video I created on how to convert audio file with Terminal (if you are running on a Linux based system like Mac, or Ubuntu): http://www.youtube.com/mybringback

Okay, now that we have all the basics down, lets look at the code:

MediaPlayer music = MediaPlayer.create(YourClassName.this, R.raw.logo_music);
music.start();

We just create a media player object called music, by using the create method and passing in the context of the activity we want to use to handle the music and the reference id of the song we threw in our “raw” folder. After we have established the setup of our music, we can control the MediaPlayer object with methods such as prepare, start, stop, pause, etc. Pretty simple right? Well there are some things that we want to consider when we are working with the MediaPlayer class and we will get to that a little bit later. First, we need to understand the concept of scope when working with a object oriented programming language like Java.

The best way to explain what scope in Java is by an example. Let’s pretend we have a room full of people and various devices to play music, such as a bunch of stereos. Let’s look at this in code:

public class Room extends Activity{
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.main);
		you();
		yourFriend();
		restOfTheRoom();
		}
	
	public void you(){
		MediaPlayer yourStereo = MediaPlayer.create(Room.this, R.raw.awesome_song);
		yourStereo.start();
		}
	public void yourFriend(){
		// he/she can't control your music (yourStereo) 
		//but he or she can play music on their stereo
		MediaPlayer friendsStereo = MediaPlayer.create(Room.this, R.raw.awesome_song2);
		friendsStereo.start();
		yourStereo.stop(); // your friend can't do this because your stereo
									//isn't in his scope
		}
	public void restOfTheRoom(){
		// they can't control your music (yourStereo)
		//but they can play music on their stereo and
		//even label it as yourStereo
		MediaPlayer yourStereo = MediaPlayer.create(Room.this, R.raw.awesome_song3);
		yourStereo.start();
		
		}
	
	}

This room would be quite annoying to be in. Three different stereos all blaring three different songs, and no one can control the other person’s stereo. The rest of the room even named their stereo the same as yours. This could get quite confusing if you are trying to just shut down your stereo since you can’t just call “yourStereo.stop()”. This is where scope comes in. Each stereo can only be controlled within the scope of the method that was established in. So, only within the “you()” method could you control your stereo, and only within “yourFriend()” method you can control your “friendsStereo”. Wouldn’t it be easier if we just had one stereo in the room that everyone could control? It definitely would! So let’s set a stereo to be within the scope of the room, so everyone can control it.

public class Room extends Activity{
	
	MediaPlayer stereo;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.main);
		you();
		yourFriend();
		restOfTheRoom();
		}
	
	public void you(){
		stereo = MediaPlayer.create(Room.this, R.raw.awesome_music);
		}
	public void yourFriend(){
		stereo.start();
		}
	public void restOfTheRoom(){
		stereo.stop();
		}
	
	}

Isn’t better if everyone works as a team? Now the whole room knows there is a MediaPlayer stereo that everyone has access to. You will insert the CD you want the stereo to play, your friend will hit the play button, and then the rest of the room must not like your music because they stop it right away. This activity is completely pointless, but it should give you some insight on what scope is. There is only one stereo everyone can control, instead everyone going buck-wild with music.

Hopefully, I didn’t confuse you with all that “scope business”, because we still have some stuff to learn about the MediaPlayer class. Learning about scope is essential for this MediaPlayer example because now we can create one stereo for our activity, play it within onResume() method, and stop it within the onPause() method. That way if the user exits our app, the music will stop, when they come back to our application the music will continue playing. I’ll show an example of this at the end of this section, but now let’s look at some of the things we can (and should do) when working with MediaPlayer objects.


Course Navigation:

Previous Lesson
Next Lesson

Author: trav

I'm just an average guy that love programming.

Share This Post On

16 Comments

  1. Quick question. How can I play different audio files based on current view text on display? In other words, if I have 20 or more audio files and I want to play a specific file according to what is displayed on the screen, how can I accomplish that.

    Thank you in advance.

    Post a Reply
    • for multiple sounds I would look into the SoundPool class a bit more. Hope that helps?!?!?

      Post a Reply
  2. why you no give me music files :( I dont have any

    Post a Reply
  3. I’ve tried to do EXACTLY like Travis bur somehow I fail time after time. This time I get a force close directly after the splash screen. If I remove the “logoMusic.release();” the error disappears, however I feel like that’s not really the best solution. Anyone care to take a look at my code and point out what I’m doing wrong?

    package com.slotigork.thebasics;

    import android.app.Activity;
    import android.content.Intent;
    import android.media.MediaPlayer;
    import android.os.Bundle;

    public class main extends Activity {
    /** Called when the activity is first created. */
    MediaPlayer logoMusic;

    @Override
    public void onCreate(Bundle TravisIsAwesome) {
    super.onCreate(TravisIsAwesome);
    setContentView(R.layout.splash);

    MediaPlayer logoMusic = MediaPlayer.create(main.this, R.raw.sounds);
    logoMusic.start();

    Thread logoTimer = new Thread(){
    public void run(){
    try{
    sleep(2000);
    Intent menuIntent = new Intent(“com.slotigork.thebasics.MENU”);
    startActivity(menuIntent);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    finally{
    finish();
    }
    }
    };
    logoTimer.start();
    }

    @Override
    protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    logoMusic.release();
    }
    }

    Post a Reply
    • make sure this part looks like this

      @Override
      public void onCreate(Bundle Iloveyouangie) {
      super.onCreate(Iloveyouangie);
      setContentView(R.layout.splash);

      here-> logoMusic = MediaPlayer.create(main.this, R.raw.splash_sound);
      logoMusic.start();

      Thread logoTimer = new Thread(){
      public void run(){
      try{
      cause you forgot to delete the MediaPlayer before logoMusic=MediaPlayer

      Post a Reply
  4. Hello, the tutorials are awesome, but I am having some issues with this one. My app keeps crashing after the splash screen. The strange thing is that everything works properly if I dont have the on pause override, but as soon as I add the override, the application crashes. I have no idea how to fix this, any ideas?

    Thank you,
    Karla

    Post a Reply
  5. @Max right below your onCreate make sure it looks like this..

    @Override
    public void onCreate(Bundle Iloveyouangie) {
    super.onCreate(Iloveyouangie);
    setContentView(R.layout.splash);

    logoMusic = MediaPlayer.create(main.this, R.raw.splash_sound);
    logoMusic.start();

    Thread logoTimer = new Thread(){
    public void run(){
    try{

    you might have forgot to delete MediaPlayer before logoMusic = MediaPlayer

    Post a Reply
  6. Same issues here get an error, when i // the media coding it works great

    package com.myBringback.theBasics;

    import android.app.Activity;
    import android.content.Intent;
    import android.media.MediaPlayer;
    import android.os.Bundle;

    public class main extends Activity {
    /** Called when the activity is first created. */

    MediaPlayer logoMusic;

    @Override
    public void onCreate(Bundle Iloveyouangie) {
    super.onCreate(Iloveyouangie);
    setContentView(R.layout.splash);

    logoMusic = MediaPlayer.create(main.this, R.raw.army_song);
    logoMusic.start();

    Thread logoTimer = new Thread() {
    public void run() {
    try {
    sleep(5000);
    Intent menuIntent = new Intent(“com.myBringback.theBasics.MENU”);
    startActivity(menuIntent);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } finally {
    finish();
    }
    }
    };
    logoTimer.start();
    }

    @Override
    protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    logoMusic.release();
    }
    }

    Post a Reply
  7. Sir you are awesome. Really awesome. Also I failed so many times, When I checked comments I realised I didn’t deleted MediaPlayer part too :D

    Post a Reply
  8. Thanks Westley!!!!!! My program was crashing too, until I deleted the “MediaPlayer” before logoMusic.

    Post a Reply
  9. Hey there Travis, hows it going..

    I have been watching your tutorials and practicing accordingly on Eclipse, but i’m kind of stuck.

    In Tutorial 17 titled ‘Android Application Development Tutorial – 17 – Adding Music with MediaPlayer’ I have followed exactly as you guided, but when i launch my avd the sound clip doesnt play, instead the splash comes… sits for 5 seconds and the next screen launches..

    I have googled a lot but still can’t resolve this. Please help me out here.. Thanks.. and Keep Up the good work.

    Post a Reply
  10. HiTravis, how are you?

    I’m trying to use the MediaPlayer this way:
    AudioPlayer = MediaPlayer.create (this, R.raw.config);
    audioPlayer.start ();

    But always my app pauses and opens the playlist screen of android.
    I wanted a way to disable this screen playlist and that my application had not entered paused.
    Can you help me?
    Thank you!

    Post a Reply
  11. Thank you for the tutorial.

    Could you please help with streaming audio link? I tried above code and was no help.

    Thank you

    Post a Reply
  12. Posted my code, forgot to state my issue.
    No sound.

    Post a Reply
    • Hey Mark, I looked over your code, and it looks pretty good. Does the console say anything when you run the application?

      You may want to double check the file to is ok, by that I mean making sure it’s and .ogg, or a .mp3.
      You also want to make sure the sound plays right away and there isn’t 2 seconds of blank audio before the actual sound plays within the audio file.

      Post a Reply

Submit a Comment

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>