Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Crossfade music in cocos2d?

Simple enough... I have a background song playing on my game, and I would like to crossfade a track, instead of a hard stop.

//Prep Background Music
        if (![[SimpleAudioEngine sharedEngine]isBackgroundMusicPlaying]) {
             [[SimpleAudioEngine sharedEngine] preloadBackgroundMusic:@"song.mp3"];
        }
        [[SimpleAudioEngine sharedEngine] setBackgroundMusicVolume:1.0]; 

        //Play Background Music
         if (![[SimpleAudioEngine sharedEngine]isBackgroundMusicPlaying]) {
             [[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"song.mp3" loop:YES];
         }
like image 496
PRNDL Development Studios Avatar asked Mar 14 '12 22:03

PRNDL Development Studios


1 Answers

I use this simple method to replace current background music:

-(void)replaceBackgroundMusic:(NSString *)filePath volume:(float)volume
{
    // no music's playing right now
    if (![[SimpleAudioEngine sharedEngine] isBackgroundMusicPlaying])
        return [self playBackgroundMusic:filePath volume:volume];

    // already playing requested track
    if ([filePath isEqualToString:[[[CDAudioManager sharedManager] backgroundMusic] audioSourceFilePath]])
        return;

    // replace current track with fade out effect
    float currentVolume = [SimpleAudioEngine sharedEngine].backgroundMusicVolume;
    id fadeOut = [CCActionTween actionWithDuration:1 key:@"backgroundMusicVolume" from:currentVolume to:0.0f];
    id playNew =
    [CCCallBlock actionWithBlock:^
     {
         [[SimpleAudioEngine sharedEngine] setBackgroundMusicVolume:volume];
         [[SimpleAudioEngine sharedEngine] playBackgroundMusic:filePath];
     }];

    [[[CCDirector sharedDirector] actionManager] addAction:[CCSequence actions:fadeOut, playNew, nil] target:[SimpleAudioEngine sharedEngine] paused:NO];
}

Hope that helps!

like image 151
adam.artajew Avatar answered Oct 05 '22 21:10

adam.artajew