• 高级声音功能
    • 配置
    • 预加载
    • 音量控制

    高级声音功能

    配置

    移动设备上的游戏会遇到一些特殊的情景,比如游戏应用被切换至后台又切换回前台,正在玩游戏的时候电话来了,电话打完继续玩游戏,这些你在进行声音控制的时候都得考虑。

    幸运的是,游戏引擎在设计的时候已经考虑到这些情景了,注意在 AppDelegate.cpp 中,有这样几个方法:

    C++

    1. // This function will be called when the app is inactive. When comes a phone call,
    2. // it's be invoked too
    3. void AppDelegate::applicationDidEnterBackground() {
    4. Director::getInstance()->stopAnimation();
    5. // if you use SimpleAudioEngine, it must be pause
    6. // SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
    7. }
    8. // this function will be called when the app is active again
    9. void AppDelegate::applicationWillEnterForeground() {
    10. Director::getInstance()->startAnimation();
    11. // if you use SimpleAudioEngine, it must resume here
    12. // SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
    13. }

    看到了那些被注释的行吗?如果你有使用 SimpleAudioEngine 在游戏中播放声音,记得取消这些注释。当这些被注释的代码生效,你的游戏就能应对刚才提到的场景。

    预加载

    加载音乐和音效通常是个耗时间的过程,为了防止由加载产生的延时导致实际播放与游戏播放不协调的现象,在播放音乐和音效前,可以预加载音乐文件。

    C++

    1. #include "SimpleAudioEngine.h"
    2. using namespace CocosDenshion;
    3. auto audio = SimpleAudioEngine::getInstance();
    4. // pre-loading background music and effects. You could pre-load
    5. // effects, perhaps on app startup so they are already loaded
    6. // when you want to use them.
    7. audio->preloadBackgroundMusic("myMusic1.mp3");
    8. audio->preloadBackgroundMusic("myMusic2.mp3");
    9. audio->preloadEffect("myEffect1.mp3");
    10. audio->preloadEffect("myEffect2.mp3");
    11. // unload a sound from cache. If you are finished with a sound and
    12. // you wont use it anymore in your game. unload it to free up
    13. // resources.
    14. audio->unloadEffect("myEffect1.mp3");

    音量控制

    可以像下面这样,通过代码控制音乐和音效的音量:

    C++

    1. #include "SimpleAudioEngine.h"
    2. using namespace CocosDenshion;
    3. auto audio = SimpleAudioEngine::getInstance();
    4. // setting the volume specifying value as a float
    5. audio->setEffectsVolume(5.0f);

    原文: http://docs.cocos.com/cocos2d-x/manual/zh/audio/advanced.html