Android - 简单使用VideoView播放MP4

使用VideoView播放MP4

播放示例

实现简单的播放功能,播放手机本地的MP4文件。不依赖任何第三方框架,不添加任何防腐剂。
添加一个系统自带的控制条。

相关代码请参阅: https://github.com/RustFisher/android-MediaPlayer/tree/master/appMp4

申请权限

读取存储中的MP4文件

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

准备布局文件

frag_video_view.xml中放置VideoView;为了让内容居中显示,将其套在LinearLayout中,并选择android:layout_gravity="center"。否则可能会出现视频内容不居中的情况。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/black">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <VideoView
            android:id="@+id/video_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center" />

    </LinearLayout>

    <TextView
        android:id="@+id/path_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@android:color/white"
        android:textSize="13sp" />

</RelativeLayout>

在Fragment中直接播放视频文件;

    private static String mMP4Path;
    VideoView mVideoView;
    MediaController mMediaController;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        TextView pathTv = view.findViewById(R.id.path_tv);
        mVideoView = view.findViewById(R.id.video_view);
        mMediaController = new MediaController(getContext());
        if (!TextUtils.isEmpty(mMP4Path)) {
            mVideoView.setVideoPath(mMP4Path);
            mVideoView.setMediaController(mMediaController);
            mVideoView.seekTo(0);
            mVideoView.requestFocus();
            mVideoView.start();
            pathTv.setText(mMP4Path);
        }
    }

Fragment视图创建完毕时,设置MP4文件路径,添加控制器,调整到最开始的地方,开始从头播放。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,560评论 25 708
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,554评论 0 17
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    wgl0419阅读 6,360评论 1 9
  • 楔子 “六个大概六岁左右的孩子正围在一起,看着一只因练习飞翔而摔断翅膀的雏鸟,‘它真可怜’一个看起来长得很心疼的女...
    陌凌曦阅读 228评论 0 2
  • 《亲密关系》 第5版 作者: [美] 莎伦·布雷姆 / 丹尼尔·珀尔曼 / 罗兰·米勒 / 苏珊·坎贝尔—————...
    小慷阅读 669评论 0 1