java.lang.IllegalArgumentException: surfaceTexture must not be null

布局中使用了TextureView来进行视屏播放:

 <TextureView
     android:id="@+id/texture_view"
     android:layout_centerInParent="true"
     android:layout_width="wrap_content"
     android:layout_height="match_parent"/>

Avtivity逻辑代码:

 private MediaPlayer mMediaPlayer;
 @BindView(texture_view)
 public TextureView texture_view;        //视频播放器
 ......调用如下方法
 /**
     * 视频播放
     * @param videoPath 视频路径
     */
    private void playVideo(String videoPath){
        if(mMediaPlayer != null){
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
        try {
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setDataSource(videoPath);
            mMediaPlayer.setSurface(new Surface(texture_view.getSurfaceTexture()));
            mMediaPlayer.setLooping(true);
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                    float ratio = mp.getVideoWidth()*1f/mp.getVideoHeight();
                    int width = texture_view.getWidth();
                    int height = texture_view.getHeight();
                    ViewGroup.LayoutParams layoutParams = texture_view.getLayoutParams();
                    layoutParams.width = (int) (height*ratio);
                    texture_view.setLayoutParams(layoutParams);
                }
            });
            mMediaPlayer.prepareAsync();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

这样运行便或出现题目中所示的错误,不会崩溃,只是资源视频无法显示,为此,进行如下修改。


 private Surface surface;
 //设置监听函数  重写4个方法
 texture_view.setSurfaceTextureListener(this);
 /**
     *  视频播放器
     * @param surfaceTexture
     * @param width
     * @param height
     */
    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
        surface=new Surface(surfaceTexture);
        playVideo(actionVideoPath);
    }
    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) {
    }
    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
        surfaceTexture=null;
        surface=null;
        mMediaPlayer.stop();
        mMediaPlayer.release();
        return true;
    }
    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) {
    }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值