0
\$\begingroup\$

I'm trying to play sounds and music with cocos2d. When I run on iPhone and .caf files the audio is perfect, but on Android it is not playing the background music and is only playing 2 sounds of 10 files. I don't know what I'm doing wrong.

#include <SimpleAudioEngine.h>
bool HelloWorld::init()
{
  const char *sound;

#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
  sound = "Fun.caf";
#else
 sound = "Fun.wav";
#endif

  auto audio = CocosDenshion::SimpleAudioEngine::getInstance();

  audio->preloadBackgroundMusic(sound);

  audio->playBackgroundMusic(sound, true);

  audio->setBackgroundMusicVolume(1.0f);
}

void HelloWorld::playSound()
{
  const char *effect;

   #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
  effect = "Bomb.caf";
#else
  effect = "Bomb.wav";
#endif

    audio->preloadEffect(effect);
    audio->playEffect(effect);    
}
\$\endgroup\$
1
\$\begingroup\$

Isn't auto audio = CocosDenshion::SimpleAudioEngine::getInstance(); local and accessible to your init function, how are you reaccessing it in your playSound() function?

Also, why are you preloading the audio every time you play it? You should only preload once (such as when the application is first launched)

It would potentially be better to create a 'helper' singleton class (such as an AudioHelper) which when initialized preloads all sound effects based on the current platform, and then with another function to play a sound effect (where you can pass in the required sound file).

So, instead of calling

CocosDenshion::SimpleAudioEngine::getInstance() ...

You could use your helper class instead, calling

AudioHelper::sharedAudioHelper()->playAudio("Bomb");

... which will then add on the file extension based on the current platform and then access SimpleAudioEngine to play the effect. Then you'll have audio handling logic accessible throughout your project, and can then customise it to fit whatever your requirements are.

\$\endgroup\$
  • \$\begingroup\$ Yeah... suggesting to use singleton is.. dangerous. \$\endgroup\$ – Alexandre Vaillancourt Feb 2 '17 at 11:00
  • \$\begingroup\$ If you have any alternatives please do suggest them so I can alter my answer! I moved over from iOS where I had previously used singletons, and my implementation doesn't have any issues. Again, if you have any safer idea, please do tell! :) \$\endgroup\$ – Ryan Bourne Feb 2 '17 at 11:04
  • \$\begingroup\$ I'm not saying it's not going to work, it's just because there is a flamestorm about the usage of singleton. An alternative would be to create a single instance of the 'helper' object, and pass it as a parameter to whoever needs it. \$\endgroup\$ – Alexandre Vaillancourt Feb 2 '17 at 11:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.