The surface has been released错误原因(亲测有效)

从网上看了很多资料,发现好多都是错误的,所以今天特意更新这个问题的原因,
在播放mediaPlayer.start()时SurfaceHolder没有来的及调用onCreate()方法创建view,导致holder没有成功加载,因为mediaplayer是在SurfaceHolder上面播放的,所以才抛出播放异常。贴出正确代码

 mSurfaceView = (SurfaceView) findViewById(R.id.surface_view);
        AssetManager assetManager = getAssets();
        try {
            mDescriptor = assetManager.openFd("test1.mp4");
        } catch (IOException e) {
            e.printStackTrace();
        }
        mediaPlayer = new MediaPlayer();
        mSurfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                Log.d(TAG, "surfaceCreated=" + System.currentTimeMillis());
                try {
                    mediaPlayer.setDataSource(mDescriptor.getFileDescriptor(), mDescriptor.getStartOffset(), mDescriptor.getLength());

                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);//设置播放声音类型
                    mediaPlayer.prepare();
                    mediaPlayer.setDisplay(mSurfaceView.getHolder());

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                Log.d(TAG, "surfaceChanged=" + System.currentTimeMillis());
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                Log.d(TAG, "surfaceDestroyed=" + System.currentTimeMillis());
            }
        });


        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                Log.d(TAG, "onPrepared=" + System.currentTimeMillis());
                mediaPlayer.start();
            }
        });


        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Log.d(TAG, " times onCompletion=" + System.currentTimeMillis());
                mediaPlayer.release();
            }
        });
    }

medialplayer播放的生命周期:
The surface has been released错误原因(亲测有效)_第1张图片

surfaceCreated—-SurfaceHolder被创建,只要在SurfaceHolder被创建的时候做设置就可以避免The surface has been released问题。
surfaceChanged——SurfaceHolder发生改变
onPrepared—-mediaPlayer准备ok
onCompletion—–mediaPlayer播放完成
surfaceDestroyed—–SurfaceHolder被销毁。
有什么问题请各位指出,谢谢!

你可能感兴趣的:(安卓技术,medialplay,genymotio,surfaceview)