android - 具有多个 mp3 文件问题的媒体播放器

标签 android android-mediaplayer

我有一个使用这种方法的钢琴应用程序:

 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/

相关文章:

java - 安卓;按钮声音在默认按钮声音后播放

java - 媒体播放器不播放音频

c# - 适用于 Android 和 Windows Phone 7 的脚本语言

android - Firebase 中有没有一种方法可以自动将 id 列表交换到对象中

Android DDMS 假调用已禁用

android - Android早期版本如何实现setVideoScalingMode

java - MediaPlayer 中的 IllegalStateException

android - Android:同步两个mediaPlayers(一个又一个播放)-消除差距

android - 如何在匈牙利语中使用 Android?

android - 禁用 Android 中的搜索按钮