我有一个使用这种方法的钢琴应用程序:
public void play(String note) {
score++;
score();
try {
mp = MediaPlayer.create(this, getResources().getIdentifier(note, "raw", getPackageName()));
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer media) {
media.release();
}
});
} catch (Exception e) {
Log.e("Error", "error playing file : " + note + "\n" + e);
}
}
问题是,如果我按得太快并且多次按下按键,我会得到这样的错误:
E/MediaPlayer: error (1, -19)
这些错误在我继续演奏时出现。但是,当我卸载该应用程序时,某些东西似乎已重置,并且我收到的错误更少...为什么会发生这种情况,是否有解决方案?
最佳答案
由于您的代码暗示您正在播放音符而不是长 MP3,我建议您使用 SoundPool
而不是 MediaPlayer
。它更适合这种应用程序,因为它会提前预加载所有资源。
这种实现的一个例子:
private SoundPool soundPool;
private HashMap<String, Integer> soundNameToSoundIdMap;
private void initSoundMap() {
soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
soundNameToSoundIdMap = new HashMap<String, Integer>();
soundNameToSoundIdMap.put("note_a", loadSound(getContext(), R.raw.note_a));
soundNameToSoundIdMap.put("note_b", loadSound(getContext(), R.raw.note_b));
}
private int loadSound(Context context, int resId) {
return soundPool.load(context, resId, 1);
}
public void play(String note) {
score++;
score();
Integer soundId = soundNameToSoundIdMap.get(note);
if (soundId != null){
soundPool.play(soundId.intValue(), 100, 100, 1, 0, 0);
}
}
关于android - 具有多个 mp3 文件问题的媒体播放器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40939016/