I’m using the following code to play a .mp4 video on my android device. I have 3 problems,
-
using this code when I press the back button on the device the sound would still continoue to play
-
It doesn’t play the video, only plays the sound!
-
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();
1) Override onBackPressed in your activity:
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?
I don’t think that will work, you cannot play videos from there. Use the
resources/rawfolder 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
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.