Cocos2D-iphone 開發之 音效引擎 CocosDenshion

來源:互聯網
上載者:User

這篇博文介紹cocos2d-iphone中的音效引擎CocosDenshion。


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> {BOOLmute_;BOOLenabled_;}/** 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的使用請參看引擎源檔案。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.