是的,如果您想要这个播放/暂停过程, Soundpool可能会有所帮助。
首先,您创建一个跨活动实例保留的声音管理器,以及一个将音频文件链接到 ID 的映射。
// Replace 10 with the maximum of sounds that you would like play at the same time.
SoundPool soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 100);
HashMap<String, Integer> stringToSoundID = new HashMap<String, Integer>();
HashMap<Integer, Integer> soundIdToStreamID = new HashMap<Integer, Integer>();
Integer streamIDbeingPlayed= -1;
然后将所有声音加载到 soundPool 中,保持文件和声音 ID 之间的链接。
for(String filePath: Files) {
int soundID = soundPool.load(filePath, 1);
stringToSoundID.put(filePath, soundID );
}
然后,您可以使用函数来播放/暂停文件,如下所示:
void playFile(String filePath) {
if(streamIDbeingPlayed!= -1) {
soundPool.pause(streamIDbeingPlayed);
}
Integer soundID = stringToSoundID.get(filePath);
Integer streamID = soundIdToStreamID.get(soundID);
if(streamID == null) {
streamIDbeingPlayed = soundPool.play (soundID, 1, 1, 1, -1, 1);
soundIdToStreamID.put(soundID, streamIDbeingPlayed);
} else {
soundPool.resume(streamID);
streamIDbeingPlayed = streamID;
}
}