简单的音频播放引擎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.   
  4. //Init audio manager asynchronously as it can take a few seconds  
  5. //The FXPlusMusicIfNoOtherAudio mode will check if the user is  
  6. // playing music and disable background music playback if   
  7. // that is the case.  
  8. [CDAudioManager initAsynchronously:kAMM_FxPlusMusicIfNoOtherAudio];  
  9.   
  10. //Wait for the audio manager to initialise  
  11. while ([CDAudioManager sharedManagerState] != kAMStateInitialised)   
  12. {  
  13.     [NSThread sleepForTimeInterval:0.1];  
  14. }  
  15.   
  16. //At this point the CocosDenshion should be initialized  
  17. // Grab the CDAudioManager and check the state  
  18. CDAudioManager *audioManager = [CDAudioManager sharedManager];  
  19. if (audioManager.soundEngine == nil ||   
  20.     audioManager.soundEngine.functioning == NO) {  
  21.     CCLOG(@"CocosDenshion failed to init, no audio will play.");  
  22.     managerSoundState = kAudioManagerFailed;   
  23. else {  
  24.     [audioManager setResignBehavior:kAMRBStopPlay autoHandle:YES];  
  25.     soundEngine = [SimpleAudioEngine sharedEngine];  
  26.     managerSoundState = kAudioManagerReady;  
  27.     CCLOG(@"CocosDenshion is Ready");  
  28. }  

当对象成功创建以后,便可以使用这个对象了,预加载的过程会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

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


你可能感兴趣的:(简单的音频播放引擎CocosDenshion)