Search code examples
androidvideoandroid-videoviewandroid-video-player

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();

Solution

  • 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.