0

我有一个非常奇怪的错误,我无法弄清楚发生了什么。在我的代码中,我通过 SoundsClass 使用媒体播放器,如下所示:

public class SoundsClass {

private int sound;
private Context mContext;
public SoundsClass(int sound, Context mContext) {
    this.sound=sound;
    this.mContext=mContext;
}

    public void clickOnAndroid() {

      switch(this.sound) {
      case R.raw.sound1:
        MediaPlayer mediaPlayer = MediaPlayer.create(mContext, R.raw.sound1);
        mediaPlayer.start();
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
          public void onCompletion(MediaPlayer mp) {
              mp.release();
          }
      });

      break;
      case R.raw.sound2:

       mediaPlayer = MediaPlayer.create(mContext, R.raw.sound2);
       mediaPlayer.start();
     mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
         public void onCompletion(MediaPlayer mp) {
             mp.release();
         }
     });
    break;
    case R.raw.sound3:
       mediaPlayer = MediaPlayer.create(mContext, R.raw.sound3);
       mediaPlayer.start();
       mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
          public void onCompletion(MediaPlayer mp) {
              mp.release();
          }
      });
      break;
      }


    }
}

所以,我在我的主要活动中使用这个类,如下所示:

    new SoundsClass(R.raw.sound1, getBaseContext()).clickOnAndroid();

在此活动的 2 个地方它工作正常,但第三个给出 NullPointerException,由 SoundsClass 中的行指向:

mediaPlayer.start();

知道为什么吗?我是否以错误的方式使用 MediaPlayer?

Logcat 是:

java.lang.NullPointerException
at com.testingapp.app.SoundsClass.clickOnAndroid(SoundsClass.java:42)
at com.testingapp.app.MainActivity$2.onClick(MainActivity.java:147)
at android.view.View.performClick(View.java:2485)
at android.view.View$PerformClick.run(View.java:9080)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)

也许我应该补充一点,我经常调用这个 SoundsClass,中间没有或几乎没有停顿。有时我会得到:

bufferCount is to small and increased to 12.
4

2 回答 2

3

http://developer.android.com/reference/android/media/MediaPlayer.html#create(android.content.Context,%20android.net.Uri,%20android.view.SurfaceHolder )

如果创建失败,MediaPlayer.create 调用将返回 null。如果它找不到指定的媒体或媒体是无效格式,则会出现这种情况。

于 2012-07-09T18:23:01.393 回答
3

这对我有用:

mediaPlayer = MediaPlayer.create(mContext, R.raw.sound1);
while(mediaPlayer == null) {
      mediaPlayer = MediaPlayer.create(mContext, R.raw.sound1);
}
于 2014-09-25T16:14:28.103 回答