播放視訊檔案其實并不比播放音頻檔案複雜,主要是使用 VideoView類來實作的。這個類将視訊的顯示和控制集于一身,使得我們僅僅借助它就可以完成一個簡易的視訊播放器。
最近在做視訊,遇到這麼個需求,播放視訊中途退出時候記錄目前播放的時間,播放視訊,最簡單的就是VideoView了,但是,官方并沒有提供擷取目前播放時間的方法,隻有個getCurrentPosition()方法,可以擷取目前播放的進度。
一般用VideoView時候都會配合MediaController來使用,MediaController就帶有顯示目前時間和總時間的功能。于是我就通過檢視MediaController的源碼,找到了如何實作VideoView擷取目前時間的方法。
//将長度轉換為時間
//将長度轉換為時間
StringBuilder mFormatBuilder = new StringBuilder();
Formatter mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
//将長度轉換為時間
private String stringForTime(int timeMs) {
int totalSeconds = timeMs / 1000;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
mFormatBuilder.setLength(0);
if (hours > 0) {
return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
}
這個就是擷取目前時間的方法了,這樣就可以通過videoview擷取目前播放的時間了
String play_time = stringForTime(binding.videoView.getCurrentPosition());
Log.e("播放時間轉換後目前播放時間是------", play_time);
String play_sum_time = stringForTime(binding.videoView.getDuration());
Log.e("播放時間總時長是------", play_sum_time);
參考連結