2015-05-09 56 views
0

我有這個代碼奇怪的問題,雖然錯誤很簡單我不明白它。MediaPlayer不從其他類的方法調用

類具有MediaPlayer的聲音和方法:

public class Sounds { 

private MediaPlayer stone; 
private MediaPlayer gong; 

public Sounds(Context con, int stoneSound, int gongSound){ 
    this.stone = MediaPlayer.create(con, stoneSound); 
    this.gong = MediaPlayer.create(con, gongSound); 
} 

public void ActivateStone(){ 
    MediaPlayer auxStone = this.stone; 
    auxStone.start(); //THIS IS THE LINE 19 of "Sounds.java:19" log error 
    auxStone.setOnCompletionListener(new OnCompletionListener() { 
     @Override 
     public void onCompletion(MediaPlayer mp) { 
      mp.release(); 
     } 
    }); 
} 

public void ActivateGong(){ 
    MediaPlayer auxGong = this.gong; 
    auxGong.start(); 
    auxGong.setOnCompletionListener(new OnCompletionListener() { 
     @Override 
     public void onCompletion(MediaPlayer mp) { 
      mp.release(); 
     } 
    }); 
} 

現在調用該方法使用的「聲音」每間隔

public void run() { 
    while (!stoped) { 
     try { 
      this.sleep(interval); 
      if (stones == mode || stones == (mode * 2)) { 
       sounds.ActivateGong(); 
      } else { 
       sounds.ActivateStone(); //THIS IS THE LINE 32 in "Counter.java:32" log error 
      } 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
     stones += 1; 
     handler.setHcron(stones + ""); 
     handler.act(); 
    } 
} 

的聲音只能播放一次,然後該應用程序拋出線程與此日誌的例外:

05-09 19:10:52.306: E/AndroidRuntime(479): FATAL EXCEPTION: Thread-9448 
05-09 19:10:52.306: E/AndroidRuntime(479): Process: contador.piedras.jugger, PID: 479 
05-09 19:10:52.306: E/AndroidRuntime(479): java.lang.IllegalStateException 
05-09 19:10:52.306: E/AndroidRuntime(479): at android.media.MediaPlayer._start(Native Method) 
05-09 19:10:52.306: E/AndroidRuntime(479): at android.media.MediaPlayer.start(MediaPlayer.java:1074) 
05-09 19:10:52.306: E/AndroidRuntime(479): at contador.piedras.jugger.Sounds.ActivateStone(Sounds.java:19) 
05-09 19:10:52.306: E/AndroidRuntime(479): at contador.piedras.jugger.Counter.run(Counter.java:32) 

回答

0

也許你應該嘗試添加同步,它可以是c線程的澳洲英語:

synchronized (auxStone) { 
     auxStone.start(); //THIS IS THE LINE 19 of "Sounds.java:19" log error 
     auxStone.setOnCompletionListener(new OnCompletionListener() { 
      @Override 
      public void onCompletion(MediaPlayer mp) { 
       mp.release(); 
      } 
     }); 
    } 

編輯:如文檔聲明,這個方法:拋出: IllegalStateException - 如果它被稱爲處於無效狀態。所以你需要檢查它的播放if(!auxStone.isPlaying())

+0

仍然沒有工作,相同的錯誤日誌。 –

+0

@CristianCañadas,我已經更新了答案 –