As few code needs to be added here, let's talk more about sound engine here. The Cocos2d-x has encapsulated SimpleAudioEngine for cross-platform use. In our game, I can play background music and sound effects with only one line of code. This is very convenient. Of course, the supported audio formats vary by platform. For more information, see
Http://www.cocos2d-x.org/projects/cocos2d-x/wiki/Audio_formats_supported_by_CocosDenshion_on_different_platforms
In fact, the cocos2d-iphone contains the cocosDenshion library, which provides a layer-3 interface from bottom to high: CDSoundEngine-> CDAudioManager-> SimpleAudioEngine, but the entire library relies entirely on OpenAL. OpenAL is not the standard of Khronos Group, but an open-source library of Creative, which can be implemented by software or hardware. Currently, the hardware implements OpenAL as if only Apple products are available. Therefore, we cannot provide the underlying support for cocosDenshion on other platforms, but we support the top-level support, it is the most common Layer for developers.
Now let's go back to the topic
First, copy the audio file background-music-aac.wav and pew-pew-lei.wav to the Resource Directory. We use the wav format because it supports all platforms and these two files are included in the Cocos2dSimpleGame project. You can also download them at the bottom of this page.
And then include SimpleaudioEngine. h In HelloWorldScene. cpp.
1 // cpp with cocos2d-x
2 # include "SimpleAudioEngine. h"
1 // objcwith cocos2d-iphone
2 # import "SimpleAudioEngine. h"
Add background music in init ()
1 // cpp with cocos2d-x
2 CocosDenshion: SimpleAudioEngine: sharedEngine ()-> playBackgroundMusic (
3 "background-music-aac.wav", true );
1 // objcwith cocos2d-iphone
2 [[SimpleAudioEngine sharedEngine] playBackgroundMusic:
3 @ background-music-aac.caf];
Then play the bullet-fired sound effect in the ccTouchesEnded () method.
1 // cpp with cocos2d-x
2 CocosDenshion: SimpleAudioEngine: sharedEngine ()-> playEffect (
3 "pew-pew-lei.wav ");
1 // objcwith cocos2d-iphone
2 [[SimpleAudioEngine sharedEngine] playEffect: @ "pew-pew-lei.caf"];
Well, the sound effects and background music are done in this way.