同时播放和暂停多个音频文件

Play and pause multiple audio file at the same time

我正在开发一个音乐播放器应用程序,在我的应用程序中,我想通过单击一个按钮来播放所有 mp3 文件。我可以用 MediaPlayer 做到这一点,但无法使用暂停按钮暂停所有歌曲。我怎样才能同时暂停所有正在播放的歌曲

播放按钮

  for (int i = 0; i < InstrumentCountSize; i++) {
        mp = new MediaPlayer();
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mp.setDataSource(instruments_count.get(i));
        mp.prepare();
        mp.start();

    }

暂停按钮

   if (mp != null) {
        try {
            mp.stop();
            mp.reset();
            mp.release();
            mp = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

您的单个 mp 变量只能引用单个 MediaPlayer,因此您的暂停按钮代码只是试图释放 last MediaPlayer 您创建的实例。您需要保留对所有 MediaPlayer 个实例的引用。

[更新]

像这样的东西应该效果更好:

// This needs to replace your "mp" variable.
List<MediaPlayer> mps = new ArrayList<MediaPlayer>();


// Play button code ....
// Make sure all the media are prepared before playing
for (int i = 0; i < InstrumentCountSize; i++) {
    MediaPlayer mp = new MediaPlayer();
    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mp.setDataSource(instruments_count.get(i));
    mp.prepare();
    mps.add(mp);
}
// Now that all the media are prepared, start playing them.
// This should allow them to start playing at (approximately) the same time.
for (MediaPlayer mp: mps) {
    mp.start(); 
}


// Pause button code ...
for (MediaPlayer mp: mps) {
    try { 
        mp.stop(); 
        mp.reset(); 
        mp.release(); 
    } catch (Exception e) {
        e.printStackTrace();
    } 
}
mps.clear();