2

I tried the following code and the 3 notes were playing simultaneously. That method is triggered by a click on a button. However on the next click event it plays only one note and the app crashes. I want to play 3 different notes every time i click the button.(I chose those randomaly)

    player = MediaPlayer.create(this, resIdFirstNote);
    player.start();

    player = MediaPlayer.create(this, resIdSecondNote);
    player.start();

    player = MediaPlayer.create(this, resIdThirdNote);
    player.start();

    player.release();

is it the player instance that overloads? and i should release it differently ? or is it something else?

Thx in advance Leon

4

2 回答 2

2

使用android.media.SoundPool

public class MyActivity extends Acticity implements SoundPool.OnLoadCompleteListener {
    private SoundPool soundPool;
    private final int maxPlaying = 4;
    private final int volume = 1;
    private final int priority = 1;
    private final int no_loop = 0;
    private final float normal_playback_rate = 1f;
    private final Map<Integer, Integer> loadedSongsCache = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        soundPool = new SoundPool(maxPlaying, AudioManager.STREAM_MUSIC, 0);
        soundPool.setOnLoadCompleteListener(this);

        playSong(R.raw.somethingSound);
        playSong(R.raw.somethingSound2);
        playSong(R.raw.somethingSound3);
    }

    private void playSong(int resourceId){
        Integer sampleId = loadedSongsCache.get(resourceId);
        if (sampleId != null) {
            soundPool.play(sampleId, volume, volume, priority, no_loop, normal_playback_rate);
        } else {
            sampleId = soundPool.load(ColorMixActivity.this, songMix.getResourceId(), priority);
            loadedSongsCache.put(songMix.getResourceId(), sampleId);
        }
    }

    @Override
    public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
        if (status == 0)
            soundPool.play(sampleId, volume, volume, priority, no_loop, normal_playback_rate);
    }

    @Override
    protected void onDestroy() {
        soundPool.release();
        super.onDestroy();
    }
}
于 2015-03-11T20:53:18.087 回答
1

您需要创建三个媒体播放器:mp_1、mp_2、mp_3

在 onCreate() 方法中:

     MediaPlayer mp_1, mp_2, mp_3;

    mp_1 = new MediaPlayer();
    mp_2 = new MediaPlayer();
    mp_3 = new MediaPlayer();

    mp_1 = MediaPlayer.create(this, R.raw.mp_1);
    mp_2 = MediaPlayer.create(this, R.raw.mp_2);
    mp_3 = MediaPlayer.create(this, R.raw.mp_3);

            mp_1.start();
            mp_2.start();
            mp_3.start();
于 2013-11-10T16:56:01.377 回答