Android-VideoView播放网络视频
官方文档: https://developer.android.google.cn/reference/android/widget/VideoView
运行截图:
/**
* 亲测以下直播源均可用
* CCTV1高清:http://ivi.bupt.edu.cn/hls/cctv1hd.m3u8
* CCTV3高清:http://ivi.bupt.edu.cn/hls/cctv3hd.m3u8
* CCTV5+高清:http://ivi.bupt.edu.cn/hls/cctv5phd.m3u8
* CCTV6高清:http://ivi.bupt.edu.cn/hls/cctv6hd.m3u8
*/
主布局文件:
<?xml version="1.0" encoding="utf-8"?>
<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" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/start"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="开始"
android:textAllCaps="false"
android:textSize="20sp" />
<Button
android:id="@+id/pause"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="暂停"
android:textAllCaps="false"
android:textSize="20sp" />
</LinearLayout>
</LinearLayout>
主类:
/**
* 该Demo用于演示VideoView播放网络视频
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private VideoView videoView;
private Button start;
private Button pause;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
initVideoView();
}
private void initVideoView() {
videoView.setVideoPath("http://ivi.bupt.edu.cn/hls/cctv1hd.m3u8");
}
private void init() {
videoView = findViewById(R.id.videoView);
start = findViewById(R.id.start);
pause = findViewById(R.id.pause);
start.setOnClickListener(this);
pause.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
if (!videoView.isPlaying()) {
videoView.start();
}
break;
case R.id.pause:
if (videoView.isPlaying()) {
videoView.pause();
}
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (videoView != null) {
videoView.suspend();
}
}
}
/**
* 亲测以下直播均可用
* CCTV1高清:http://ivi.bupt.edu.cn/hls/cctv1hd.m3u8
* CCTV3高清:http://ivi.bupt.edu.cn/hls/cctv3hd.m3u8
* CCTV5+高清:http://ivi.bupt.edu.cn/hls/cctv5phd.m3u8
* CCTV6高清:http://ivi.bupt.edu.cn/hls/cctv6hd.m3u8
*/
不要忘记在Manifest.xml里添加网络权限:
<uses-permission android:name="android.permission.INTERNET" />