如何在android中同时播放多个声音

时间:2013-11-10 16:32:36

标签: android android-music-player

我尝试了下面的代码,同时播放了3个音符。单击按钮即可触发该方法。但是,在下一次单击事件中,它只播放一个音符,应用程序崩溃。每次点击按钮,我想播放3个不同的音符。(我选择那些randomaly)

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

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

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

    player.release();

是重载的玩家实例吗?我应该以不同的方式发布它? 还是别的什么?

提前谢谢 利昂

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:1)

使用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();
    }
}