zoukankan      html  css  js  c++  java
  • Cocos2d-x之Sound

    |   版权声明:本文为博主原创文章,未经博主允许不得转载。

    音效简介:

    1.1 在游戏开发的过程中除了华丽的界面,生动的动画之外,适当的音效也是重要的一部分

    1.2 游戏中的声音分为两类,一类是音乐,播放时间较长,适合用作背景音乐。另一类是音效,播放时间较短,可以重复的播放,例如,子弹打出的声音,地鼠触动的声音。             
    1.3 cocos2d-x集成了CocosDenshion音效引擎,可以方便的实现游戏音效。CocosDenshion提供了多个音效API,它们分别是CDSoundEngine,CDAudioManager和SimpleAudioEngine。前两个是比较底层的可以控制多个声音的播放,在游戏开发中我们一般使用SimpleAudioEngine就足够了。

    1.4 使用SimpleAudioEngine比较的简单,只要添加头文件和命名空间就可以使用了。#include "SimpleAudioEngine.h";即可使用。

    1.5 在Cocos2d-x中不同的平台之下,所支持的音乐格式有些差异:

        Cocos2d-x在不同平台下支持的背景音乐格式:

        Android:  MP3, WAV, 3GP

        IOS: MP3, CAF

        Win32:  MID,WAV

      Cocos2d-x在不同平台下支持的音效音乐格式:

        Android:   OGG, WAV

        IOS: CAF

        Win32:  MID,WAV

     

    音乐不同平台的判别:

    音效文件

    #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
    
            #define EFFECT_FILE "effect.ogg"
    
    #elif (CC_TARGET_PLATFORM == CC_PLATFROM_MARMALADE)
    
            #define EFFECT_FILE "effect.raw"
    
    #else
    
            #define EFFECT_FILE "effect.wav"
    
    #endif // CC_PLATFORM_ANDROID

    背景音乐文件

    #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
    
            #define MUSIC_FILE "music.mid"
    
    #elif (CC_TARGET_PLATFROM == CC_PLATFORM_BLACKBERRY)
    
            #define MUSIC_FILE "music.ogg"
    
    #else
    
            #define MUSIC_FILE "music.mp3"
    
    #endif // CC_PLATFORM_WIN32

     

    音效API中的重要函数:

     1 /** Returns a shared instance of the SimpleAudioEngine.*/
     2 实例化
     3     static SimpleAudioEngine* getInstance();
     4 /** Release the shared Engine object.warning It must be called before the application exit, or it will lead to memory leaks.*/
     5     static void end();
     6 /** Preload background music.param filePath The path of the background music file.*/
     7 预处理背景音乐问ujianjiang压缩格式的文件进行解压处理,如MP3解压为WAV
     8     virtual void preloadBackgroundMusic(const char* filePath);    
     9 /** Play background music.param filePath The path of the background music file,or the FileName of T_SoundResInfo.param loop Whether the background music loop or not.*/
    10 播放背景音乐,参数bLoop控制是否循环播放,默认为false
    11    virtual void playBackgroundMusic(const char* filePath, bool loop = false);
    12 /** Stop playing background music.param releaseData If release the background music data or not.As default value is false.*/
    13 停止播放音乐
    14     virtual void stopBackgroundMusic(bool releaseData = false);
    15 /** Pause playing background music.*/
    16 暂停播放背景音乐
    17     virtual void pauseBackgroundMusic();
    18 /** Resume playing background music.*/
    19 继续播放背景音乐
    20     virtual void resumeBackgroundMusic();
    21 /** Rewind playing background music.*/
    22 倒带
    23     virtual void rewindBackgroundMusic();
    24 /** Indicates whether any background music can be played or not.return <i>true</i> if background music can be played, otherwise <i>false</i>.*/
    25     virtual bool willPlayBackgroundMusic();
    26 /** Indicates whether the background music is playing.return <i>true</i> if the background music is playing, otherwise <i>false</i>.*/
    27 判断背景音乐是否在播放
    28     virtual bool isBackgroundMusicPlaying();
    29 /** The volume of the background music within the range of 0.0 as the minimum and 1.0 as the maximum.*/
    30     virtual float getBackgroundMusicVolume();
    31 /** Set the volume of background music.param volume must be within the range of 0.0 as the minimum and 1.0 as the maximum.*/
    32 设置背景音乐的音量大小
    33     virtual void setBackgroundMusicVolume(float volume);
    34 /** The volume of the effects within the range of 0.0 as the minimum and 1.0 as the maximum.*/
    35 获得背景音乐的音量大小
    36     virtual float getEffectsVolume();
    37 /** Set the volume of sound effects.param volume must be within the range of 0.0 as the minimum and 1.0 as the maximum.*/
    38     virtual void setEffectsVolume(float volume);
    39 /** Play sound effect with a file path, pitch, pan and gain.
    40      * @param filePath The path of the effect file.
    41      * @param loop Determines whether to loop the effect playing or not. The default value is false.
    42      * @param pitch Frequency, normal value is 1.0. Will also change effect play time.
    43      * @param pan   Stereo effect, in the range of [-1..1] where -1 enables only left channel.
    44      * @param gain  Volume, in the range of [0..1]. The normal value is 1.
    45      * @return The sound id.
    46      * 
    47      * @note Full support is under development, now there are limitations:
    48      *     - no pitch effect on Samsung Galaxy S2 with OpenSL backend enabled;
    49      *     - no pitch/pan/gain on win32.
    50      */
    51 播放音频
    52     virtual unsigned int playEffect(const char* filePath, bool loop = false,float pitch = 1.0f, float pan = 0.0f, float gain = 1.0f);
    53 /** Pause playing sound effect.param soundId The return value of function playEffect.*/
    54 暂停播放所有音效,参数SoundId是playEffect函数返回ID
    55     virtual void pauseEffect(unsigned int soundId);
    56 /** Pause all playing sound effect.*/
    57 暂停播放所有音效
    58     virtual void pauseAllEffects();
    59 /** Resume playing sound effect.param soundId The return value of function playEffect.*/
    60 继续播放音效,参数SoundId是playEffect函数返回ID
    61     virtual void resumeEffect(unsigned int soundId);
    62 /** Resume all playing sound effect.*/
    63 继续播放所有音效
    64     virtual void resumeAllEffects();
    65 /** Stop playing sound effect.param soundId The return value of function playEffect.*/
    66 停止播放所有音效,参数soundId是playEffect函数返回ID
    67     virtual void stopEffect(unsigned int soundId);
    68 /** Stop all playing sound effects.*/
    69 停止播放所有音效
    70     virtual void stopAllEffects();
    71 /** Preload a compressed audio file.The compressed audio will be decoded to wave, then written into an internal buffer in SimpleAudioEngine.param filePath The path of the effect file.*/
    72 预处理音频文件,将压缩格式的文件进行解压处理,如MP3解压为WAV
    73     virtual void preloadEffect(const char* filePath);
    74 /** Unload the preloaded effect from internal buffer.param filePath The path of the effect file.*/
    75     virtual void unloadEffect(const char* filePath);
    View Code

     

    实例:

    .h files
    
    #ifndef _SOUNDTEST_SCENE_H_
    #define _SOUNDTEST_SCENE_H_
    //使用音效比较的简单我们只要包含托文件SimpleAudioEngine.h和命名空间CocosDenshion
    #include "cocos2d.h"
    #include "uiCocosGUI.h"
    #include "editor-support/cocostudio/CCSGUIReader.h"
    #include "SimpleAudioEngine.h"
    
    //设置音乐格式的宏
    #define BG_FILES "MainMenuMusic1.wav"
    #define EFFECT_FILES "mole.wav"
    USING_NS_CC;
    using namespace cocos2d::ui;
    using namespace CocosDenshion;
    class soundTest : public cocos2d::Layer
    {
    private:
    public:
            static cocos2d::Scene* createScene();
            virtual bool init();
            //Player music
            void testPlayBGMusic(Ref* snedef);
            void testPlayEffMusic(Ref* snedef);
            //Pause music
            void testPauseBGMusic(Ref* snedef);
            void testPauseEffMusic(Ref* snedef);
            //Resume music
            void testResumeBGMusic(Ref* snedef);
            void testResumeEffMusic(Ref* snedef);
            //Stop music
            void testStopBGMusic(Ref* snedef);
            void testStopEffMusic(Ref* snedef);
            //CallBack function
            void sliderEvent1(Ref* sendef, SliderEventType type);
            void sliderEvent2(Ref* sendef, SliderEventType type);
            CREATE_FUNC(soundTest);
    };
    #endif // _SOUNDTEST_SCENE_H_
    
    
    
    .cpp files
    
    #include "SoundTest.h"
    
    Scene* soundTest::createScene()
    {
            auto scene = Scene::create();
            auto layer = soundTest::create();
            scene->addChild(layer);
            return scene;
    }
    bool soundTest::init()
    {
            if (!Layer::init())
            {
                   return false;
            }
    
            Size size = Director::getInstance()->getWinSize();
            Vec2 origin = Director::getInstance()->getVisibleOrigin();
    
            SimpleAudioEngine::getInstance()->preloadBackgroundMusic(BG_FILES);
            SimpleAudioEngine::getInstance()->preloadEffect(EFFECT_FILES);
    
            SimpleAudioEngine::getInstance()->setBackgroundMusicVolume(0.2);
            SimpleAudioEngine::getInstance()->setEffectsVolume(0.2);
    
            auto item1 = MenuItemFont::create("Play bg", CC_CALLBACK_1(soundTest::testPlayBGMusic, this));
            auto item2 = MenuItemFont::create("Play eff", CC_CALLBACK_1(soundTest::testPlayEffMusic, this));
    
            auto item3 = MenuItemFont::create("Pause bg", CC_CALLBACK_1(soundTest::testPauseBGMusic, this));
            auto item4 = MenuItemFont::create("Pause ef", CC_CALLBACK_1(soundTest::testPauseEffMusic, this));
    
            auto item5 = MenuItemFont::create("Resume bg", CC_CALLBACK_1(soundTest::testResumeBGMusic, this));
            auto item6 = MenuItemFont::create("Resume eff", CC_CALLBACK_1(soundTest::testResumeEffMusic, this));
    
            auto item7 = MenuItemFont::create("Stop bg", CC_CALLBACK_1(soundTest::testStopBGMusic, this));
            auto item8 = MenuItemFont::create("Stop eff", CC_CALLBACK_1(soundTest::testStopEffMusic, this));
    
            auto menu1 = Menu::create(item1, item3, item5, item7, NULL);
            menu1->setPosition(Vec2(100, size.height - 100));
            menu1->alignItemsVertically();
            this->addChild(menu1);
    
            auto menu2 = Menu::create(item2, item4, item6, item8, NULL);
            menu2->setPosition(Vec2(300, size.height - 100));
            menu2->alignItemsVertically();
            this->addChild(menu2);
    
            Slider* slider1 = Slider::create();
    
            slider1->loadBarTexture("sliderTrack.png");
            slider1->loadSlidBallTextures("sliderThumb.png", "sliderThumb.png", "");
            slider1->loadProgressBarTexture("sliderProgress.png");
            slider1->setPosition(Vec2(200, 300));
            slider1->addEventListenerSlider(this, sliderpercentchangedselector(soundTest::sliderEvent1));
            this->addChild(slider1);
    
            Slider* slider2 = Slider::create();
    
            slider2->loadBarTexture("sliderTrack.png");
            slider2->loadSlidBallTextures("sliderThumb.png", "sliderThumb.png", "");
            slider2->loadProgressBarTexture("sliderProgress.png");
            slider2->setPosition(Vec2(size.width - 200, 10));
            slider2->addEventListenerSlider(this, sliderpercentchangedselector(soundTest::sliderEvent1));
            this->addChild(slider2);
    
            return true;
    }
    //设置调节音量大小条的回调函数
    void soundTest::sliderEvent1(Ref* sendef, SliderEventType type)
    {
            if (type == SLIDER_PERCENTCHANGED)
            {
                   Slider* slider = dynamic_cast<Slider*>(sendef);
                   int percent = slider->getPercent();
                   SimpleAudioEngine::getInstance()->setBackgroundMusicVolume(percent*0.1);
            }
    }
    void soundTest::sliderEvent2(Ref* sendef, SliderEventType type)
    {
            if (type == SLIDER_PERCENTCHANGED)
            {
                   Slider* slider = dynamic_cast<Slider*>(sendef);
                   int percent = slider->getPercent();
                   SimpleAudioEngine::getInstance()->setBackgroundMusicVolume(percent*0.1);
            }
    }
    //开始播放音乐
    void soundTest::testPlayBGMusic(Ref* sendef)
    {
            SimpleAudioEngine::getInstance()->playBackgroundMusic(BG_FILES, true);
    }
    //开始播放音效
    void soundTest::testPlayEffMusic(Ref* sendef)
    {
            SimpleAudioEngine::getInstance()->playEffect(EFFECT_FILES);
    }
    //暂停播放的音乐
    void soundTest::testPauseBGMusic(Ref* sendef)
    {
            SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
    }
    //暂停播放所有的音效
    void soundTest::testPauseEffMusic(Ref* sendef)
    {
            SimpleAudioEngine::getInstance()->pauseAllEffects();
    }
    //恢复播放的音乐
    void soundTest::testResumeBGMusic(Ref* sendef)
    {
            SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
    }
    //恢复播放所有的音效
    void soundTest::testResumeEffMusic(Ref* sendef)
    {
            SimpleAudioEngine::getInstance()->resumeAllEffects();
    }
    //停止播放的音乐
    void soundTest::testStopBGMusic(Ref* sendef)
    {
            SimpleAudioEngine::getInstance()->stopBackgroundMusic();
    }
    //停止播放所有的音效
    void soundTest::testStopEffMusic(Ref* sendef)
    {
            SimpleAudioEngine::getInstance()->stopAllEffects();
    }
    

  • 相关阅读:
    最简单的图片轮播
    首页图片轮播效果
    windows简单杀死进程的批处理程序
    js实现无限级树形导航列表
    漂亮竖向菜单 有缓存 javascript
    竖向折叠二级导航JS代码(可防刷新ul/li结构)
    bzoj 1060: [ZJOI2007]时态同步【树形dp】
    bzoj 2733: [HNOI2012]永无乡【并查集+权值线段树】
    洛谷 P3952 时间复杂度【模拟】
    bzoj 2208: [Jsoi2010]连通数【tarjan+拓扑+dp】
  • 原文地址:https://www.cnblogs.com/geore/p/5799485.html
Copyright © 2011-2022 走看看