Cocos2D-iphone 开发之 音效引擎 CocosDenshion

这篇博文介绍cocos2d-iphone中的音效引擎CocosDenshion。

Cocos2D-iphone 开发之 音效引擎 CocosDenshion_第1张图片

CocosDenshion引擎是一套用于声音控制的类库,支持iOS 和 Mac OS系统。在Cocos2D中已经内置该引擎。

CocosDenshion是一个低延时的音效引擎,用来播放游戏中的音效,同时可以修改音调,音高等,同时还提供一个音效管理器,可以播放多声道音乐,负责iOS的声音进程管理。

CocosDenshion音效引擎提供多个API。

(1)CDSoundEngine在对底层,提供低延时的音效播放引擎以及一些面向对象的API

(2)CDAudioManager基于CDSoundEngine构建,添加多声道音乐播放功能。

(3)SimpleAudioEngine提供一个简化的声音控制API,可以极大的简化游戏中的声音控制。

使用CocosDenshion,可以充分发挥AVAudioPlayer和OpenAL的强大威力,同时可以不用考虑如何使用低级别的API。



(1)

SimpleAudioEngine使用方法:是Cocos2D中添加背景音乐最简单的方式。(单例类)    


The SimpleAudioEngine doesn’tallow you to control channels, so it’ll just play your sound effects in one ofthe channels it has allocated internally.

 Eventually all channels are playingaudio. In that case, when a new audio file is to be played and all channels arealready playing, SimpleAudioEngine will

 cancel one of the existing audio files.On occasion this will be your background music.

解释:SimpleAudioEngine不允许你控制声道,所以播放声音在那个声道是内部分配的,假如所有的声道都在播放声音,当一个新的声音想要加入播放,那么

SimpleAudioEngine的处理是取消一个正在播放的声音,有可能就取消你的背景声音。

打开SimpleAudioEngine类的头文件就可以知道如何使用了。


@interface SimpleAudioEngine : NSObject <CDAudioInterruptProtocol> {

	BOOL	mute_;
	BOOL	enabled_;
}

/** Background music volume. Range is 0.0f to 1.0f. This will only have an effect if willPlayBackgroundMusic returns YES */
@property (readwrite) float backgroundMusicVolume;
/** Effects volume. Range is 0.0f to 1.0f */
@property (readwrite) float effectsVolume;
/** If NO it indicates background music will not be played either because no background music is loaded or the audio session does not permit it.*/
@property (readonly) BOOL willPlayBackgroundMusic;

/** returns the shared instance of the SimpleAudioEngine object */
+ (SimpleAudioEngine*) sharedEngine;

/** Preloads a music file so it will be ready to play as background music */
-(void) preloadBackgroundMusic:(NSString*) filePath;

/** plays background music in a loop*/
-(void) playBackgroundMusic:(NSString*) filePath;
/** plays background music, if loop is true the music will repeat otherwise it will be played once */
-(void) playBackgroundMusic:(NSString*) filePath loop:(BOOL) loop;
/** stops playing background music */
-(void) stopBackgroundMusic;
/** pauses the background music */
-(void) pauseBackgroundMusic;
/** resume background music that has been paused */
-(void) resumeBackgroundMusic;
/** rewind the background music */
-(void) rewindBackgroundMusic;
/** returns whether or not the background music is playing */
-(BOOL) isBackgroundMusicPlaying;

/** plays an audio effect with a file path*/
-(ALuint) playEffect:(NSString*) filePath;
/** stop a sound that is playing, note you must pass in the soundId that is returned when you started playing the sound with playEffect */
-(void) stopEffect:(ALuint) soundId;
/** plays an audio effect with a file path, pitch, pan and gain */
-(ALuint) playEffect:(NSString*) filePath pitch:(Float32) pitch pan:(Float32) pan gain:(Float32) gain;
/** preloads an audio effect */
-(void) preloadEffect:(NSString*) filePath;
/** unloads an audio effect from memory */
-(void) unloadEffect:(NSString*) filePath;
/** Gets a CDSoundSource object set up to play the specified file. */
-(CDSoundSource *) soundSourceForFile:(NSString*) filePath;

/** Shuts down the shared audio engine instance so that it can be reinitialised */
+(void) end;

@end

其中主要包括的属性有:mute(静音),背景音乐音量,音效音量等。

