Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 option.

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

Thanks!

like image 320
jowie Avatar asked Nov 16 '10 14:11

jowie


1 Answers

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]];
like image 103
Martin Cote Avatar answered Oct 06 '22 14:10

Martin Cote