开发者

How can I fade out an AVAudioPlayer on a background thread?

I have an audio file which needs to fade out while the user is scrolling a UIScrollView. However, any performSelector:withObject:afterDelay: method is blocked until the user has stopped scrolling. So I have tried to create some code to perform a fadeout on another thread:

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

It gets as far as the performSelector, but no further because I guess it's trying to perform on a thread it has no access to. I can't even change it for performSelector:onThread:withObject:waitUntilDone: because there is no delay o开发者_Python百科ption.

Any ideas? Why have they made it so hard to just fade out a sound? moan

Thanks!


I resolved a similar issue by scheduling the selector in a different run loop mode than the default one. This way it is not interfering with the scrolling events. Using the NSRunLoopCommonModes worked for me:

[self performSelector:@selector(fadeVolumeDown:) 
           withObject:aPlayer
           afterDelay:0.1 
              inModes:[NSArray arrayWithObject: NSRunLoopCommonModes]];


Inspired by the answer above

   while (theAudio.volume > 0.000000)
        [self fadeVolumeDown];

- (void) fadeVolumeDown{
    theAudio.volume -=0.01;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