0
我需要一個Android應用程序能夠從時間t1播放視頻到其他時間t2。基本上,這個視頻是我應用中的一種「精靈」(它是一個基於H.264編碼的.mp4視頻h264)。在Android兩次播放視頻
所以,我試了下面。一個按鈕「next」在t1和t2之間播放視頻。要檢查視頻是否已到達t2,我每20毫秒使用一個帶有postDelayed調用的處理程序。如果視頻當前位置大於t2,我停止播放視頻。否則,我會在20ms內再次檢查。
但它不起作用。由於我不明白的原因,我在postDelayed中讀取的視頻當前位置突然從一段時間到幾秒鐘後。在我的屏幕上,視頻正常播放。
某些代碼:
// MainActivity
// setting up the video
vidView = (VideoView) findViewById(R.id.myVid);
vidView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/raw/myvid"));
// wiring up Bt next
Button nextBt = (Button) findViewById(R.id.next);
nextBt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
playVideo();
}
});
而的playVideo方法:
private void playVideo() {
// t1 and t2 are defined within MainActivity class
t1 = (int) (Math.random() * (80000));
t2 = t1 + (int) (Math.random() * (5000));
// we start at t1
vidView.seekTo(t1);
// We check video position in 20 ms
mHandler.postDelayed(new Runnable() {
public void run() {
int currentTime = vidView.getCurrentPosition();
Log.i("currentTime", String.valueOf(currentTime));
Log.i("T2", String.valueOf(t2));
// Ok, we can pause the video
if(currentTime > t2 - 20) {
vidView.pause();
}
// We check again in 20ms
else {
mHandler.postDelayed(this, 20);
}
}
}, 20);
vidView.start();
}
的logcat的給我(在這個例子中,T1 = 47286和T2 = 51478)
10-14 11:31:56.603: I/currentTime(3359): 47286 // first call to postDelayed, fine
10-14 11:31:56.603: I/T2(3359): 51478
10-14 11:31:56.623: I/currentTime(3359): 47286 // second call to postDelayed, still ok
10-14 11:31:56.623: I/T2(3359): 51478
10-14 11:31:56.653: I/currentTime(3359): 50000 // What? How the video current time can already be 3 seconds later?
10-14 11:31:56.653: I/T2(3359): 51478
你能告訴我我的代碼有什麼問題嗎? 謝謝!
我希望它儘可能準確。您的想法存在的問題是,視頻需要時間才能達到其搜索點並開始播放。這些時間取決於設備和視頻編碼。我想每20ms做一次檢查(不是在所有的視頻播放過程中,而是在最後一秒的播放過程中)會更準確。 – JuCachalot
在視頻中添加一個'onPreparedListener',只發布處理器'onPrepared' - 這將消除開始時間問題。 'getCurrentPosition'不保證是準確的,當然每20ms調用它似乎對我來說不是一個好主意。 –
我試過了你的想法,但它仍然不起作用,因爲我希望它。我使用'MediaPlayer' +'SufaceView'來發布'onSeekComplete'事件的處理程序。基本上它可以工作,但它不夠準確:視頻暫停時間在200到1500毫秒之間。 – JuCachalot