如何在后台线程上淡出AVAudioPlayer?

jow*_*wie 7 objective-c avaudioplayer nsthread ipad ios

我有一个音频文件,当用户滚动UIScrollView时需要淡出.但是,performSelector:withObject:afterDelay:在用户停止滚动之前,任何方法都会被阻止.所以我试图创建一些代码来在另一个线程上执行淡出:

- (void)fadeOut
{
    [NSThread detachNewThreadSelector:@selector(fadeOutInBackground:) toTarget:self withObject:self.audioPlayer];
}

- (void)fadeOutInBackground:(AVAudioPlayer *)aPlayer
{
    NSAutoreleasePool *myPool = [[NSAutoreleasePool alloc] init];
    [self performSelector:@selector(fadeVolumeDown:) withObject:aPlayer afterDelay:0.1]; 
    [myPool release];
}

- (void)fadeVolumeDown:(AVAudioPlayer *)aPlayer
{
    aPlayer.volume = aPlayer.volume - 0.1;
    if (aPlayer.volume < 0.1) {
        [aPlayer stop];         
    } else {
        [self performSelector:@selector(fadeVolumeDown:) withObject:aPlayer afterDelay:0.1];  
    }
}
Run Code Online (Sandbox Code Playgroud)

它得到了performSelector,但没有进一步,因为我猜它试图在一个它无法访问的线程上执行.我甚至无法改变它,performSelector:onThread:withObject:waitUntilDone:因为没有延迟选项.

有任何想法吗?他们为什么要这么难以淡出声音呢?呻吟

谢谢!

Mar*_*ote 14

我通过将选择器安排在与默认运行循环模式不同的运行循环模式中来解决类似的问题.这样它就不会干扰滚动事件.使用NSRunLoopCommonModes为我工作:

[self performSelector:@selector(fadeVolumeDown:) 
           withObject:aPlayer
           afterDelay:0.1 
              inModes:[NSArray arrayWithObject: NSRunLoopCommonModes]];
Run Code Online (Sandbox Code Playgroud)

  • 绝对的天才.谢谢!:) (2认同)