安卓開發(fā)游戲音效代碼實(shí)例

字號(hào):


    //音效的音量
    int streamVolume;
    //定義SoundPool 對(duì)象 private SoundPool soundPool;
    //定義HASH表 private HashMap<Integer, Integer> soundPoolMap;
    /*************************************************************** * Function: initSounds();
    * Parameters: null
    * Returns: None.
    * Description: 初始化聲音系統(tǒng)
    * Notes: none.
    ***************************************************************/
    public void initSounds() { //初始化soundPool 對(duì)象,第一個(gè)參數(shù)是允許有多少個(gè)聲音流同時(shí)播放,第2個(gè)參數(shù)是聲音類型,第三個(gè)參數(shù)是聲音的品質(zhì) soundPool = new SoundPool(100, AudioManager.STREAM_MUSIC, 100);
    //初始化HASH表 soundPoolMap = new HashMap<Integer, Integer>();
    //獲得聲音設(shè)備和設(shè)備音量 AudioManager mgr = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
    streamVolume = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
    }
    /*************************************************************** * Function: loadSfx();
    * Parameters: null
    * Returns: None.
    * Description: 加載音效資源
    * Notes: none.
    ***************************************************************/
    public void loadSfx(int raw, int ID) { //把資源中的音效加載到指定的ID(播放的時(shí)候就對(duì)應(yīng)到這個(gè)ID播放就行了) soundPoolMap.put(ID, soundPool.load(context, raw, ID));
    }
    /*************************************************************** * Function: play();
    * Parameters: sound:要播放的音效的ID, loop:循環(huán)次數(shù)
    * Returns: None.
    * Description: 播放聲音
    * Notes: none.
    ***************************************************************/
    public void play(int sound, int uLoop) { soundPool.play(soundPoolMap.get(sound), streamVolume, streamVolume, 1, uLoop, 1f); }