2017-05-17 43 views
0

这是我的代码:java.lang.IllegalStateException在MediaPlayer的

final MediaPlayer[] threeSound = new MediaPlayer[1]; 
threeSound[0] = new MediaPlayer(); 
final CountDownTimer playThreeSound = new CountDownTimer(1000, 1) { 
    boolean timerStarted = false; 
    @Override 
    public void onTick(long millisUntilFinished) { 
     torgText.setText("3..."); 
     if (!timerStarted) { 
      timerStarted = true; 
      threeSound[0] = MediaPlayer.create(PlayActivity.this, R.raw.three); 
      try { 
       threeSound[0].prepare(); 
       threeSound[0].start(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
       Log.e("IOE", "Something went wrong"); 
      } 
     } 
    } 

    @Override 
    public void onFinish() { 
     if (threeSound[0].isPlaying()) { 
      threeSound[0].stop(); 
     } 
     playTwoSound.start(); 
    } 
}; 

它抛出IllegalStateException异常。这些是日志:

FATAL EXCEPTION: main 
Process: testapplication.android.com.guesstune_v2, PID: 3641 
java.lang.IllegalStateException 
at android.media.MediaPlayer._prepare(Native Method) 
at android.media.MediaPlayer.prepare(MediaPlayer.java:1351) 
at testapplication.android.com.guesstune_v2.PlayActivity$6.onTick(PlayActivity.java:316) 
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:133) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:145) 
at android.app.ActivityThread.main(ActivityThread.java:7007) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 

准备MediaPlayer有什么问题?我应该添加什么代码?我是一个新手,对于一个可能愚蠢的问题和糟糕的英语抱歉。

回答

0

的文档MediaPlayer状态:

MediaPlayer create (Context context, int resid) 方便的方法来创建一个给定的资源ID的MediaPlayer。成功时,prepare()已经被调用,不能再次调用。

https://developer.android.com/reference/android/media/MediaPlayer.html#create(android.content.Context, int)

所以,你的出现IllegalStateException因为prepare()要求MediaPlayer是在任何一个初始化停止状态,但是当create(Context context, int resid)被调用时,它调用prepare()导致MediaPlayer的是编写的状态,当调用prepare()时,不应该有这种状态。

总之:删除prepare()呼叫和IllegalStateException应该不再发生。

完整的状态图和有效状态列表显示在文档中。

相关问题