多次播放MediaPlayer

时间:2018-11-11 17:33:45

标签: android android-mediaplayer

我有以下课程,每按一次按钮,就会弹钢琴音符(A,C,D,G):

public class AudioSoundPlayer {

    private SparseArray<PlayThread> threadMap;
    private Context context;
    private static final SparseArray<String> SOUND_MAP = new SparseArray<>();
    public static final int MAX_VOLUME = 100, CURRENT_VOLUME = 90;

    static {
        SOUND_MAP.put(1, "G");
        SOUND_MAP.put(2, "D");
        SOUND_MAP.put(3, "C");
        SOUND_MAP.put(4, "A");
    }

    public AudioSoundPlayer(Context context) {
        this.context = context;
        threadMap = new SparseArray<>();
    }

    public void playNote(int note) {
        if (!isNotePlaying(note)) {
            PlayThread thread = new PlayThread(note);
            thread.start();
            threadMap.put(note, thread);
        }
    }

    public void stopNote(int note) {
        PlayThread thread = threadMap.get(note);

        if (thread != null) {
            threadMap.remove(note);
        }
    }

    public boolean isNotePlaying(int note) {
        return threadMap.get(note) != null;
    }

    private class PlayThread extends Thread {
        int note;
        MediaPlayer player;

        public PlayThread(int note) {
            this.note = note;
        }

        @Override
        public void run() {
            try {
                String path = SOUND_MAP.get(note) + ".wav";
                AssetManager assetManager = context.getAssets();
                AssetFileDescriptor afd = assetManager.openFd(path);

                player = new MediaPlayer();
                player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(),
                        afd.getLength());
                player.prepare();
                player.start();
                player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        //mp.reset();
                        // mp.release();
                        player.reset();
                        player.release();
                        player = null;
                    }
                });
                player.setLooping(false);

            } catch (Exception e) {

            } finally {

            }
        }
    }

}

在我的活动中,我有4个按钮,其中每个按钮都有一个setOnTouchListenersoundPlayer.playNote(1);soundPlayer.stopNote(1);,分别在Action为Down或Up时使用。如果我玩得很爽,它会很好地工作,但是一旦我开始推动它并加快演奏速度,它就开始无法正常工作,并且只返回错误“ E/MediaPlayer: Error (1,-19)”。我不确定这种播放声音的方式是否对我正在提出的建议是最好的选择?

0 个答案:

没有答案