Android - 按顺序播放多个声音

问题描述:

我需要在活动运行时运行很多小声音。 某些文件每隔固定的时间间隔播放(例如5秒) 当屏幕被触摸时,某些文件将在下一次启动完成时(例如sound1,sound2,sound3)按顺序播放。Android - 按顺序播放多个声音

总声音大约是35个短mp3文件(最长3秒)。

实现此目的的最佳方法是什么?

感谢

SoundPool是通常用于播放多个短音。你可以加载onCreate()中的所有声音,将它们的位置存储在HashMap中。

创建的Soundpool

public static final int SOUND_1 = 1; 
public static final int SOUND_2 = 2; 

SoundPool mSoundPool; 
HashMap<Integer, Integer> mHashMap; 

@Override 
public void onCreate(Bundle savedInstanceState){ 
    mSoundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 100); 
    mSoundMap = new HashMap<Integer, Integer>(); 

    if(mSoundPool != null){ 
    mSoundMap.put(SOUND_1, mSoundPool.load(this, R.raw.sound1, 1)); 
    mSoundMap.put(SOUND_2, mSoundPool.load(this, R.raw.sound2, 1)); 
    } 
} 

然后,当你需要与你的声音的恒定值,播放声音,简单的调用playSound()。

/* 
*Call this function from code with the sound you want e.g. playSound(SOUND_1); 
*/ 
public void playSound(int sound) { 
    AudioManager mgr = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE); 
    float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC); 
    float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC); 
    float volume = streamVolumeCurrent/streamVolumeMax; 

    if(mSoundPool != null){ 
     mSoundPool.play(mSoundMap.get(sound), volume, volume, 1, 0, 1.0f); 
    } 
} 

MediaPlayerPlaybackCompleted状态,所以当一个音频完成后,就可以开始播放另一种

public void setOnCompletionListener (MediaPlayer.OnCompletionListener listener) 

source

,我会尝试ThreadAsyncTask分别扮演不同的音频线

+0

谢谢,我相信应该有更好的方法来做到这一点。这是因为我将不得不为每个文件“准备”中间球员。这就是为什么我提到了手头上的文件数量。 – askanaan 2012-07-07 12:59:55