Cocos2d play 2 different background music files or loop playEffect
I need to have to have a backgr开发者_如何学编程ound 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:
- Play 2 background music files in the same time, and stop the one related to the Character
- Loop a sound effect.
Which one of this is 2 possible & recommended?
Regards!
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 toOpenAL
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];
@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.
精彩评论