前言
什么是VideoView?
VideoView是Android原生提供的一个封装类,只用以播放视频,视频源可以是本地也可以是网络,支持大部分格式的视频源。
VideoView原理
VideoView继承自SurfaceView,里面封装了一个MediaPlayer用以具体的播放业务,并自带了一个简单的控制界面MediaController。
适用场景
VideoView的功能比较简单,非常适用于那些只单纯地播放视频的场景,如不断循环播放的广告视频。不适用于交互性多的视频播放场景,像调节亮度、调节音量、双击暂停等交互逻辑,VideoView是无法实现的。
1.简单使用步骤
第一步:在布局中添加
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<VideoView
android:id="@+id/vv_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
第二步:设置视频源地址并开始播放
//播放本地视频
String videoPath= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)+"/dync.mp4";
//videoPath = "http://vfx.mtime.cn/Video/2019/07/12/mp4/190712140656051701.mp4";
//设置播放地址,网络视频同样使用此方法,将网址链接放入即可
vvMain.setVideoPath(videoPath);
//开始播放
vvMain.start();
注意:本地视频需要读取存储的权限,网络视频需要网络权限,别忘了添加。
<uses-permission android:name="android.permissio