Open marclee44 opened 3 years ago
使用VideoView不依赖任何第三方框架,即可轻松实现简单的本地MP4文件播放功能。配合MediaController还能添加一个系统自带的控制条。
VideoView
MediaController
首先是权限
为了能读取存储中的MP4文件,需要READ_EXTERNAL_STORAGE权限 在AndroidManifest.xml中
READ_EXTERNAL_STORAGE
AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
布局文件
考虑到复用性,做成Fragment。然内容极简
<?xml version="1.0" encoding="utf-8"?> <FrameLayout 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=".VideoViewFragment"> <VideoView android:id="@+id/video_view" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" /> </FrameLayout>
可以看到,布局中仅VideoView即可
控制代码
在fragment中,添加文件路径字符串及设置方法
private static String mMP4Path; public void setmMP4Path(String mMP4Path) { this.mMP4Path = mMP4Path; }
重载onViewCreated方法,在fragmentf视图创建完毕后,直接进行播放
onViewCreated
private VideoView mVideoView; private MediaController mMediaController; @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mVideoView = view.findViewById(R.id.video_view); mMediaController = new MediaController(getContext()); if (!mMP4Path.isEmpty()) { mVideoView.setVideoPath(mMP4Path); mVideoView.setMediaController(mMediaController); mVideoView.start(); mVideoView.requestFocus(); } }
在MainActivity中调用fragment
private VideoViewFragment mVideoView; private void PlayFile() { File file = new File(Environment.getExternalStorageDirectory(), "Movies/test.mp4"); if (file.exists()) { mVideoView = VideoViewFragment.newInstance(); mVideoView.setmMP4Path(file.getPath()); FragmentTransaction tran = getSupportFragmentManager().beginTransaction(); if (!mVideoView.isAdded()) { tran.setReorderingAllowed(true) .add(R.id.fragment_container_view, mVideoView, null); } tran.commit(); } }
ok,基本功能已然完成
使用
VideoView
不依赖任何第三方框架,即可轻松实现简单的本地MP4文件播放功能。配合MediaController
还能添加一个系统自带的控制条。为了能读取存储中的MP4文件,需要
READ_EXTERNAL_STORAGE
权限 在AndroidManifest.xml
中考虑到复用性,做成Fragment。然内容极简
可以看到,布局中仅VideoView即可
在fragment中,添加文件路径字符串及设置方法
重载
onViewCreated
方法,在fragmentf视图创建完毕后,直接进行播放在MainActivity中调用fragment
ok,基本功能已然完成