Mona Mona - 4 months ago 17
Android Question

Android play a video with controller

I'm using the following code to play a .mp4 video on my android device. I have 3 problems,


  1. using this code when I press the back button on the device the sound would still continoue to play

  2. It doesn't play the video, only plays the sound!

  3. I don't know how to get controller for the video so the user can stop the video, go back or forth on the video.

    VideoView videoHolder = new VideoView(this);
    videoHolder.setMediaController(new MediaController(this));
    getWindow().setFormat(PixelFormat.TRANSLUCENT);
    MediaPlayer mediaPlayer = new MediaPlayer();
    Uri myUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.drawable.video);

    videoHolder.setVideoURI(myUri);
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setDataSource(getApplicationContext(), myUri);
    mediaPlayer.prepare();
    mediaPlayer.start();

    videoHolder.requestFocus();
    videoHolder.start();


Answer

1) Override onBackPressed in your activity:

@Override
public void onBackPressed() {
    mediaPlayer.stopPlayback();
    super.onBackPressed();        
}

2) Is it a valid video format? Are you using emulator or a real device? If you use an emulator, try a real device instead. I recall similar issues before. But I also notice: did you put your video in the drawable folder?

R.drawable.video

I don't think that will work, you cannot play videos from there. Use the resources/raw folder instead. btw: Audio can be played from assets folder directly, while video cannot; video can only played from the raw folder or if you copy it to the apps files folder (getFilesDir()) - or sdcard of course.

3) Why are you using a VideoView AND a MediaPlayer, instead of just a VideoView? You should get rid of the mediaPlayer and just use the VideoView. This line

videoHolder.setMediaController(new MediaController(this));

looks correct and sets the media controller, with which the user can seek in the video. Programatically you can also use seekTo() to go back and forth in a video.

Comments