Reputation: 6976
I'm using cocos denshion for the music in my game.
I'm currently playing background music with the code:
[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"backSong.mp3"];
However, when the game ends, I need the background music to fade out gradually. How can I fade out the background music, is there a way to do this? Thanks in advance!
Additionally, is ObjectAL any better than CocosDenshion? If so, what are the differences/advantages?
Upvotes: 2
Views: 2484
Reputation: 147
Try this:
float currentVolume = [SimpleAudioEngine sharedEngine].backgroundMusicVolume;
id fadeOut = [CCActionTween actionWithDuration:1 key:@"backgroundMusicVolume" from:currentVolume to:0.0f];
[[[CCDirector sharedDirector] actionManager] addAction:fadeOut target:[SimpleAudioEngine sharedEngine] paused:NO];
Hope that helps!
Upvotes: 9
Reputation: 9089
The only way i found of doing that is to schedule a method for execution and change the volume setting accordingly, kind of as follows:
-(void) fadeOutBackgroundMusic{
if (!currentBackgroundMusic_) {
CCLOG(@"GESoundServicesProviderImpl<fadeOutBackgroundMusic> : No background music at this time, ignoring.");
return;
}
fadeOutActionTickerCount_=0;
[self schedule:@selector(tickMusicFadeOut:)];
}
-(BOOL) isPlayingBackgroundMusic{
return isPlayingBackgroundMusic_;
}
#pragma mark sequencing stuff
-(void) tickMusicFadeOut:(ccTime) dt{
static float fadeTime;
static float volume;
static float maxVolume;
fadeOutActionTickerCount_++;
if (1==fadeOutActionTickerCount_) {
isPerformingFadeOutAction_ =YES;
fadeTime=0.0f;
volume=0.0f;
maxVolume=audioSettings_.masterVolumeGain*audioSettings_.musicCeilingGain;
} else {
fadeTime+=dt;
volume=MAX(0.0f, maxVolume*(1.0 - fadeTime/K_MUSIC_FADE_TIME));
[self setMusicVolume:volume];
if (fadeTime>K_MUSIC_FADE_TIME) {
volume=0.0f; // in case we have a .000000231 type seting at that moment.
}
if (volume==0.0f) {
CCLOG(@"GESoundServicesProviderImpl<tickMusicFadeOut> : background music faded out in %f seconds.",fadeTime);
[self setMusicVolume:0.0f];
[sharedAudioEngine_ stopBackgroundMusic];
self.currentBackgroundMusic=nil;
isPlayingBackgroundMusic_=NO;
isPerformingFadeOutAction_=NO;
[self unschedule:@selector(tickMusicFadeOut:)];
}
}
}
this is a simplified (edited) sample from my sound services provider implementation class (not tested as shown here). The general idea is to schedule yourself a method that will gradually fade out the music over a period of time (here an app-wide constant, K_MUSIC_FADE_TIME).
Upvotes: 2