Step 5 Learn to play video using VideoView

  • 2021-09-16 07:57:23
  • OfStack

We can imagine that ImageView can display pictures, while VideoView is used to display videos.

The steps to play video using VideoView are as follows

"1" Define VideoView in interface layout


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  tools:context=".MainActivity">

  <VideoView
    android:id="@+id/videoview"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"/>
  <Button
    android:id="@+id/button"
    android:text=" Play "
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</LinearLayout>

"2" Calls the following two methods to load the specified video

setVideoPath (String Path); Load video under the path
setVideoURL (URL url); Load the video corresponding to url.


mVideoView.setVideoPath(Environment.getExternalStorageDirectory()+"/aa.mp4");

"3" authority


<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

"4" call

start (), stop (), pause () control playback

"5" is often combined with MediaController class in practice, which provides a friendly image control interface to control video playback;


mVideoView.setMediaController(new MediaController(MainActivity.this));

The complete program code is as follows


public class MainActivity extends Activity {

  private VideoView mVideoView;
  private Button mButton;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mVideoView= (VideoView) findViewById(R.id.videoview);
    mButton= (Button) findViewById(R.id.button);
    mButton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {

        // Get sdcard Below aa.mp4 File of 
        // Two calling methods 
//        File videofile =new File("/mut/extSdCard/DCIM/Camera/20150915_160202.mp4");
//        mVideoView.setVideoPath(videofile.getAbsolutePath());
        mVideoView.setVideoPath(Environment.getExternalStorageDirectory()+"/20150915_160202.mp4");
        mVideoView.setMediaController(new MediaController(MainActivity.this));
        mVideoView.start();
      }
    });
  }


}


Related articles: