android 开发音乐播放器 MediaPlayer.prepare();报错

偷菜的小喵
  • 71

android 播放音乐 MediaPlayer.prepare();报错。点击多次后才崩溃

/**
     * 播放音乐
     * @param path
     */

    public void play(String path){
        if(mediaPlayer!=null){
            mediaPlayer.reset();
            try {
                mediaPlayer.setDataSource(path);
                mediaPlayer.prepare();
                mediaPlayer.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

报错:

 FATAL EXCEPTION: main
       Process: cn.com.mymusic, PID: 11807
       java.lang.IllegalStateException
       at android.media.MediaPlayer._prepare(Native Method)
       at android.media.MediaPlayer.prepare(MediaPlayer.java:1143)
       at cn.com.mymusic.MusicService.play(MusicService.java:101)
回复
阅读 9.7k
3 个回答

why not use 'mediaPlayer.prepareAsync()',then you can setup the callback just like this:

mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mediaPlayer.start();
        }
});

it worked fine to me ,i hope it can help you ~

prepare成功 之后再start.

姗姗12345
  • 2
新手上路,请多包涵

播放本地文件 用 mediaPlayer.prepare()
播放网络 mediaPlayer.prepareAsync()

宣传栏