2013-10-08 22 views
0

我的ViewPager中有兩個片段。第一個片段列出所有可用的mp3文件,第二個片段實際播放(實現MediaPlayer邏輯)。如何getDuration()有/沒有MediaPlayer

在我的第一個片段中,我想列出mp3文件的持續時間。因爲所有的mp3文件都是從媒體文件加載的,我怎樣才能得到它們的文件持續時間?

我試過如下:

初始聲明:

MediaPlayer mediaPlayer; 

代碼實現:

mediaPlayer.setDataSource(mp3URL); 
totalDuration = utils.milliSecondsToTimer(mediaPlayer.getDuration()); 

MilliSecondsToTimermilliseconds字符串轉換爲3:40格式。

最終應用:

duration.setText(totalDuration); 

這樣做給了我以下錯誤:

10-08 03:38:03.341: E/MediaPlayer(2586): Attempt to call getDuration without a valid mediaplayer 
10-08 03:38:03.361: E/MediaPlayer(2586): error (-38, 0) 
10-08 03:38:03.461: E/MediaPlayer(2586): Error (-38,0) 

如何我剛剛從該網址提取總時長?請幫助。

回答

0

您可能在完全加載文件之前調用getDuration。看看這個問題的解決方案是否適合你。

final VideoView video = (VideoView) findViewById(R.id.videoplayer); 
      final MediaController controller = new MediaController(this); 

      video.setVideoURI(Uri.parse(getIntent().getStringExtra("url"))); 
      video.setMediaController(controller); 
      controller.setMediaPlayer(video); 
      video.setOnPreparedListener(new OnPreparedListener() { 

        public void onPrepared(MediaPlayer mp) { 
         int duration = video.getDuration(); 
         video.requestFocus(); 
         video.start(); 
         controller.show(); 

        } 
       }); 
+0

如何完全加載文件?我打電話給onPreparedListener? –

+0

是的,你也有。請看我的答案! –

0

您正準備在準備工作完成之前獲得mediaPlayer.getDuration()。只有在準備完成後,才能使用setOnPreparedListener()方法設置準備偵聽器並調用getDuration()方法。

mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { 
    public void onPrepared(MediaPlayer mp) { 
     totalDuration = utils.milliSecondsToTimer(mediaPlayer.getDuration()); 
    } 
}); 
+0

我得到'IllegalStateException' - attachNewPlayer在狀態2錯誤中調用! –

相關問題