2008-11-13 79 views
5

我已经在我的Mac编写的廉价&欢快的音板的NSSound对象,我玩的各种声音与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]; 
    } 
} 

而不是只是阻止它死了,我想让它在几秒钟内消失。

回答

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

所以只有淡出如果我通过了同样的声音(即点击相同的按钮),另外,我去了nanosleep而不是睡眠,因为它具有1秒的粒度。

我挣扎试图找出为什么我的200毫秒的延迟似乎没有任何作用了一段时间,但随后200纳秒是不是真的那么长时间了:-)

0

像这样的事情吧?你可能需要一个更线性的空投,但其基本思想是让循环和睡眠的时间,直到下一个更新周期。

if([nowPlaying isPlaying]) { 
    for(int i = 1; i < 100; ++i) 
    { 
     [nowPlaying setVolume: (1.0/i)]; 
     Sleep(20); 
    } 
    [nowPlaying stop]; 
    wasPlaying = TRUE; 
} 
+0

我只是尝试这样做克里斯,睡眠功能把整个笔记本电脑睡觉,这让我窃喜。 睡眠正常工作,但它发生在秒,而不是毫秒的参数。 – 2008-11-15 15:43:48

+0

诅咒你犯错误的shift键! – 2008-11-17 22:09:31

1

我会使用的NSTimer避免阻塞主线程。