我已经为我的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];
}
}我希望它在几秒钟左右的时间里淡出,而不是直接停止。
发布于 2008-11-16 21:06:12
这是该方法的最终版本:
-(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];
}
}因此,只有当我输入相同的声音(即,点击相同的按钮)时,它才会淡出,而且,我选择了纳米睡眠,而不是睡眠,因为它的粒度是1秒。
我挣扎了一段时间,试图弄清楚为什么我的200毫秒延迟似乎没有任何影响,但然后200 NANOseconds并不是真的那么长,是吧:-)
发布于 2008-11-19 17:06:50
我会使用NSTimer来避免阻塞主线程。
发布于 2008-11-14 06:50:27
也许是这样的东西?你可能想要一个更线性的衰减,但基本的想法是做一个循环,并休眠一段时间,直到下一次更新。
if([nowPlaying isPlaying]) {
for(int i = 1; i < 100; ++i)
{
[nowPlaying setVolume: (1.0 / i)];
Sleep(20);
}
[nowPlaying stop];
wasPlaying = TRUE;
}https://stackoverflow.com/questions/288687
复制相似问题