2017-05-17 45 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應該不再發生。

完整的狀態圖和有效狀態列表顯示在文檔中。

相關問題