The surface has been released錯誤原因(親測有效)
阿新 • • 發佈:2019-02-13
從網上看了很多資料,發現好多都是錯誤的,所以今天特意更新這個問題的原因,
在播放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被銷燬。
有什麼問題請各位指出,謝謝!