2013-04-30 140 views
1

我有一个关于在an​​droid中播放/暂停多个音频文件的问题。我们的应用程序使用restful API从服务器加载音频文件。在api中将有链接访问音频文件(如http://www.common.com/folder/folder1/file1.mp4)。我们的应用程序将在android活动列表视图中列出音频文件的名称。一旦用户点击file1,那么file1开始播放。当用户点击另一个文件时,file1会暂停播放并开始播放所点击的文件。这应该发生在所有文件中。在android中播放或暂停多个音频文件

我们的疑问是,我们是否需要使用媒体播放器的多个实例来播放不同的音频文件。像每个文件的新MediaPlayer()对象一样?我们可以通过一个MediaPlayer实例来处理这种情况吗? SoundPool在这种情况下有帮助吗?

回答

1

是的,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; 
    } 
} 
+0

感谢您的回答。但是,当我们使用soundpool时,它不会将播放的当前位置和音频的总持续时间返回给我。这些细节我用于更新进度条... – developerXXX 2013-05-08 09:20:30

+0

SoundPool用于小型音频文件。 – 2016-01-13 06:39:49