Android MediaPlayer控制進度播放音頻
本文簡單介紹MediaPlayer獲取播放進度和設置進度播放。
1、獲取音頻文件的播放時間總長度
//返回的是int的毫秒級數據
/**
* Gets the duration of the file.
*
* @return the duration in milliseconds, if no duration is available
* (for example, if streaming live content), -1 is returned.
*/
public int getDuration();
2、獲取音頻文件的播放時間當前時間值
//返回的是int的毫秒級數據
/**
* Gets the current playback position.
*
* @return the current position in milliseconds
*/
public int getCurrentPosition();
3、設置進度播放音頻
//設置之前的毫秒數
seekTo(int msec)
//設置之前的毫秒數和播放模式
seekTo(long msec,int mode)
mode的值有如下選擇:
public static final int SEEK_PREVIOUS_SYNC = 0x00; //同步播放模式,會往前一點播放,默認模式
public static final int SEEK_NEXT_SYNC = 0x01; //同步播放模式,會後一點播放
public static final int SEEK_CLOSEST_SYNC = 0x02; //同步播放模式,精確播放
public static final int SEEK_CLOSEST = 0x03; //異步播放模式,精確播放
關於SeekTo要注意的地方:
1、首次播放在線音頻要在onPrepared回調中執行seekTo
mOnlineMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
if (mOnlineMediaPlayer != null) {
mp.seekTo(30 * 1000, MediaPlayer.SEEK_CLOSEST); // 30秒的位置播放
mp.start();
}
}
});
2、如果是暫停狀態,再調seekTo,可以直接調
public void resumeOnlineMedia() {
if (mOnlineMediaPlayer != null) {
try {
if (!mOnlineMediaPlayer.isPlaying()) {
mOnlineMediaPlayer.seekTo(30 * 1000, MediaPlayer.SEEK_CLOSEST);
mOnlineMediaPlayer.start();
}
} catch (IllegalStateException e) {
Log.e(TAG, "resumeOnlineMedia error=" + e.getMessage());
}
}
}