天天看點

簡單的音頻播放引擎CocosDenshion

下載下傳位址:http://download.csdn.net/detail/daiyelang/6628605

使用:下載下傳後導入項目中

一、CCMenu

遊戲中的菜單必不可少,CCMenu正是你想要的。

要建立CCMenu,你必須有CCMenuItem對象,CCMenuItem便是你菜單中的某個選項,可以為圖檔、文字等

cocos2d為menu item提供了必要的轉換方法,比如CCMenuItemLabel你可以通過CCLabelBMFont得到;遊戲中某些開關,比如聲音開關可以用CCMenuItemToggle對象

每一個CCMenuItem都可以在建立的時候綁定某個對象的方法,當這個CCMenuItem被點選的時候會觸發這個方法

二、CocosDenshion

cocos2d中內建了CocosDenshion,不過遊戲中我們一般都是整個背景音樂或者來點音效,是以我們隻需要用SimpleAudioEngine就可以了。

SimpleAudioEngine其實是對CDAudioManager進行了一些封裝,我們暫時不去關注細節實作,先看看怎麼使用

這是一段通用的代碼,用來確定建立SimpleAudioEngine對象成功

[cpp]  view plain copy

  1. // Indicate that we are trying to start up the Audio Manager  
  2. [CDSoundEngine setMixerSampleRate:CD_SAMPLE_RATE_MID];  
  3. //Init audio manager asynchronously as it can take a few seconds  
  4. //The FXPlusMusicIfNoOtherAudio mode will check if the user is  
  5. // playing music and disable background music playback if   
  6. // that is the case.  
  7. [CDAudioManager initAsynchronously:kAMM_FxPlusMusicIfNoOtherAudio];  
  8. //Wait for the audio manager to initialise  
  9. while ([CDAudioManager sharedManagerState] != kAMStateInitialised)   
  10. {  
  11.     [NSThread sleepForTimeInterval:0.1];  
  12. }  
  13. //At this point the CocosDenshion should be initialized  
  14. // Grab the CDAudioManager and check the state  
  15. CDAudioManager *audioManager = [CDAudioManager sharedManager];  
  16. if (audioManager.soundEngine == nil ||   
  17.     audioManager.soundEngine.functioning == NO) {  
  18.     CCLOG(@"CocosDenshion failed to init, no audio will play.");  
  19.     managerSoundState = kAudioManagerFailed;   
  20. } else {  
  21.     [audioManager setResignBehavior:kAMRBStopPlay autoHandle:YES];  
  22.     soundEngine = [SimpleAudioEngine sharedEngine];  
  23.     managerSoundState = kAudioManagerReady;  
  24.     CCLOG(@"CocosDenshion is Ready");  
  25. }  

當對象成功建立以後,便可以使用這個對象了,預加載的過程會hang住程式,是以不要在主線程中進行聲音的預加載

[soundEnginepreloadBackgroundMusic:trackFileName];

[soundEngineplayBackgroundMusic:trackFileNameloop:YES];

[cpp]  view plain copy

  1. [CDSoundEngine setMixerSampleRate:CD_SAMPLE_RATE_MID];  

設定采樣率,可以在CocosDenshion.h中看到各種采樣率的宏定義,可以根據自己的聲音檔案來設定,注意:當你聲音檔案低于設定的采樣率時,會使用設定的采樣率而産生記憶體的浪費。

[cpp]  view plain copy

  1. [CDAudioManager initAsynchronously:kAMM_FxPlusMusicIfNoOtherAudio];  

共有這幾種模式:

kAMM_FxOnly,//!Other apps will be able to play audio

kAMM_FxPlusMusic,//!Only this app will play audio

kAMM_FxPlusMusicIfNoOtherAudio,//!If another app is playing audio at start up then allow it to continue and don't play music

kAMM_MediaPlayback,//!This app takes over audio e.g music player app

kAMM_PlayAndRecord//!App takes over audio and has input and output

都很好懂,就不一一翻譯了