Search code examples
androidmedia-player

Android MediaPlayer Question


public class PlayAudio extends BroadcastReceiver{
       private Context mContext;
        MediaPlayer mp;

@Override
public void onReceive(Context context, Intent intent) {

    mContext = context;
    mIntent = intent;
    playSound("sound.mp3");

    }

       private void playSound(String file){
           mp = MediaPlayer.create(mContext, Uri.parse("file://"+file));
           if (mp.isPlaying())
           {
              mp.stop();
           }

                mp.setLooping(true);
                try {
                   mp.prepare();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
                mp.start();
        }

}

I am getting an error when i check if mp is playing. How can i check if MediaPlayer(mp) is playing so that i can stop it?


Solution

  • First a bit of confusion in the above code In the above code new instance of media player will get created each time you call playsound() what you need to do is instantiate mp only once in oncreate() of playaudio class and use it repeatedly.

    Also if you use create to instantiate mediaplayer you prepare gets called internally you should not call it again.http://developer.android.com/reference/android/media/MediaPlayer.html#create(android.content.Context, android.net.Uri)

    Check if mp is null after you do create to verify if mediaplayer instance was created successfully.