2012-07-07 264 views
1

我需要在活動運行時運行很多小聲音。 某些文件每隔固定的時間間隔播放(例如5秒) 當屏幕被觸摸時,某些文件將在下一次啓動完成時(例如sound1,sound2,sound3)按順序播放。Android - 按順序播放多個聲音

總聲音大約是35個短mp3文件(最長3秒)。

實現此目的的最佳方法是什麼?

感謝

回答

0

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); 
    } 
} 
1

MediaPlayerPlaybackCompleted狀態,所以當一個音頻完成後,就可以開始播放另一種

public void setOnCompletionListener (MediaPlayer.OnCompletionListener listener) 

source

,我會嘗試ThreadAsyncTask分別扮演不同的音頻線

+0

謝謝,我相信應該有更好的方法來做到這一點。這是因爲我將不得不爲每個文件「準備」中間球員。這就是爲什麼我提到了手頭上的文件數量。 – askanaan 2012-07-07 12:59:55