类方法:sharedEngine(用于获取SimpleAudioEngine单例对象

实例方法:播放背景音乐的相关方法,播放音效的相关方法

例如(循环播放背景音乐):

    [[SimpleAudioEngine sharedEngine]playBackgroundMusic:@"bgmusic.mp3" loop:YES];


(2)

大多数情况下SimpleAudioEngine就可以满足游戏开发的需要,但是有时候需要更多复杂的音效的时候,就会用到CDSoundEngine和CDAudioManager。

CDSoundEngine允许同时播放多个声音,可以将声音分类,实时修改声音的音高,音源位置和音量(音效),同时支持在应用程序启动时预加载声音。(这个类是放在CocosDenshion文件中的)

CDAudioManager主要进行对音效的管理(设定播放模式mode)和播放背景音乐,他支持左右两个声道。

/** CDAudioManager supports two long audio source channels called left and right*/
typedef enum {
	kASC_Left = 0,
	kASC_Right = 1
} tAudioSourceChannel;

二者之间的关系吧:在CDAudioManager类中就包含了一个CDSoundEngine的属性。

下面通过一个例子来解释吧!

在AppDelegate.m的

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法中进行声音文件的预加载。

//这里用CDAudioManager单例类的soundEngine属性初始化一个CDSoundEngine
    //其实这里可以省略的,在后面需要用到soundEngine的时候,直接[CDAudioManager sharedManager].soundEngine就可以了
    //不过这样写的话可简约代码和清楚理解
    CDSoundEngine *sse = [CDAudioManager sharedManager].soundEngine;
    
    /**
     A source group is another name for a channel
     //source group是channel的一个别名
     
     Here I have 2 channels, the first index allows for only a single effect... my background music
     The second channel I have reserved for my sound effects.  This is set to 31 because you can
     have up to 32 effects at once
     //这里有两个声道,一共支持载入音效32个,不可以超过。
     //第一个声道仅支持一个音效播放[NSNumber numberWithInt:1],播放背景音乐
     //第二个声道播放音效,[NSNumber numberWithInt:31] 表示支持31个音效
     */
    
    //设置声道channel(source group)
    NSArray *sourceGroups = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:31], nil];
    [sse defineSourceGroups:sourceGroups];
    
    //Initialise audio manager asynchronously as it can take a few seconds
    //异步加载音效
    /** Different modes of the engine  音效引擎的模式
     typedef enum {
     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
     } tAudioManagerMode;
     */
    
    //Initializes the engine asynchronously with a mode
    [CDAudioManager initAsynchronously:kAMM_FxPlusMusicIfNoOtherAudio];
    
    //Load sound buffers asynchrounously 异步加载声音缓存
    NSMutableArray *loadRequests = [[[NSMutableArray alloc] init] autorelease];
    
    /**
     Here we set up an array of sounds to load
     定义了一组声音文件准备加载
     Each CDBufferLoadRequest takes an integer as an identifier (to call later)and the file path.
     每一个CDBufferLoadRequest都使用一个integer去标识一个声音文件的路径(file path)以后可以使用这个整型数去调用声音文件     
     */
    
    //注意所载入的音效不可以超过32个
    [loadRequests addObject:[[CDBufferLoadRequest alloc] init:SND_BG_LOOP filePath:@"bgmusic.mp3"]];
    [loadRequests addObject:[[CDBufferLoadRequest alloc] init:SND_ROCKET filePath:@"rocket.mp3"]];
    [loadRequests addObject:[[CDBufferLoadRequest alloc] init:SND_CANNON filePath:@"cannon.mp3"]];
    [loadRequests addObject:[[CDBufferLoadRequest alloc] init:SND_BLAST filePath:@"explosion.mp3"]];
    
    //异步加载这些声音
//    [sse loadBuffersAsynchronously:loadRequests];
    [[CDAudioManager sharedManager].soundEngine loadBuffersAsynchronously:loadRequests];
    

定义一些宏定义

#define CGROUP_BG       kASC_Left    // Channel for background music
#define CGROUP_EFFECTS  kASC_Right   // Channel for sound effects
#define SND_BG_LOOP 1     // Identifier for background music audio
#define SND_ROCKET   2     // Identifier for click sound effect
#define SND_CANNON  3
#define SND_BLAST   4
// Helper macro for playing sound effects
#define playEffect(__ID__)      [[CDAudioManager sharedManager].soundEngine playSound:__ID__ sourceGroupId:CGROUP_EFFECTS pitch:1.0f pan:0.0f gain:1.0f loop:NO]

播放背景音乐

[[CDAudioManager sharedManager] playBackgroundMusic:@"bgmusic.mp3" loop:YES];
    //也可以使用播放音效的方式来播放背景音乐
//    [[CDAudioManager sharedManager].soundEngine playSound:SND_BG_LOOP sourceGroupId:CGROUP_BG pitch:1.0 pan:0.0 gain:1.0 loop:NO];

在CDAudioManager文件中定义了一些关于播放背景音乐有关的方法:

/** Plays music in background. The music can be looped or not
 It is recommended to use .aac files as background music since they are decoded by the device (hardware).
 */
-(void) playBackgroundMusic:(NSString*) filePath loop:(BOOL) loop;
/** Preloads a background music */
-(void) preloadBackgroundMusic:(NSString*) filePath;
/** Stops playing the background music */
-(void) stopBackgroundMusic;
/** Pauses the background music */
-(void) pauseBackgroundMusic;
/** Rewinds the background music */
-(void) rewindBackgroundMusic;
/** Resumes playing the background music */
-(void) resumeBackgroundMusic;
/** Returns whether or not the background music is playing */
-(BOOL) isBackgroundMusicPlaying;

//设置背景音乐完成监听器
-(void) setBackgroundMusicCompletionListener:(id) listener selector:(SEL) selector;

播放音效

//   playEffect(SND_BLAST);
    [[CDAudioManager sharedManager].soundEngine playSound:SND_BLAST sourceGroupId:CGROUP_EFFECTS pitch:1.0f pan:0.0f gain:1.0f loop:NO];


以上就主要介绍了两种播放音效的方法,第一中使用SimpleAudioEngine,简单方便;假如播放音效有一些复杂变化和预处理,就可以使用第二种方法,使

用CDSoundEngine和CDAudioManager。


(3)关于声音播放的设置,一般情况下,游戏中都支持用户对声音进行设置,多数是游戏音效的关闭和打开。

在上面介绍的三个类中都有mute(静音)这个属性(BOOL类型),假如你单纯设置mute=true的话,那么游戏中的所有声音(包括背景音乐和音效)都会听不

到,但是有时候游戏中只是想单方面禁止背景音乐或者单方面禁止音效,那么这个时候一般的处理是设置音量volume(float类型),把音量设置为0,即可以

单方面禁止背景音乐或者音效了。


关于更多CocosDenshion的使用请参看引擎源文件。大笑



你可能感兴趣的:(cocos2d,CocosDenshion,CDAudioManager,CDSoundEngine)