Android之播放本地视频和Url视频方法

一、播放本地视频文件

根据文件路径在浏览器中播放,可用于视频预览等场景

效果:

用浏览器播放本地视频

文件路径例子:
/storage/emulated/0/Android/data/com.custom.jfrb/files/Movies/1697687179497.mp4

File file = new File("文件路径");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra("oneshot", 0);
intent.putExtra("configchange", 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Uri contentUri = FileProvider.getUriForFile(UploadVideoActivity.this, getContext().getPackageName() + ".provider", file);
        intent.setDataAndType(contentUri, "video/*");
} else {
        intent.setDataAndType(Uri.fromFile(file), "video/*");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
startActivity(intent);

二、播放Url视频(GSYVideoPlayer类的使用)

效果:

播放Url视频

1、导入依赖

implementation 'com.github.CarGuo.GSYVideoPlayer:GSYVideoPlayer:v8.1.7-release-jitpack'

2、xml文件


3、Activity中调用

(1) 绑定控件

@InjectView(id = R.id.video_player)
StandardGSYVideoPlayer mVideoPlayer;

(2)播放视频
视频Url例子:https://recordcdn-qk.jfdaily.com/upload/vod/user1694515885005019/1697678251135382/preview/video.mp4

//播放横屏视频
 boolean setUp = mVideoPlayer.setUp("视频Url", true, "名字");
//设置封面
//        if (setUp) {
//            Glide.with(this).load(productItem.getCapture()).into((ImageView) mVideoPlayer.getThumbImageView());
//        }
//隐藏自带的标题和返回键
mVideoPlayer.getTitleTextView().setVisibility(View.GONE);
 mVideoPlayer.getBackButton().setVisibility(View.GONE);
 
//全屏按键
mVideoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
             mVideoPlayer.startWindowFullscreen(ProductDetailActivity.this,false,true);
       }
});
GSYVideoType.setShowType(GSYVideoType.SCREEN_TYPE_DEFAULT);
//根据视频尺寸,自动选择竖屏全屏或者横屏全屏
mVideoPlayer.setAutoFullWithSize(true);
//全屏动画
mVideoPlayer.setShowFullAnimation(true);
//开始播放
mVideoPlayer.startPlayLogic();

(3)相关生命周期中添加操作

@Override
    public void onBackPressed() {
        if (GSYVideoManager.backFromWindowFull(this)){
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mVideoPlayer.onVideoResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mVideoPlayer.onVideoPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        GSYVideoADManager.releaseAllVideos();
    }

三、持续更新中…

你可能感兴趣的:(android,音视频)