|Articles & Tutorials|
|Cocos2D 1.0 - Basic audio|
|Monday, 28 May 2012 18:57|
Audio in Cocos2D is implemented through a third-party library, CocosDenshion.
There are different ways to use CocosDenshion, depending on how much features you need for your project. For basic audio features we'll use the SimpleAudioEngine.
Since CocosDenshion is a separate library, you need to import the related header file wherever you need to use it:
Similar to CCDirector, SimpleAudioEngine is a singleton class. You retrieve the shared engine instance in a similar way:
To play a background music, use playBackgroundMusic:
By default, it will play in loop. If you want it to play just once, you can specify it:
Instead, to stop it use stopBackgroundMusic:
To check if a background music is currently playing:
You can also pause it:
And then resume it:
Finally, if you need to rewind it you can use rewindBackgroundMusic:
Playing sound effects is quite similar to music.
You can play a sound effect in this way:
Or you can also specify pitch, panning and gain:
Just note that playEffect returns an ID. If you later want to stop a sound effect that's still playing, you need to pass the related sound ID:
You can change both music and audio effects volume. Their range is from 0.0f to 1.0f.
For the music volume, set backgroundMusicVolume:
While for the audio effects: