如何淡化NSSound对象

Stu*_*haw 5 objective-c nssound

我为我的Mac写了一个廉价而欢快的声板,我用NSSound播放各种声音:

-(void)play:(NSSound *)soundEffect:(BOOL)stopIfPlaying {
    BOOL wasPlaying = FALSE;

    if([nowPlaying isPlaying])  {
        [nowPlaying stop];
        wasPlaying = TRUE;
    }   

    if(soundEffect != nowPlaying)
    {
        [soundEffect play];
        nowPlaying = soundEffect;
    } else if(soundEffect == nowPlaying && ![nowPlaying isPlaying] && !wasPlaying) {
        [nowPlaying play];
    }
}
Run Code Online (Sandbox Code Playgroud)

而不是仅仅停止它,我希望它能在几秒钟内消失.

Stu*_*haw 1

这是该方法的最终版本:

-(void)play:(NSSound *)soundEffect:(BOOL)stopIfPlaying {
    BOOL wasPlaying = FALSE;

    if([nowPlaying isPlaying])  {
        struct timespec ts;
        ts.tv_sec = 0;
        ts.tv_nsec = 25000000;

        // If the sound effect is the same, fade it out.
        if(soundEffect == nowPlaying)
        {
            for(int i = 1; i < 30; ++i)
            {
                [nowPlaying setVolume: (1.0 / i )];
                nanosleep(&ts, &ts);
            }           
        }

        [nowPlaying stop];
        [nowPlaying setVolume:1];
        wasPlaying = TRUE;
    }   

    if(soundEffect != nowPlaying)
    {
        [soundEffect play];
        nowPlaying = soundEffect;
    } else if(soundEffect == nowPlaying && ![nowPlaying isPlaying] && !wasPlaying) {
        [nowPlaying play];
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,只有当我传入相同的声音(即单击相同的按钮)时,它才会淡出,而且,我选择了 nanosleep 而不是 sleep,因为它的粒度为 1 秒。

我花了一段时间试图弄清楚为什么我的 200 毫秒延迟似乎没有任何效果,但 200 纳秒其实并没有那么长,是吗:-)