jueves, 6 de junio de 2013

Adding sound to your game with Cocos2D

If you are developing a game probably you need to add sound to your app.

As many other things, although Apple offers you a library to manage the audio, Cocos2D has it's own class: SimpleAudioEngine. It makes you really easy to insert background music and sound effects. It also allows you to modify basic properties such as pitch, pan and gain, and the possibility of looping a sound.

You can preload the sound (if you have a lot and heavy sounds). For loopings you need a CDSoundsource class:
soundEngine = [SimpleAudioEngine sharedEngine];
[soundEngine preloadEffect:@"sound1.mp3"];
[soundEngine preloadEffect:@"sound2.mp3"];
[soundEngine preloadBackgroundMusic:@"backgroundMusic.mp3"];
loopingSound = [[soundEngine soundSourceForFile:@"loopingSound.mp3"] retain];
loopingSound.looping = YES;
view raw gistfile1.m hosted with ❤ by GitHub
Playing effects and background is very easy:
[soundEngine playBackgroundMusic:@"backgroundMusic.mp3" loop:YES];
[soundEngine playEffect:@"sound1.mp3"];
view raw gistfile1.m hosted with ❤ by GitHub
Setting other properties is also easy:
[soundEngine setBackgroundMusicVolume:0.4];
[soundEngine playEffect:@"sound1.mp3" pitch:1 pan:0 gain:0.4];
[loopingSound setMute:YES];
view raw gistfile1.txt hosted with ❤ by GitHub
Playing around with looping sounds:
[loopingSound play];
[loopingSound pause];
[loopingSound rewind];
[loopingSound stop];
view raw gistfile1.m hosted with ❤ by GitHub
// Never forget to release the looping sound in the dealloc method
[loopingSound release];
view raw gistfile2.txt hosted with ❤ by GitHub

No hay comentarios:

Publicar un comentario