Android 视频播放器dkplayer

gihub地址

https://github.com/Doikki/DKVideoPlayer

GitHub - Doikki/DKVideoPlayer: Android Video Player. 安卓视频播放器,封装MediaPlayer、ExoPlayer、IjkPlayer。模仿抖音并实现预加载,列表播放,悬浮播放,广告播放,弹幕,视频水印,视频滤镜

列表播放如图所示:

一、依赖

     //添加RecyclerView的依赖包implementation 'androidx.recyclerview:recyclerview:1.2.1'// 异步加载图片依赖implementation 'com.squareup.picasso:picasso:2.5.2'// 上拉刷新、下来加载依赖implementation 'com.scwang.smartrefresh:SmartRefreshLayout:1.1.3'// --  Android:视频播放器dkplayer//# 必选,内部默认使用系统mediaplayer进行解码implementation 'com.github.dueeeke.dkplayer:dkplayer-java:3.2.6'//# 可选,包含StandardVideoController的实现implementation 'com.github.dueeeke.dkplayer:dkplayer-ui:3.2.6'//# 可选,使用exoplayer进行解码implementation 'com.github.dueeeke.dkplayer:player-exo:3.2.6'//# 可选,使用ijkplayer进行解码implementation 'com.github.dueeeke.dkplayer:player-ijk:3.2.6'//# 可选,如需要缓存或者抖音预加载功能请引入此库implementation 'com.github.dueeeke.dkplayer:videocache:3.2.6'

二、工具类

Tag.java

package com.chy.permission;/*** 播放器标签*/
public final class Tag {//列表播放public static final String LIST = "list";//无缝播放public static final String SEAMLESS = "seamless";//画中画public static final String PIP = "pip";
}
Utils.java
package com.chy.permission;import android.view.View;
import android.view.ViewParent;
import android.widget.FrameLayout;import com.dueeeke.videoplayer.player.VideoView;
import com.dueeeke.videoplayer.player.VideoViewConfig;
import com.dueeeke.videoplayer.player.VideoViewManager;import java.lang.reflect.Field;public final class Utils {private Utils() {}/*** 获取当前的播放核心*/public static Object getCurrentPlayerFactory() {VideoViewConfig config = VideoViewManager.getConfig();Object playerFactory = null;try {Field mPlayerFactoryField = config.getClass().getDeclaredField("mPlayerFactory");mPlayerFactoryField.setAccessible(true);playerFactory = mPlayerFactoryField.get(config);} catch (Exception e) {e.printStackTrace();}return playerFactory;}/*** 将View从父控件中移除*/public static void removeViewFormParent(View v) {if (v == null) return;ViewParent parent = v.getParent();if (parent instanceof FrameLayout) {((FrameLayout) parent).removeView(v);}}/*** Returns a string containing player state debugging information.*/public static String playState2str(int state) {String playStateString;switch (state) {default:case VideoView.STATE_IDLE:playStateString = "idle";break;case VideoView.STATE_PREPARING:playStateString = "preparing";break;case VideoView.STATE_PREPARED:playStateString = "prepared";break;case VideoView.STATE_PLAYING:playStateString = "playing";break;case VideoView.STATE_PAUSED:playStateString = "pause";break;case VideoView.STATE_BUFFERING:playStateString = "buffering";break;case VideoView.STATE_BUFFERED:playStateString = "buffered";break;case VideoView.STATE_PLAYBACK_COMPLETED:playStateString = "playback completed";break;case VideoView.STATE_ERROR:playStateString = "error";break;}return String.format("playState: %s", playStateString);}/*** Returns a string containing player state debugging information.*/public static String playerState2str(int state) {String playerStateString;switch (state) {default:case VideoView.PLAYER_NORMAL:playerStateString = "normal";break;case VideoView.PLAYER_FULL_SCREEN:playerStateString = "full screen";break;case VideoView.PLAYER_TINY_SCREEN:playerStateString = "tiny screen";break;}return String.format("playerState: %s", playerStateString);}}

