2014年2月28日

SoundPool 音效播放

SoundPool soundPool


soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 5);

第一個參數 SoundPool 內總共放置的音效數目。
第二個參數 串流類型。
第三個參數 音效品質,預設為1。



音效檔來源設定
soundPool_ID= soundPool.load(mainActivity, R.raw.music01 , 1);
讀取效果音resource的檔案,檔名記得要小寫並且小於1mb


SoundPool.play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)
soundPool.play(soundPool_ID= , 1.0F, 1.0F, 0, 0, 1.0F);
第一個參數 音效檔來源
第二個參數 左喇叭音量
第三個參數 右喇叭音量
第四個參數 固定用 0
第五個參數 0 為不重複,-1 為無限重複
第六個參數 播放速度,可用 0.5 到 2


SoundPool優點為CPU資源使用率低,反應延遲較少。
用來播放一些短短的音效、急促的效果音很好用。


public void initSounds() {
soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 100);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
          public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                   // TODO Auto-generated method stub
          playSound(1,2);
                  }
    });
    soundPoolMap = new HashMap<Integer, Integer>();  
    soundPoolMap.put(1, soundPool.load(getContext(), R.raw.gamestart, 1));
}

public void playSound(int sound, int loop) {
Log.e("WelcomeView", "playSound()");
AudioManager mgr = (AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE);  
   float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);  
   float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);      
   float volume = streamVolumeCurrent / streamVolumeMax;
   soundPool.play(soundPoolMap.get(sound), volume, volume, 1, loop, 1.0F);
}

沒有留言:

張貼留言