Cocos2D-X笔记(4)播放音乐/音效

时间:2020-12-18 23:29:51

首先,把背景音乐文件bg_music.wav 和 音效文件attack.wav复制到Resources目录下,

之后在GameScene.cpp里包含SimpleaudioEngine.h中,给2个音乐文件起别名。


#include "SimpleAudioEngine.h"         
#define MUSIC_FILE "bg_music.mid"
#define EFFECT_FILE "attack.wav"


然后在init()里添加背景音乐


//预加载CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadBackgroundMusic(MUSIC_FILE);CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadEffect(EFFECT_FILE );         //设置音量CocosDenshion::SimpleAudioEngine::sharedEngine()->setEffectsVolume(0.5);CocosDenshion::SimpleAudioEngine::sharedEngine()->setBackgroundMusicVolume(0.5);         //循环播放背景音乐,CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic(MUSIC_FILE,true);


在ccTouchEnded事件中写入以下代码播放音效:


//播放音效CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(EFFECT_FILE);