在课堂上我有这个领域:
private MediaPlayer mp = new MediaPlayer();
每次需要播放某些声音时,都会调用以下方法:
private synchronized void playSound(int sound) {
try {
mp.setDataSource(context, Uri.parse("android.resource://" + context.getPackageName() + "/" + sound));
} catch (IOException e) {
e.printStackTrace();
}
mp.prepareAsync();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
if (mp != null) {
while (mp.isPlaying()) {
// waiting while it is already playing
}
mp.stop();
mp.reset();
}
mp.start();
}
});
问题是这个例外:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.app, PID: 28893
java.lang.IllegalStateException
at android.media.MediaPlayer._setDataSource(Native Method)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1128)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1012)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:968)
at com.speechsynthesizer.TextProcessor.playSound(TextProcessor.java:92)
URI来源正常,我已经检查过了。
答案 0 :(得分:0)
Javadocs说:
IllegalStateException - 如果以无效状态调用
查看除IDLE
之外的valid/invalid states table任何状态都会导致此异常。我的猜测是playSound
被调用了两次,因为它已经在第二次准备/播放时状态无效。