打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Chapter 6 - How to Play Music and Sound Effect

Chapter 6 - How to Play Music and Sound Effect

In this chapter, we would add background music to the game and play sound effect when the hero fires bullets.

Because there’s so few codes to add that we could say a little more about audio engine here. Cocos2d-x has wrapped SimpleAudioEngine to cross platforms. In our game, we are able to play music and sound effect using only one line of codes. It is so convenient. Of course, audio formats supported in different platform are different, about this issue, you could refer to http://www.cocos2d-x.org/projects/cocos2d-x/wiki/Audio_formats_supported_by_CocosDenshion_on_different_platforms.

In fact, cocos2d-iphone includes the cocosDenshion library, and the library offers three layers of interfaces: CDSoundEngine->CDAudioManager->SimpleAudioEngine, but its realization totally relies on OpenAL. About OpenAL, it is not a standard of Khronos Group, it is an open source of Creative, which could be realize by software and hardware. So far, OpenAL is hardware realized only by Apple’s products, so in other platforms, we couldn’t provide supports for the lower layers of cocosDenshion, but we support the top layer which is used most commonly by the developers.

Now let’s get right to the issues.
First, copy the sound files background-music-aac.wav and pew-pew-lei.wav to the Resource directory. We use wav here because wav is supported in all platforms and these two files have been included in the Cocos2dSimpleGame project, you could download them from the bottom of this page.
Then include SimpleaudioEngine.h in HelloWorldScene.cpp.

1// cpp with cocos2d-x2#include "SimpleAudioEngine.h"    
1// objc with cocos2d-iphone2#import "SimpleAudioEngine.h" 

Add the background music in init().

1// cpp with cocos2d-x2CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic(3"background-music-aac.wav", true);    
1// objc with cocos2d-iphone2[[SimpleAudioEngine sharedEngine] playBackgroundMusic:3@"background-music-aac.caf"];

And play the sound effect in ccTouchesEnded() when the bullet is fired.

1// cpp with cocos2d-x2CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(3"pew-pew-lei.wav");    
1// objc with cocos2d-iphone2[[SimpleAudioEngine sharedEngine] playEffect:@"pew-pew-lei.caf"]; 

Ok, the audio addition is completed now.

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
cocos2d
cocos2dx 音乐音效
sound effect
【cocos2d-x入门实战】微信飞机大战之十四:背景音乐和音效
让电脑每次的开机音乐都不一样
How To Make a Tile-Based Game with Cocos2D 2.X Part 2
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服