yangchaojiang / yjPlay

一个支持自定义UI布局,流式API, 加密,直播 ,亮度,音量,快进等手势 ,广告视频预览,多种加载模式 ,多种分辨率切换 ,多种封面图, 自定义数据源,列表播放,倍数播放,边播变缓存<font color="red">不是使用AndroidVideoCache</font>,离线播放,神奇的播放器
Apache License 2.0
1.73k stars 301 forks source link

Activity 中获取 VideoPlayer 为空 #317

Open liguobing opened 2 years ago

liguobing commented 2 years ago

我是使用 RecyclerView 来实现的,Activity 布局中有一个 RecyclerView,RecyclerView 的每个 Item 都是一个 VideoPlayerView,然后使用 PagerSnapHelper 来实现类似于抖音一样的功能

Adapter 代码如下:


public class Adapter extends RecyclerView.Adapter<VideoViewHolder> {

    private Context context;
    private ArrayList<VideoBean> list;

    public Adapter(Context context, ArrayList<VideoBean> list) {
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public VideoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(context).inflate(R.layout.view___play_video_viewpager_item, parent, false);
        return new VideoViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull VideoViewHolder holder, int position) {
        String videoUrl = "list.get(position).getVideoUser()+"/" + list.get(position).getSourceFileName();
        holder.bindData(videoUrl);
        String coverUrl = "list.get(position).getVideoUser() + "/cover/" + list.get(position).getCoverFileName();
        holder.setPreImage(context,coverUrl);
    }

    @Override
    public int getItemCount() {
        return list.size();
    }
}

ViewHolder 代码如下:

public class VideoViewHolder extends RecyclerView.ViewHolder {
    private ExoUserPlayer userPlayer;
    private VideoPlayerView playerView;

    public VideoViewHolder(@NonNull View itemView) {
        super(itemView);
        playerView = itemView.findViewById(R.id.video_view);
        userPlayer = new VideoPlayerManager.Builder(VideoPlayerManager.TYPE_PLAY_USER,
                playerView).setDataSource(new PlayVideoDataSource(itemView.getContext())).create();
    }

    public void setPreImage(Context context, String imageUrl) {
        Glide.with(context).load(imageUrl).into(playerView.getPreviewImage());
    }

    public void bindData(String string) {
        userPlayer.setPlayUri(string);
    }
}

代码可以正常运行,我想要实现抖音那样,进入Activity之后会自动播放,所以我尝试在 Activity 当中获取 VideoPlayer ,然后再调用它的 startPlayer 方法:

VideoPlayerManager instance = VideoPlayerManager.getInstance();
        ExoUserPlayer videoPlayer = instance.getVideoPlayer();
        videoPlayer.startPlayer();

但是 videoPlayer 为空,请问是什么原因啊,是我使用的方法哪里出错了吗?

我的依赖版本如下: implementation 'com.ycjiang:VideoPlayModule:2.3.61' implementation 'com.google.android.exoplayer:extension-okhttp:2.9.5'