CocosDenshion音乐淡出

时间:2012-05-21 20:09:42

标签: objective-c ios audio cocos2d-iphone

我在游戏中使用cocos denshion作为音乐。 我正在播放带有代码的背景音乐:
[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@“backSong.mp3”];
然而,当游戏结束时,我需要背景音乐逐渐淡出。如何淡出背景音乐,有没有办法做到这一点?提前致谢! 另外,ObjectAL是否比CocosDenshion更好?如果是这样,有什么区别/优势?

2 个答案:

答案 0 :(得分:9)

试试这个:

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];

希望有所帮助!

答案 1 :(得分:2)

我发现这样做的唯一方法是安排执行方法并相应地更改音量设置,如下所示:

-(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:)];
        }
    }

}

这是我的声音服务提供程序实现类的简化(已编辑)示例(未按此处所示进行测试)。一般的想法是安排自己一种方法,在一段时间内逐渐淡出音乐(这里是一个应用范围的常量,K_MUSIC_FADE_TIME)。