In the previous article we have introduced how to use the android VideoView widget to play, pause, continue, stop and replay video files in android. But when you use VideoView‘s method seekto to make the video play from a particular position, you will find the video playing is inconsistent. Sometimes it starts from the beginning. There are two methods to resolve the above problem.
1. Make Video Start After SeekTo Method Complete.
- This is one reason for the issue. The VidewView widget starts to play the video file while the seekto method does not finish.
- You can add a MediaPlayer.OnPreparedListener to the VideoView object. And override it’s onPrepared method to resolve this problem.
- From the onPrepared method, we can get a reference to the MediaPlayer object. And we can set MediaPlayer.OnSeekCompleteListener to listen to the seek complete event and play the video when the seek action completes.
- Why we do the above action is because we can not set OnSeekCompleteListener to the VideoView object directly. So we have to do this. Now the video will play only when the method seekto is complete.
playVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { // Set media player on seek complete listener. mediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() { // This method will be invoked when seekto method complete. @Override public void onSeekComplete(MediaPlayer mediaPlayer) { // Play video only when seekto method complete and video is paused. if(isVideoPaused) { playVideoView.start(); isVideoPaused = false; } } }); } });
2. Use FFMpeg To Make Video Key Frame Continuous.
- Video file consists of frames, and there are some frames that are called a keyframe. When you use the seekto method to seek a special position, the VideoView object will jump to the keyframe which is nearest to the position.
- So if the keyframe in the video is not continuous, you will find the seekto method do not consistent. So we need a tool to make the video keyframe continuous.
- FFMpeg is a very good tool to do the above task. First, you need to download it from https://ffmpeg.zeranoe.com/builds/. This is a windows version. You can also download the source code from its official website since it is open source.
- After download, unzip it to a local folder such as C:\ffmpeg and add C:\ffmpeg\bin folder in the computer Path environment variable. Please refer article How To Set Java Environment Variable JAVA_HOME, CLASSPATH, PATH for a detailed explanation.
- Then open the dos window, run the below command in it. This command will make a keyframe between every 2 normal frames.
ffmpeg.exe -i "C:\WorkSpace\play_video_test.mp4" -c:v libx264 -preset superfast -x264opts keyint=2 -acodec copy -f mp4 "C:\WorkSpace\play_video_test_key_frame.mp4"
- Then you will find VideoView‘s seekto method more accurate and consistent with the new keyframe added video file.
Reference