简介
Cocos2d-x 提供了一个 SimpleAudioEngine 类支持游戏内的音乐和音效。它可以被用来增加背景音乐,控制游戏音效。
SimpleAudioEngine 是一个共享的单例对象,你可以在代码中的任何地方通过很简单的方式获取到。以下,我们会尽可能的为你展示它的各种使用方法。先来了解一下支持的文件格式。
支持的音乐格式:
支持的音效格式:
播放背景音乐
通过下面的方式,播放一个音频文件作为背景音乐,可以控制背景音乐是否循环播放:
#include "SimpleAudioEngine.h"
using namespace CocosDenshion;
auto audio = SimpleAudioEngine::getInstance();
// set the background music and continuously play it.
audio->playBackgroundMusic("mymusic.mp3", true);
// set the background music and play it just once.
audio->playBackgroundMusic("mymusic.mp3", false);
播放音效
通过下面的方式,将一个音频文件作为音效:
#include "SimpleAudioEngine.h"
using namespace CocosDenshion;
auto audio = SimpleAudioEngine::getInstance();
// play a sound effect, just once.
audio->playEffect("myEffect.mp3", false, 1.0f, 1.0f, 1.0f);
声音控制
开始播放音乐和音效后,你可能需要对它们进行一些控制,比如暂停、停止、恢复。这很容易完成,下面介绍:
1.暂停声音:
#include "SimpleAudioEngine.h"
using namespace CocosDenshion;
auto audio = SimpleAudioEngine::getInstance();
// pause background music.
audio->pauseBackgroundMusic();
// pause a sound effect.
audio->pauseEffect();
// pause all sound effects.
audio->pauseAllEffects();
2.停止声音:
#include "SimpleAudioEngine.h"
using namespace CocosDenshion;
auto audio = SimpleAudioEngine::getInstance();
// stop background music.
audio->stopBackgroundMusic();
// stop a sound effect.
audio->stopEffect();
// stops all running sound effects.
audio->stopAllEffects();
3.恢复声音:
#include "SimpleAudioEngine.h"
using namespace CocosDenshion;
auto audio = SimpleAudioEngine::getInstance();
// resume background music.
audio->resumeBackgroundMusic();
// resume a sound effect.
audio->resumeEffect();
// resume all sound effects.
audio->resumeAllEffects();
预加载
加载音乐和音效通常是个耗时间的过程,为了防止由加载产生的延时导致实际播放与游戏播放不协调的现象,在播放音乐和音效前,可以预加载音乐文件:
#include "SimpleAudioEngine.h"
using namespace CocosDenshion;
auto audio = SimpleAudioEngine::getInstance();
// pre-loading background music and effects. You could pre-load// effects, perhaps on app startup so they are already loaded// when you want to use them.
audio->preloadBackgroundMusic("myMusic1.mp3");
audio->preloadBackgroundMusic("myMusic2.mp3");
audio->preloadEffect("myEffect1.mp3");
audio->preloadEffect("myEffect2.mp3");
// unload a sound from cache. If you are finished with a sound and// you wont use it anymore in your game. unload it to free up// resources.
audio->unloadEffect("myEffect1.mp3");