Jim Thornton Jim Thornton - 6 months ago 10
Android Question

Sound file won't play when using MediaPlayer

I'm trying to create a method for my class

soundBuzzer()
that when called plays an mp3 file which contains a 2s buzzer sound. I've been searching for a long time but anything I've tried isn't working. The closest thing that I could find that would not generate syntax errors in the code is:

// function to play buzzer_2s.mp3
public void soundBuzzer() {
MediaPlayer mp = MediaPlayer.create(null, R.raw.buzzer_2s);
mp.start();

}


Can someone please tell me what is wrong. When I run the above method my app crashes. I've tried looking at the errors in catlog but they don't make sense to me:

12-26 14:50:57.491: E/AndroidRuntime(16520): FATAL EXCEPTION: main
12-26 14:50:57.491: E/AndroidRuntime(16520): java.lang.NullPointerException
12-26 14:50:57.491: E/AndroidRuntime(16520): at android.media.MediaPlayer.create(MediaPlayer.java:731)
12-26 14:50:57.491: E/AndroidRuntime(16520): at com.example.ultimatescoreclock.ClockTimer.soundBuzzer(ClockTimer.java:108)
12-26 14:50:57.491: E/AndroidRuntime(16520): at com.example.ultimatescoreclock.ClockTimer.onFinish(ClockTimer.java:40)
12-26 14:50:57.491: E/AndroidRuntime(16520): at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:118)
12-26 14:50:57.491: E/AndroidRuntime(16520): at android.os.Handler.dispatchMessage(Handler.java:99)
12-26 14:50:57.491: E/AndroidRuntime(16520): at android.os.Looper.loop(Looper.java:137)
12-26 14:50:57.491: E/AndroidRuntime(16520): at android.app.ActivityThread.main(ActivityThread.java:4424)
12-26 14:50:57.491: E/AndroidRuntime(16520): at java.lang.reflect.Method.invokeNative(Native Method)
12-26 14:50:57.491: E/AndroidRuntime(16520): at java.lang.reflect.Method.invoke(Method.java:511)
12-26 14:50:57.491: E/AndroidRuntime(16520): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
12-26 14:50:57.491: E/AndroidRuntime(16520): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
12-26 14:50:57.491: E/AndroidRuntime(16520): at dalvik.system.NativeStart.main(Native Method)`

Answer

You need to give MediaPlayer.create() a Context instead of a null. If you're doing this from an Activity class, it's easy:

MediaPlayer mp = MediaPlayer.create(this, R.raw.buzzer2s);

If you're calling it from a different class, you'll need to pass the context to soundBuzzer() in some way.

public void soundBuzzer(Context context)
{
    MediaPlayer mp = MediaPlayer.create(context, R.raw.buzzer2s);
    mp.start();
}

If you're not sure what a Context is, you might want to read up a bit. Demystifying Context in Android might be a good one to start with.

Comments