简体   繁体   中英

duration of a video on Android

in this code I try to get the duration of a video with the method getDuration() but it doesn't work and it return always -1. What is wrong? Could I get the duration in another way?(The video is an mp4 file putted in the directory raw)

    videoPlayer = (VideoView) this.findViewById(R.id.videoView2);
    videoPlayer.setVideoPath("android.resource://"+getPackageName()+"/"+R.raw.video3);
    int duration = videoPlayer.getDuration();

Copied from getDuration in videoView:

public int getDuration(){
    if (isInPlaybackState()) {
        return mMediaPlayer.getDuration();
    }
    return -1;
}

So from what I see, you cannot get the correct duration if the video isn't playing. So a possible solution is to start the playback, get the duration to then stop it and restart the video.

Call getDuration inside setOnPreparedListener

 videoPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    long duration = videoPlayer.getDuration();
                }
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM