Android MediaPlayer出现prepareasync called in state 8的错误的解决方法
使用android MediaPlayer播放音频文件时,有时会出现prepareasync called in state 8错误。
以下方法可以避免这个异常出现:
private void playAudio(String audioUri){
Uri uri = Uri.parse(audioUri);
mMediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
try {
//在播放之前先判断playerMusic是否被占用,防止报错
if (mMediaPlayer != null) {
mMediaPlayer.stop();
}
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
另一种解决办法:
try {
if (!isPlaying) {
isPlaying = true;
//装载资源
mediaPlayer = MediaPlayer.create(PlaySDMp3Activity.this, R.raw.trouble);
isReleased = false;
mediaPlayer.setLooping(true);
mediaPlayer.start();
mTextView.setText("当前正在播放音乐!");
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MediaPlayer.create(context,resId)//这个方式配置数据源后,就完成了初始化,所以不用prepare可以直接start了