Cocos2d-x Sound

Sound

There are 2 types of sound.

  • sound effect
  • background music

cocos2d-x prepares APIs both types for each.

Support files

  • Android OGG, MP3, WAV
  • Others MP3, WAV

Sound Effect

Sound Effect is short term sound. 1,2 crash sound or something.
Steps

  1. Add Header
  2. Add prepare in init()
  3. Play sound

Add Header

#include <audio/include/SimpleAudioEngine.h>

Add prepare in init()

CocosDenshion::SimpleAudioEngine::getInstance()->preloadEffect("filename");

Play sound

CocosDenshion::SimpleAudioEngine::getInstance()->playEffect("filename");

Pause, Resume

unsigned int id;
id = CocosDenshion::SimpleAudioEngine::getInstance()->playEffect("filename");
CocosDenshion::SimpleAudioEngine::getInstance()->pauseEffect(id);
CocosDenshion::SimpleAudioEngine::getInstance()->resumeEffect(id);

Background Music

Steps

  1. Add Header
  2. Check playing or not init() and play

Add Header

#include <audio/include/SimpleAudioEngine.h>

Check playing or not init() and play

if (!CocosDenshion::SimpleAudioEngine::getInstance()->isBackgroundMusicPlaying()) {
    	CocosDenshion::SimpleAudioEngine::getInstance()->preloadBackgroundMusic("filename.mp3");
    	CocosDenshion::SimpleAudioEngine::getInstance()->playBackgroundMusic("filename.mp3", true);  // loop: true
}

Volume

CocosDenshion::SimpleAudioEngine::getInstance()->setBackgroundVolume(0.5);

Pause, Resume

– applicationDidEnterBackground
Stop sound when the software go background

CocosDenshion::SimpleAudioEngine::getInstance()->pauseBackgroundMusic();

– applicationWillEnterForeground
when coming back, restart music

CocosDenshion::SimpleAudioEngine::getInstance()->resumeBackgroundMusic();

Stop

If change file, we need to stop and release file

CocosDenshion::SimpleAudioEngine::getInstance()->stopBackgroundMusic(true); // release data: true