2012-07-20 62 views
2

試圖在我的整個應用程序的很多地方使用的MediaPlayer時減少的行數,我繼承的MediaPlayer,並在構造函數中我調用相同的3條線,每次我需要播放媒體文件重複:MediaPlayer.start()不能在構造函數被調用?

public MyMediaPlayer(Context context, int resid) { 
    create(context, resid); 
    setOnCompletionListener(this); 
    start();   
} 

所以這不是那3行,我只把這個在來電者:

new MyMediaPlayer(this, R.raw.happybirthday); 

它編譯和構建,甚至運行,但媒體文件將不會出於某種原因發揮。

我檢查了logcat的,發現:

07-19 20:00:51.124: E/MediaPlayer(16517): start called in state 1 
07-19 20:00:51.124: E/MediaPlayer(16517): error (-38, 0) 

什麼這些錯誤是什麼意思?

我錯過了什麼?

BTW,onCompletion()被調用,運行良好。

回答

4

含義:遵守的MediaPlayer的狀態圖,你不能調用start()在每一個國家。下面是狀態圖,你是不是調用的準備,PlaybackCompleted或暫停啓動。

即使你正在做它在正確的狀態,稱它的onCreate或任何其他初始化方法是直接不是一個好的做法,因爲這些方法被保留用於初始化佈局和應用。

你可以做的onCreate(),或在onStart()下列操作之一,以確保他們完成後播放。

// delaying play until after all application initialization is done 
    findViewById(R.id.main_page_layout).post(new Runnable() { 
     public void run() { 
     //play your music here 
     } 
    }); 

enter image description here

+0

歡迎您。希望能幫助到你。 – Erol 2012-07-20 00:44:26