Sound Effects for Cocos2d-x Game Development

Source: Internet
Author: User

In our game development, apart from the UI being the top priority, music is also an indispensable part.

Because people have two eyes and ears.

Now let's take a look at the introduced library files, which is relatively simple in general.


First introduce the library file and use the namespace:

#include "SimpleAudioEngine.h"using namespace CocosDenshion;

The following code is used:

// Play the background music. Put the relative path in the resource string music = "Audio/bgaudioaudio"; SimpleAudioEngine: sharedEngine ()-> playBackgroundMusic (music. c_str (), true );



/****************************************************************************Copyright (c) 2010-2012 cocos2d-x.orgCopyright (c) 2010      Steve Oldmeadowhttp://www.cocos2d-x.orgPermission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included inall copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.****************************************************************************/#ifndef _SIMPLE_AUDIO_ENGINE_H_#define _SIMPLE_AUDIO_ENGINE_H_#include 
 
  #include "Export.h"#include 
  
   #include 
   
    #include 
    
     namespace CocosDenshion {class TypeInfo{public:    virtual long getClassTypeInfo() = 0;};static inline unsigned int getHashCodeByString(const char *key){unsigned int len = strlen(key);const char *end=key+len;unsigned int hash;for (hash = 0; key < end; key++){hash *= 16777619;hash ^= (unsigned int) (unsigned char) toupper(*key);}return (hash);}/**@class          SimpleAudioEngine@brief          offer a VERY simple interface to play background music & sound effect*/class EXPORT_DLL SimpleAudioEngine : public TypeInfo{public:    SimpleAudioEngine();    /**     *  @js NA     *  @lua NA     */    ~SimpleAudioEngine();    /**     *  @js NA     *  @lua NA     */    virtual long getClassTypeInfo() {        return getHashCodeByString(typeid(CocosDenshion::SimpleAudioEngine).name());    }    /**    @brief Get the shared Engine object,it will new one when first time be called    @js getInstance    */    static SimpleAudioEngine* sharedEngine();    /**    @brief Release the shared Engine object    @warning It must be called before the application exit, or a memroy leak will be casued.    @lua NA    */    static void end();    /**     @brief Preload background music     @param pszFilePath The path of the background music file,or the FileName of T_SoundResInfo     @js preloadMusic     */    void preloadBackgroundMusic(const char* pszFilePath);        /**    @brief Play background music    @param pszFilePath The path of the background music file,or the FileName of T_SoundResInfo    @param bLoop Whether the background music loop or not    @js playMusic    */    void playBackgroundMusic(const char* pszFilePath, bool bLoop);    /**     @js playMusic     */    void playBackgroundMusic(const char* pszFilePath) {    this->playBackgroundMusic(pszFilePath, false);    }    /**    @brief Stop playing background music    @param bReleaseData If release the background music data or not.As default value is false    @js stopMusic    */    void stopBackgroundMusic(bool bReleaseData);    /**     @js stopMusic     */    void stopBackgroundMusic() {    this->stopBackgroundMusic(false);    }    /**    @brief Pause playing background music    @js pauseMusic    */    void pauseBackgroundMusic();    /**    @brief Resume playing background music    @js resumeMusic    */    void resumeBackgroundMusic();    /**    @brief Rewind playing background music    @js rewindMusic    */    void rewindBackgroundMusic();    /**     *  @js willPlayMusic     */    bool willPlayBackgroundMusic();    /**    @brief Whether the background music is playing    @return If is playing return true,or return false    @js isMusicPlaying    */    bool isBackgroundMusicPlaying();    // properties    /**    @brief The volume of the background music max value is 1.0,the min value is 0.0    @js getMusicVolume    */    float getBackgroundMusicVolume();    /**    @brief set the volume of background music    @param volume must be in 0.0~1.0    @js setMusicVolume    */    void setBackgroundMusicVolume(float volume);    /**    @brief The volume of the effects max value is 1.0,the min value is 0.0    */    float getEffectsVolume();    /**    @brief set the volume of sound effecs    @param volume must be in 0.0~1.0    */    void setEffectsVolume(float volume);    // for sound effects    /**    @brief Play sound effect    @param pszFilePath The path of the effect file,or the FileName of T_SoundResInfo    @bLoop Whether to loop the effect playing, default value is false    */    unsigned int playEffect(const char* pszFilePath, bool bLoop);    unsigned int playEffect(const char* pszFilePath) {    return this->playEffect(pszFilePath, false);    }    /**    @brief Pause playing sound effect    @param nSoundId The return value of function playEffect    */    void pauseEffect(unsigned int nSoundId);    /**    @brief Pause all playing sound effect    @param nSoundId The return value of function playEffect    */    void pauseAllEffects();    /**    @brief Resume playing sound effect    @param nSoundId The return value of function playEffect    */    void resumeEffect(unsigned int nSoundId);    /**    @brief Resume all playing sound effect    @param nSoundId The return value of function playEffect    */    void resumeAllEffects();    /**    @brief Stop playing sound effect    @param nSoundId The return value of function playEffect    */    void stopEffect(unsigned int nSoundId);    /**    @brief Stop all playing sound effects    */    void stopAllEffects();    /**    @brief          preload a compressed audio file    @details        the compressed audio will be decode to wave, then write into an     internal buffer in SimpleaudioEngine    */    void preloadEffect(const char* pszFilePath);    /**    @brief          unload the preloaded effect from internal buffer    @param[in]        pszFilePath        The path of the effect file,or the FileName of T_SoundResInfo    */    void unloadEffect(const char* pszFilePath);};} // end of namespace CocosDenshion#endif // _SIMPLE_AUDIO_ENGINE_H_
    
   
  
 





1. The sound of Cocos2d-x

The Cocos2d-iphone contains the CocosDenshion library, which provides three layers of interfaces from low to high: CDSoundEngine, CDAudioManager, and SimpleAudioEngine, but the entire library is fully dependent on OpenAL. Since CocosDenshiono underlying support cannot be provided on other platforms, we only use the SimpleAudioEngine class at the top to implement cross-platform sound engines, which is very easy to use.

View the SimpleAudioEngine file to know the APIs for playing background music and sound effects. (The file location is as follows :)


Note: What is the difference in CocZ? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> vczJkeNL9x + bOxLz + release + xL/CvM/C09DSu7j2uL20 + LXEwP3X06OswO/release + a1xMq508PA/release cjxwPgqjqDGjqbnY09rJ + dL0zsS8/rXE1KS809TYo6y/examples + CjxwPgo8L3A + CgoKCjxzdHJvbmc + summary "1" class = "dp-cpp">

  • // Preload background music and effect
  • SimpleAudioEngine: sharedEngine ()-> preloadBackgroundMusic (MUSIC_FILE );
  • SimpleAudioEngine: sharedEngine ()-> preloadEffect (EFFECT_FILE );
    The parameter is the name of the audio file. The two pre-loading methods show that the implementation of these methods will help us obtain the full path of the sound file.

    [Cpp]View plaincopy
    1. Void SimpleAudioEngine: preloadBackgroundMusic (const char * pszFilePath)
    2. {
    3. // Changing file path to full path
    4. Std: string fullPath = CCFileUtils: sharedFileUtils ()-> fullPathForFilename (pszFilePath );
    5. Static_preloadBackgroundMusic (fullPath. c_str ());
    6. }
    7. Void SimpleAudioEngine: playBackgroundMusic (const char * pszFilePath, bool bLoop)
    8. {
    9. // Changing file path to full path
    10. Std: string fullPath = CCFileUtils: sharedFileUtils ()-> fullPathForFilename (pszFilePath );
    11. Static_playBackgroundMusic (fullPath. c_str (), bLoop );
    12. }


      (2) end the use of SimpleAudioEngine in the onExit function.

      [Cpp]View plaincopy
      1. Void CocosDenshionTest: onExit ()
      2. {
      3. CCLayer: onExit ();
      4. SimpleAudioEngine: sharedEngine ()-> end ();
      5. }

        1. The sound of Cocos2d-x

        The Cocos2d-iphone contains the CocosDenshion library, which provides three layers of interfaces from low to high: CDSoundEngine, CDAudioManager, and SimpleAudioEngine, but the entire library is fully dependent on OpenAL. Since CocosDenshiono underlying support cannot be provided on other platforms, we only use the SimpleAudioEngine class at the top to implement cross-platform sound engines, which is very easy to use.

        View the SimpleAudioEngine file to know the APIs for playing background music and sound effects. (The file location is as follows :)


        Note: samples/Cpp/TestCpp/proj. there is an accompanying example under the ios file directory, which contains a vast majority of examples, which are very detailed. It is a good demo collection for learning Cocos2dx.


        Example of SimpleAudioEngine sound engine in Cocos2dx ---- CocosDenshionTest


        (1) sound file pre-loading can improve the execution efficiency of the program in the game, but it cannot avoid increasing the memory usage.

        [Cpp]View plaincopy
        1. // Preload background music and effect
        2. SimpleAudioEngine: sharedEngine ()-> preloadBackgroundMusic (MUSIC_FILE );
        3. SimpleAudioEngine: sharedEngine ()-> preloadEffect (EFFECT_FILE );
          The parameter is the name of the audio file. The two pre-loading methods show that the implementation of these methods will help us obtain the full path of the sound file.

          [Cpp]View plaincopy
          1. Void SimpleAudioEngine: preloadBackgroundMusic (const char * pszFilePath)
          2. {
          3. // Changing file path to full path
          4. Std: string fullPath = CCFileUtils: sharedFileUtils ()-> fullPathForFilename (pszFilePath );
          5. Static_preloadBackgroundMusic (fullPath. c_str ());
          6. }
          7. Void SimpleAudioEngine: playBackgroundMusic (const char * pszFilePath, bool bLoop)
          8. {
          9. // Changing file path to full path
          10. Std: string fullPath = CCFileUtils: sharedFileUtils ()-> fullPathForFilename (pszFilePath );
          11. Static_playBackgroundMusic (fullPath. c_str (), bLoop );
          12. }


            (2) end the use of SimpleAudioEngine in the onExit function.

            [Cpp]View plaincopy
            1. Void CocosDenshionTest: onExit ()
            2. {
            3. CCLayer: onExit ();
            4. SimpleAudioEngine: sharedEngine ()-> end ();
            5. }

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.