Reputation: 323
I have a piano app working with this method:
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);
}
}
The issue is that if I press the keys too fast and several times i get errors like this:
E/MediaPlayer: error (1, -19)
These errors occur as I go on playing. But when I uninstall the app, something seems to reset, and I get less errors...Why is this happening and is there a solution for it?
Upvotes: 1
Views: 54
Reputation: 5480
As your code implies you are playing notes and not long MP3s, I suggest you use SoundPool
instead of MediaPlayer
. It is better suited for this kind of application as it pre-loads all the resources in advance.
An example of this kind of implementation:
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);
}
}
Upvotes: 1