我正在尝试开发一个Android应用程序,用于从原始文件夹播放视频。我正在使用自定义控件选项getduration()返回-1,所以我不能将max值设置为我的搜索栏。这是我的代码
private MediaController mediaController;
private VideoView videoView;
public TextView duration;
private int timeElapsed=0,finalTime=0;
private int forwardTime=2000, backwardTime=2000;
private SeekBar seekBar;
private Handler durationHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
}
public void initialize()
{
videoView =(VideoView)findViewById(R.id.videoView1);
mediaController= new MediaController(this);
mediaController.setAnchorView(videoView);
String
uri1="android.resource://"+getPackageName()+"/"+R.raw.materialdesign;
Uri uri = Uri.parse(uri1);
videoView.setMediaController(null);
videoView.setVideoPath("android.resource://" + getPackageName() + "/" +
R.raw.materialdesign);
Log.e("finalTime", "" + finalTime);
finalTime = videoView.getDuration();
Log.e("finalTime", ""+finalTime);
Log.e("finalTime", ""+videoView.getDuration());
duration = (TextView) findViewById(R.id.songDuration);
seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setMax(finalTime);
seekBar.setClickable(false);
videoView.requestFocus();
}
答案 0 :(得分:5)
如果您没有找到解决方案,如果视频未处于播放状态,VideoView.getDuration()
将返回-1。视频在准备好之前不处于播放状态。因此,在设置URI后直接调用VideoView.getDuration()
并不能保证视频已经准备好。
我通过查看VideoView的来源找到了这个:
@Override
public int getDuration() {
if (isInPlaybackState()) {
return mMediaPlayer.getDuration();
}
return -1;
}
解决方案是将OnPreparedListener设置为VideoView,并在准备好视频后获取持续时间。然后,您可以使用几乎相同的VideoView.getDuration()
或MediaPlayer.getDuration()
。
解决方案:
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
int duration = mp.getDuration();
int videoDuration = videoView.getDuration();
Log.d(TAG, String.format("onPrepared: duration=%d, videoDuration=%d", duration,
videoDuration);
}
seekBar.setMax(videoDuration);
});