4

I need to have to have a background music for the Scene and a background music for an Character,but I have to stop it when the character makes some actions.

For this problem I have to options:

  1. Play 2 background music files in the same time, and stop the one related to the Character
  2. Loop a sound effect.

Which one of this is 2 possible & recommended?

Regards!

James Webster
  • 31,873
  • 11
  • 70
  • 114
mxg
  • 20,946
  • 12
  • 59
  • 80

2 Answers2

16

You say you're using cocos2d so I've made the assumption that you're also using the SimpleAudioEngine provided with cocos2d.

With SimpleAudioEngine, it's not possible to play 2 background tracks. It is possible to loop effects with some small modifications:

  • Provide a -(int) playEffect:(NSString*) file loop:(BOOL) loop message;
  • In this method, you'll need to find out what play effect normally does. The thing you're looking out for is the ALUInt that is used as the handle for the sound. Keep a reference to this. You'll need it to stop the loop.
  • Provide a -(void) stopEffectWithHandle:(int) handle that takes that in and passes it back to OpenAL to stop the effect.

-EDIT-

Here's some code for looping an effect:

int handle = [[SimpleAudioEngine sharedEngine] playEffect:name];
if (loop) {
    alSourcei(handle, AL_LOOPING, 1);
}
return handle;

And some for stopping effects:

[[SimpleAudioEngine sharedEngine] stopEffect:handle];
James Webster
  • 31,873
  • 11
  • 70
  • 114
  • I found what effect is stoped on loop when you play a lot of another effects simultaneously. – Sound Blaster Aug 29 '12 at 10:50
  • I think this is because there is a limit in CocosDension of how many sounds can be simultaneously loaded. – James Webster Aug 29 '12 at 10:56
  • 1
    After playing and stopping the sound nearly 32 times, it stops working. After some googling I found the memory pool is filled. I need to somehow release the sound object. How to do that? – Naveed Abbas Nov 26 '12 at 08:46
0

@ToughGuy comment on @JamesWebster answer is right, I ran into the same problem with that solution.

I solved this problem using this approach from this forum post.

Play effect with:

CDSoundSource *loopSound = [[SimpleAudioEngine sharedEngine] soundSourceForFile:LOOPING_SOUND_FILENAME];
loopSound.looping = YES;
[loopSound play];

And stop it with:

[loopSound stop];

Hope this helps.

Firula
  • 1,251
  • 10
  • 29