【Android】- MediaPlayer错误之MediaPlayer start called in state 0

先看MediaPlayer的这张图:

【Android】- MediaPlayer错误之MediaPlayer start called in state 0_第1张图片


1.MediaPlayer.create(this, R.raw.music);设置数据源

       出现MediaPlayer start called in state 0 主要原因在于start()出现问题,问题在于start()播放开始之前没有调用prepare()。在初始化MediaPlayer时,通过create()方法设置数据源,则不能写mediaPlayer.prepare()方法,只要成功返回播放器就不需要prepare,但是:如果反复多次调用了start()和stop()方法,就会出现MediaPlayer start called in state 0错误,因此需要在start()之前必须重新prepare()的或stop()之后调用prepare(),如果使用pause()暂停则不需要在其之后调用prepare(),直接start()就可以。
代码如下:

@Override
public void onCreate() {
    mediaPlayer = MediaPlayer.create(this, R.raw.music);
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    boolean isPlaying = intent.getBooleanExtra("isPlaying", false);
    if (isPlaying&&!mediaPlayer.isPlaying()){
        mediaPlayer.start();
    }else if (!isPlaying&&mediaPlayer.isPlaying()){
        mediaPlayer.stop();
        try {
            mediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return super.onStartCommand(intent, flags, startId);
}

2.mediaPlayer.setDataSource("http://zphxl.tunnel.qydev.com/music/Burning.mp3");设置数据源

mediaPlayer.setDataSource()之后需要调用prepare(),才可以start(),不然会报错,但我们播放在线音频时,做好使用prepareAsync()。

/**
 * 创建一个类,并继承Binder,将暴露该类的方法写入其中
 */
public class MyMusicService extends Binder{
    public MusicBindService getMusicService(){
        return MusicBindService.this;
    }
}
/*实例化创建的MusicService*/
private IBinder iBinder = new MyMusicService();
@Override
public IBinder onBind(Intent intent) {
    return iBinder;
}
public void play(){
    mediaPlayer = new MediaPlayer();
    try {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {//确保在prepare()之前调用了stop()
            mediaPlayer.stop();
            mediaPlayer.reset();
        }
        mediaPlayer.setDataSource("http://zphxl.tunnel.qydev.com/music/Burning.mp3");
        mediaPlayer.setOnPreparedListener(preparedListener);
        mediaPlayer.prepareAsync();//在线播放音频,使用prepareAsync()
    } catch (IOException e) {
        e.printStackTrace();
    }
}
MediaPlayer.OnPreparedListener preparedListener = new MediaPlayer.OnPreparedListener() {

    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.start();
    }
};
public void stop(){
    if (mediaPlayer != null && mediaPlayer.isPlaying()) {//在播放状态才可以停止播放
        mediaPlayer.stop();
        mediaPlayer.reset();
    }
}

@Override
public boolean onUnbind(Intent intent) {

    return super.onUnbind(intent);
}

@Override
public void onDestroy() {
    super.onDestroy();
    mediaPlayer.release();
}



你可能感兴趣的:(Android)