從網上看了很多資料,發現好多都是錯誤的,所以今天特意更新這個問題的原因, 在播放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播放的生命周期:
surfaceCreated—-SurfaceHolder被創建,只要在SurfaceHolder被創建的時候做設置就可以避免The surface has been released問題。 surfaceChanged——SurfaceHolder發生改變 onPrepared—-mediaPlayer準備ok onCompletion—–mediaPlayer播放完成 surfaceDestroyed—–SurfaceHolder被銷毀。 有什么問題請各位指出,謝謝!
總結
以上是生活随笔 為你收集整理的The surface has been released错误原因(亲测有效) 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。