VideoAdapter.java

package com.chy.demoprj.adapter;import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;import com.chy.demoprj.R;
import com.dueeeke.videocontroller.component.PrepareView;
import com.squareup.picasso.Picasso;import java.util.HashMap;
import java.util.List;public class VideoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {private Context context;private List<HashMap<String,String>> datas;private OnItemChildClickListener mOnItemChildClickListener;// 播放控件点击事件/*** 构造函数* */public VideoAdapter(Context context,List<HashMap<String,String>> datas){this.context = context;this.datas = datas;}@NonNull@Overridepublic RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent,int viewType) {View view = LayoutInflater.from(context).inflate(R.layout.item_video_layout,parent,false);ViewHolder viewHolder = new ViewHolder(view);return viewHolder;}@Overridepublic void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder,int position) {ViewHolder vh = (ViewHolder) holder;HashMap<String,String> entity = datas.get(position);// 设置播放占位图(不设置默认黑色)Picasso.with(context).load(entity.get("thumbUrl")).into(vh.mThumb);vh.mPosition = position;}@Overridepublic int getItemCount() {return datas.size();}public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{public FrameLayout mPlayerContainer;// 容器public PrepareView mPrepareView;// 播放视图public ImageView mThumb;// 缩略图public int mPosition;// 当前视图indexpublic ViewHolder(@NonNull View itemView) {super(itemView);mPlayerContainer = itemView.findViewById(R.id.player_container);mPrepareView = itemView.findViewById(R.id.prepare_view);mThumb = mPrepareView.findViewById(R.id.thumb);/*** 添加点击事件* */if (mOnItemChildClickListener != null) {mPlayerContainer.setOnClickListener(this);}//通过tag将ViewHolder和itemView绑定itemView.setTag(this);}@Overridepublic void onClick(View v) {if (v.getId() == R.id.player_container){if (mOnItemChildClickListener != null){mOnItemChildClickListener.onItemChildClick(mPosition);}}}}/*** 点击事件接口* */public interface OnItemChildClickListener{void onItemChildClick(int position);}/*** 点击事件回调函数* */public void setOnItemChildClickListener(OnItemChildClickListener onItemChildClickListener) {mOnItemChildClickListener = onItemChildClickListener;}}

三、布局

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<com.scwang.smartrefresh.layout.SmartRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/refreshLayout"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><androidx.recyclerview.widget.RecyclerViewandroid:id="@+id/recyclerView"android:layout_width="match_parent"android:layout_height="match_parent"/></com.scwang.smartrefresh.layout.SmartRefreshLayout>

item_video_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical"><FrameLayoutandroid:id="@+id/player_container"android:layout_width="match_parent"android:layout_height="187dp"android:layout_marginTop="8dp"android:background="@android:color/black"app:layout_constraintDimensionRatio="16:9"app:layout_constraintTop_toTopOf="parent"><com.dueeeke.videocontroller.component.PrepareViewandroid:id="@+id/prepare_view"android:layout_width="match_parent"android:layout_height="match_parent" /></FrameLayout></LinearLayout>

四、实现

package com.chy.demoprj;import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.chy.demoprj.adapter.VideoAdapter;
import com.chy.permission.PermissionUtils;
import com.chy.permission.Tag;
import com.chy.permission.Utils;
import com.dueeeke.videocontroller.StandardVideoController;
import com.dueeeke.videocontroller.component.CompleteView;
import com.dueeeke.videocontroller.component.ErrorView;
import com.dueeeke.videocontroller.component.GestureView;
import com.dueeeke.videocontroller.component.TitleView;
import com.dueeeke.videocontroller.component.VodControlView;
import com.dueeeke.videoplayer.player.VideoView;
import com.dueeeke.videoplayer.player.VideoViewManager;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;public class MainActivity extends AppCompatActivity {private static final int REQUEST_PERMISSION_CODE = 0;// 权限所用// 动态申请权限private String[] permissions = {Manifest.permission.INTERNET,// 网络权限Manifest.permission.WRITE_EXTERNAL_STORAGE,// 写入数据权限Manifest.permission.READ_EXTERNAL_STORAGE,// 读取数据权限Manifest.permission.ACCESS_FINE_LOCATION,// 定位权限Manifest.permission.ACCESS_COARSE_LOCATION // 获取基站的服务信号权限,以便获取位置信息};private RefreshLayout refreshLayout;private RecyclerView recyclerView;// 列表private LinearLayoutManager layoutManager;private List<HashMap<String,String>> datas = new ArrayList<>();// 视频播放-控件protected VideoView mVideoView;protected StandardVideoController mController;protected ErrorView mErrorView;protected CompleteView mCompleteView;protected TitleView mTitleView;/*** 当前播放的位置* */protected int mCurPos = -1;/*** 上次播放的位置,用于页面切换回来继续播放* */protected int mLastPos = mCurPos;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);getPermission();initData();initControls();initVideoView();}/*** 权限* */private void getPermission(){boolean flage = PermissionUtils.hasPermissions(MainActivity.this,permissions);if (flage) {System.out.println("权限获取成功!");} else {PermissionUtils.requestPermissions(MainActivity.this, REQUEST_PERMISSION_CODE, permissions);}}/*** 数据初始化* */private void initData(){HashMap<String,String> hashMap = null;// 占位图String thumbUrl = "https://p1-xg.byteimg.com/img/tos-cn-p-0000/527b08d0f31d4705a4d8f4a72120948c~tplv-crop-center:1041:582.jpg";// 视频播放地址String playerUrl = "https://vd4.bdstatic.com/mda-pdhb52ikamv3bdb7/sc/cae_h264/1681819063478400576/mda-pdhb52ikamv3bdb7.mp4";// 循环添加数据for (int i=0,len=8;i<=len;i++){hashMap = new HashMap<>();hashMap.put("thumbUrl",thumbUrl);hashMap.put("playerUrl",playerUrl);hashMap.put("vtitle","播放标题"+i);datas.add(hashMap);}}/*** 初始化控件* */private void initControls(){refreshLayout = findViewById(R.id.refreshLayout);// 下拉刷新事件refreshLayout.setOnRefreshListener(new OnRefreshListener() {@Overridepublic void onRefresh(@NonNull RefreshLayout refreshLayout) {refreshLayout.finishRefresh(2000/*,false*/);// 传入false表示刷新失败}});// 上拉加载事件refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {@Overridepublic void onLoadMore(@NonNull RefreshLayout refreshLayout) {refreshLayout.finishLoadMore(2000/*,false*/);// 传入false表示加载失败runOnUiThread(new Runnable() {@Overridepublic void run() {Toast.makeText(getApplication(),"没有更多数据",Toast.LENGTH_SHORT).show();}});}});recyclerView = findViewById(R.id.recyclerView);// 设置布局layoutManager = new LinearLayoutManager(this);layoutManager.setOrientation(LinearLayoutManager.VERTICAL);recyclerView.setLayoutManager(layoutManager);// 配置器VideoAdapter videoAdapter = new VideoAdapter(this,datas);// 设置点击事件videoAdapter.setOnItemChildClickListener(new VideoAdapter.OnItemChildClickListener() {@Overridepublic void onItemChildClick(int position) {/*** PrepareView被点击*/startPlay(position);}});recyclerView.setAdapter(videoAdapter);// RecyclerView监听事件recyclerView.addOnChildAttachStateChangeListener(new RecyclerView.OnChildAttachStateChangeListener() {@Overridepublic void onChildViewAttachedToWindow(@NonNull View view) {}@Overridepublic void onChildViewDetachedFromWindow(@NonNull View view) {FrameLayout playerContainer = view.findViewById(R.id.player_container);View v = playerContainer.getChildAt(0);if (v != null && v == mVideoView && !mVideoView.isFullScreen()){releaseVideoView();}}});}/*** 播放控件初始化* */protected void initVideoView() {mVideoView = new VideoView(this);mVideoView.setOnStateChangeListener(new VideoView.SimpleOnStateChangeListener() {@Overridepublic void onPlayStateChanged(int playState) {//监听VideoViewManager释放,重置状态if (playState == com.dueeeke.videoplayer.player.VideoView.STATE_IDLE) {Utils.removeViewFormParent(mVideoView);mLastPos = mCurPos;mCurPos = -1;}}});mController = new StandardVideoController(this);mErrorView = new ErrorView(this);mController.addControlComponent(mErrorView);mCompleteView = new CompleteView(this);mController.addControlComponent(mCompleteView);mTitleView = new TitleView(this);mController.addControlComponent(mTitleView);mController.addControlComponent(new VodControlView(this));mController.addControlComponent(new GestureView(this));mController.setEnableOrientation(true);mVideoView.setVideoController(mController);}@Overridepublic void onPause() {super.onPause();pause();}/*** 由于onPause必须调用super。故增加此方法,* 子类将会重写此方法,改变onPause的逻辑*/protected void pause() {releaseVideoView();}@Overridepublic void onResume() {super.onResume();resume();}/*** 由于onResume必须调用super。故增加此方法,* 子类将会重写此方法,改变onResume的逻辑*/protected void resume() {if (mLastPos == -1)return;//恢复上次播放的位置startPlay(mLastPos);}/*** 开始播放** @param position 列表位置*/protected void startPlay(int position) {if (mCurPos == position) return;if (mCurPos != -1) {releaseVideoView();}HashMap<String,String> entity = datas.get(position);//边播边存
//        String proxyUrl = ProxyVideoCacheManager.getProxy(getActivity()).getProxyUrl(videoBean.getUrl());
//        mVideoView.setUrl(proxyUrl);String playurl = entity.get("playerUrl");mVideoView.setUrl(playurl);mTitleView.setTitle(entity.get("vtitle"));View itemView = layoutManager.findViewByPosition(position);if (itemView == null) return;VideoAdapter.ViewHolder viewHolder = (VideoAdapter.ViewHolder) itemView.getTag();//把列表中预置的PrepareView添加到控制器中,注意isPrivate此处只能为true。mController.addControlComponent(viewHolder.mPrepareView, true);Utils.removeViewFormParent(mVideoView);viewHolder.mPlayerContainer.addView(mVideoView, 0);//播放之前将VideoView添加到VideoViewManager以便在别的页面也能操作它getVideoViewManager().add(mVideoView, Tag.LIST);mVideoView.start();mCurPos = position;}/*** 释放播放控件* */private void releaseVideoView() {mVideoView.release();if (mVideoView.isFullScreen()) {mVideoView.stopFullScreen();}if (this.getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);}mCurPos = -1;}/*** 创建播放管理类* */protected VideoViewManager getVideoViewManager(){return VideoViewManager.instance();}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/66126.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

定量分析计算51单片机复位电路工作原理 怎么计算单片机复位电容和电阻大小

下面画出等效电路图 可以知道单片机内必然有一个电阻RX&#xff0c;为了简化分析&#xff0c;我们假设他是线性电阻&#xff08;不带电容&#xff0c;电感的支路&#xff09; 还有一个基础知识&#xff1a; 电容器的充电放电曲线&#xff1a; 还需要知道电容电压的变化是连续…

Android Jetpack Compose 中的分页与缓存展示

Android Jetpack Compose 中的分页与缓存展示 在几乎任何类型的移动项目中&#xff0c;移动开发人员在某个时候都会处理分页数据。如果数据列表太大&#xff0c;无法一次从服务器检索完毕&#xff0c;这就是必需的。因此&#xff0c;我们的后端同事为我们提供了一个端点&#…

11、Nvidia显卡驱动、CUDA、cuDNN、Anaconda及Tensorflow Pytorch版本

Nvidia显卡驱动、CUDA、cuDNN、Anaconda及Tensorflow-GPU版本 一、确定版本关系二、安装过程1.安装显卡驱动2、安装CUDA3、安装cudnn4、安装TensorFlow5、安装pytorch 三、卸载 一、确定版本关系 TensorFlow Pytorch推出cuda和cudnn的版本&#xff0c;cuda版本推出驱动可选版本…

【不限于联想Y9000P电脑关盖再打开时黑屏的解决办法】

不限于联想Y9000P电脑关盖再打开时黑屏的解决办法 问题的前言问题的出现问题拟解决 问题的前言 事情发生在昨天&#xff0c;更新了Win11系统后&#xff1a; 最惹人注目的三处地方就是&#xff1a; 1.可以查看时间的秒数了&#xff1b; 2.右键展示的内容变窄了&#xff1b; 3.按…

Oracle database Linux自建环境备份至远端服务器自定义保留天数

环境准备 linux下安装oracle 请看 oracle12c单节点部署 系统版本: CentOS 7 软件版本&#xff1a; Oracle12c 备份策略与实现方法 此次备份依赖Oracle自带命令exp与linux下crontab命令&#xff08;定时任务&#xff09; exp Oracle中exp命令是一个用于导出数据库数据和对象的…

教你如何为博客网站申请阿里云的免费域名HTTPS证书

如何为博客网站申请阿里云的免费域名HTTPS证书 文章目录 如何为博客网站申请阿里云的免费域名HTTPS证书前置条件&#xff1a;步骤1 例如阿里云控制台&#xff0c;选择SSL证书步骤2 申请购买免费证书步骤3 创建证书步骤3.1 证书申请步骤3.2 DNS域名验证 步骤4 等待证书审核成功&…

【产品设计】移动端表单设计

本文主要是根据项目的表单填写体验差被客户撤下线重新整改&#xff0c;而对此将表单进行了新的用户体验设计的一些构思。 一、现状 传统的PC端空间范围大&#xff0c;能够将表单的所有信息连同温馨提示语等平铺展示出来&#xff0c;但是一下子用户看到这么多内容会给用户带来压…

【设计模式】责任链模式

顾名思义&#xff0c;责任链模式&#xff08;Chain of Responsibility Pattern&#xff09;为请求创建了一个接收者对象的链。这种模式给予请求的类型&#xff0c;对请求的发送者和接收者进行解耦。这种类型的设计模式属于行为型模式。 在这种模式中&#xff0c;通常每个接收者…

腾讯云轻量应用服务器搭建WordPress网站教程

腾讯云百科分享使用腾讯云轻量应用服务器搭建WordPress网站教程流程&#xff0c;WordPress 是全球最流行的开源的博客和内容管理网站的建站平台&#xff0c;具备使用简单、功能强大、灵活可扩展的特点&#xff0c;提供丰富的主题插件。腾讯云轻量应用服务器提供 WordPress 应用…

C++:模拟实现list

文章目录 迭代器模拟实现 本篇模拟实现简单的list和一些其他注意的点 迭代器 如下所示是利用拷贝构造将一个链表中的数据挪动到另外一个链表中&#xff0c;构造两个相同的链表 list(const list<T>& lt) {emptyinit();for (auto e : lt){push_back(e);} }void test_…

二叉树(4)------收尾

1)最大二叉树 654. 最大二叉树 - 力扣&#xff08;LeetCode&#xff09; 题目解析: 1)首先我们找到了整个数组中最大的元素作为我们的根节点&#xff0c;然后再从左区间中找到最大的元素作为当前根节点的左子树&#xff0c;然后再从右区间里面找到最大的元素作为根节点的右子树…

8.10 用redis实现缓存功能和Spring Cache

什么是缓存? 缓存(Cache), 就是数据交换的缓冲区,俗称的缓存就是缓冲区内的数据,一般从数据库中获取,存储于本地代码。 通过Redis来缓存数据&#xff0c;减少数据库查询操作; 逻辑 每个分类的菜品保存一份缓存数据 数据库菜品数据有变更时清理缓存数据 如何将商品数据缓存起…