前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android 使用VideoView播放MP4的简单实现

Android 使用VideoView播放MP4的简单实现

作者头像
砸漏
发布2020-11-05 10:35:53
3.1K0
发布2020-11-05 10:35:53
举报
文章被收录于专栏:恩蓝脚本

使用VideoView播放MP4

播放示例

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

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

申请权限

读取存储中的MP4文件

代码语言:javascript
复制
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" / 

准备布局文件

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

代码语言:javascript
复制
<?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中直接播放视频文件;

代码语言:javascript
复制
  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文件路径,添加控制器,调整到最开始的地方,开始从头播放。

以上就是本文的全部内容,希望对大家的学习有所帮助。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档