我可以在“ surfaceCreated”,“ onPrepared”和“ new MediaPlayer()”之间放置mMediaPlayer.start()方法?

时间:2019-04-16 02:49:29

标签: android android-mediaplayer surfaceholder

使用MediaPlayer和SurfaceView播放视频时。当mMediaPlayer为null时,有时会调用surfaceCreated。然后将不会调用“ surfaceCreated(Surfaceholder)”下的方法“ mMediaPlayer.setDisplay(holder)”。 调用mMediaPlayer.prepareAsync()之后,mMediaPlayer将在不设置surfaceHolder的情况下执行.start()。

我没有办法安排他们的关系。

//pseudo code
public class PlayerManager extends BaseMediaPlayer implements SurfaceHolder.Callback,
        MediaPlayer.OnCompletionListener,
        MediaPlayer.OnPreparedListener {

    private boolean isSurfaceCreated = false;
    private boolean isMediaPlayerPrepared = false;
    private boolean isMediaDataSourceOk = false; 

    private void initMediaPlayer(){
        if(!null){
            mMediaPlayer.release();
            =null
        }
        new MediaPlayer();
        isMediaPlayerPrepared = false;
        isMediaDataSourceOk = false;
    }

    /**
     * here!!!
     */
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        isSurfaceCreated = true;
        if (mMediaPlayer != null) {
            mMediaPlayer.setDisplay(holder);
            if (isMediaPlayerPrepared && isMediaDataSourceOk) {
                play();
            }
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.d(TAG, "surfaceDestroyed");
        isSurfaceCreated = false;
    }

    /**
     * here!!!
     */
    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        Log.d(TAG, "MediaPlayer prepared");
        isMediaPlayerPrepared = true;
        if (isSurfaceCreated && isMediaDataSourceOk) {
            play();
        }
    }

    public void play(){
        initMediaPlayer();

        try mMediaPlayer.setDataSource(xxx);
        catch e return;
        isMediaDataSourceOk =true;

        try mMediaPlayer.prepareAsync();
        catch e return;
    }

}

0 个答案:

没有答案