This blog post describes the sound engine cocosdenshion in the cocos2d-iphone.
The cocosdenshion engine is a class library for sound control, supporting iOS and Mac OS systems. The engine has been built in cocos2d.
Cocosdenshion is a low-latency sound engine used to play in-game sound effects. It can also modify the tone and pitch. It also provides a sound effect manager to play multi-channel music, manages IOS sound processes.
Cocosdenshion sound engine provides multiple APIs.
(1) cdsoundengine provides low-latency sound playback engines and some object-oriented APIs at the underlying layer.
(2) cdaudiomanager is built based on cdsoundengine and adds the multi-channel music playing function.
(3) simpleaudioengine provides a simplified sound control API that greatly simplifies the sound control in the game.
With cocosdenshion, you can give full play to the power of avaudioplayer and openal, without considering how to use low-level APIs.
(1)
Simpleaudioengine usage: it is the easiest way to add background music in cocos2d. (Singleton class)
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.
Explanation: simpleaudioengine does not allow you to control the audio channel, so the playing sound is allocated internally. If all the audio channels are playing the sound, when a new sound wants to be played
Simpleaudioengine cancels a playing sound and may cancel your background sound.
Open the header file of the simpleaudioengine class to know how to use it.
@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
The main attributes include: Mute (mute), Background Music volume, and sound volume.
Class Method: sharedengine (used to obtain simpleaudioengine singleton object)
Example method: Method for playing background music and method for Playing Sound Effects
For example ):
[[SimpleAudioEngine sharedEngine]playBackgroundMusic:@"bgmusic.mp3" loop:YES];
(2)
In most cases, simpleaudioengine can meet the needs of game development, but sometimes cdsoundengine and cdaudiomanager are used when more complex sound effects are required.
Cdsoundengine allows you to play multiple sounds at the same time, classify the sounds, modify the pitch, source position, and volume (sound effect) of the sounds in real time, and support pre-loading the sounds when the application starts. (This class is stored in the cocosdenshion file)
Cdaudiomanager manages sound effects (sets the playback mode) and plays background music. It supports both the left and right channels.
/** CDAudioManager supports two long audio source channels called left and right*/typedef enum {kASC_Left = 0,kASC_Right = 1} tAudioSourceChannel;
Relationship: The cdaudiomanager class contains a cdsoundengine attribute.
The following is an example!
In appdelegate. m
-(Bool) Application :( uiapplication *) Application didfinishlaunchingwitexceptions :( nsdictionary *) pre-load the sound file in the launchoptions method.
// Use the soundengine attribute of the cdaudiomanager Singleton class to initialize a cdsoundengine // It can be omitted here. When soundengine is used later, you can directly [cdaudiomanager sharedmanager]. soundengine can be written. // However, the code can be simplified and the cdsoundengine * SSE = [cdaudiomanager sharedmanager] can be clearly understood. soundengine;/** a source group is another name for a channel // The Source group is a channel alias here I have 2 channels, the first index allows for only a single effect... my background music the SE Cond channel I have reserved for my sound effects. this is set to 31 because you can have up to 32 effects at once // There are two channels, a total of 32 sound effects can be loaded, cannot exceed. // The first audio channel only supports playing one sound effect [nsnumber numberwithint: 1], playing background music // The second audio channel, [nsnumber numberwithint: 31] indicates 31 audio effects * // set the 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 // asynchronously load sound effects/** different modes of the engine sound effects Upload mode 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 asynchronously loads the sound cache nsmutablearray * loadrequests = [[[nsmutablearray alloc] init] autorelray]; /** here we set up an array of sounds to load defines a set of sound files to prepare to load each cdbufferloadrequest takes an integer as an identifier (to call later) and the file path. each cdbufferloadrequest uses an integer to identify the path of a sound file (file path) in the future, you can use this integer to call the sound file * // note that the loaded sound effects cannot exceed 32 [loadrequests addobject: [[cdbufferloadrequest alloc] init: snd_bg_loop filepath: @ "response"]; [loadrequests addobject: [[cdbufferloadrequest alloc] init: snd_rocket filepath: @ "rockettings"]; [loadrequests addobject: [[cdbufferloadrequest alloc] init: snd_cannon filepath: @ "cannontransfer"]; [loadrequests addobject: [[cdbufferloadrequest alloc] init: snd_blast filepath: @" explosiontransfer"]; // asynchronously load these sounds // [SSE loadbuffersasynchronously: loadrequests]; [[cdaudiomanager sharedmanager]. soundengine loadbuffersasynchronously: loadrequests];
Define macro definitions
#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]
Play background music
[[Cdaudiomanager sharedmanager] playbackgroundmusic: @ "bgmusicloud" loop: Yes]; // You can also play background music by playing audio. // [[cdaudiomanager sharedmanager]. soundengine playsound: snd_bg_loop sourcegroupid: cgroup_bg pitch: 1.0 Pan: 0.0 gain: 1.0 loop: No];
The cdaudiomanager file defines some methods related to playing background music:
/** 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; // set the background music completion listener-(void) setbackgroundmusiccompletionlistener :( ID) Listener selector :( SEL) selector;
Playing Sound Effects
// playEffect(SND_BLAST); [[CDAudioManager sharedManager].soundEngine playSound:SND_BLAST sourceGroupId:CGROUP_EFFECTS pitch:1.0f pan:0.0f gain:1.0f loop:NO];
The above mainly introduces two methods for playing sound effects. The first method is simpleaudioengine, which is simple and convenient. If the playing sound effects have some complicated changes and preprocessing, the second method can be used
Use cdsoundengine and cdaudiomanager.
(3) sound playback settings. Generally, users can set the sound in the game, most of which are about to disable and enable the game sound.
The above three classes all have the mute (mute) attribute (bool type). If you simply set mute = true, all the sounds in the game (including background music and sound effects) won't be heard.
Yes, but sometimes the game only wants to unilaterally disable background music or sound effects. In this case, the general processing is to set the volume (float type) and set the volume to 0.
Background Music or sound effects are banned.
For more information about how to use cocosdenshion, see the engine source file.