Android videoView 存在的其中一个bug就是如果视频宽度和手机宽度不一致会出现问题,可以进行简单的重写VideoView,如下实现如下即可,然后用重写后的控件替换VideoView即可
1.重新定义videoView
/** * videoview存在的其中一个bug就是如果视频宽度和手机宽度不一致会出现问题 * @author smile */ public class MyVideoView extends VideoView{ public MyVideoView(Context context) { super(context); } public MyVideoView(Context context, AttributeSet attrs) { super(context, attrs); } public MyVideoView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int widthSize = getDefaultSize(0, widthMeasureSpec); int heightSize = getDefaultSize(0, heightMeasureSpec); setMeasuredDimension(widthSize,heightSize); } }
2.播放器布局文件
<?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" tools:context="com.gbf.livingdemo.MainActivity" android:orientation="vertical"> <com.gbf.livingdemo.MyVideoView android:id="@+id/videoview" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout>
3.mainfest文件
<uses-permission android:name="android.permission.INTERNET"/>
4.activity
public class MainActivity extends AppCompatActivity { private MyVideoView mVideoView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initData(); } private void initData() { mVideoView.setMediaController(new MediaController(this)); mVideoView.setVideoURI(Uri.parse("http://alcdn.hls.xiaoka.tv/2017427/14b/7b3/Jzq08Sl8BbyELNTo/index.m3u8")); mVideoView.start(); mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { Toast.makeText(MainActivity.this, "播放完成了", Toast.LENGTH_SHORT).show(); } }); } private void initView() { mVideoView=findViewById(R.id.videoview); } }
可以正常播放了
注意:1.如果是播放本地视频,需要添加权限:读写外部存储的权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
播放本地视频:
如:
File f = new File(path, "/Camera/test.mp4");
- videoView.setVideoPath(f.getAbsolutePath());
播放网络视频
videoView.setVideoURI(Uri.parse("http://xxx.xxx/xxx.mp4"));
2.videoView的缺点:
(1)页面进入videoview播放页面时候,黑屏
(2)播放器支持的视频格式:3gp MP4 avi