如何从停止的位置开始播放视频

时间:2012-06-05 11:13:28

标签: android video

我正在使用VideoView播放视频。如果我退出应用程序,在返回应用程序时,即onResume(),它应该播放停止的视频。

2 个答案:

答案 0 :(得分:3)

获取当前进度(在onPause中检查):

long progress = mVideoView.getCurrentPosition(); 

要恢复(在onResume中):

mVideoView.seekTo(progress);

答案 1 :(得分:2)

在onPause()中,保存播放器的当前位置,例如在共享偏好中。在onResume()中,检索该值,然后使用MediaPlayer.seekTo()进行定位。

http://developer.android.com/reference/android/media/MediaPlayer.html#seekTo(int)

@Override
protected void onPause() {

    Log.d(App.TAG, "onPause called");

    if(mMediaPlayer==null){
        Log.d(App.TAG, "Returning from onPause because the mediaplayer is null");
        super.onPause();
        return;
    }

    // the OS is pausing us, see onResume() for resume logic
    settings = getSharedPreferences(Dawdle.TAG, MODE_PRIVATE);
    SharedPreferences.Editor ed = settings.edit();
    mMediaPlayer.pause();
    ed.putInt("LAST_POSITION", mMediaPlayer.getCurrentPosition());  // remember where we are
    ed.putBoolean("PAUSED", true); 
    ed.commit();
    Log.d(App.TAG, "LAST_POSITION saved:" + mMediaPlayer.getCurrentPosition());

    super.onPause();
    releaseMediaPlayer();

}

@Override
public void onResume() {
    Log.d(App.TAG, "onResume called");

    try {

        if (mMediaPlayer==null){
            setupMediaPlayer();
        }

        // if we were paused (set in this.onPause) then resume from the last position
        settings = getSharedPreferences(Dawdle.TAG, MODE_PRIVATE);
        if (settings.getBoolean("PAUSED", false)) {
            // resume from the last position
            startPosition= settings.getInt("LAST_POSITION", 0);
            Log.d(App.TAG,"Seek to last position:" + startPosition);
        }

        mMediaPlayer.setDataSource(path);
        mMediaPlayer.setDisplay(holder);

        // this is key, the call will return immediately and notify this when the player is prepared through a callback to onPrepared
        // so we do not block on the UI thread - do not call any media playback methods before the onPrepared callback
        mMediaPlayer.prepareAsync();  

    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

private void startVideoPlayback() {
    Log.v(App.TAG, "startVideoPlayback at position:" + startPosition);
    mMediaPlayer.seekTo(startPosition);
    mMediaPlayer.start();
}