Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should AVAudioPlayer be used to play sound in background or main thread?

Tags:

ios

swift

Should AVAudioPlayer be used to play sound in background or main thread? Is it a better practice to use background thread to play sound to not block the UI?

like image 560
user1615898 Avatar asked Oct 24 '25 18:10

user1615898


1 Answers

play your sound on a separate thread and I suspect your blocking issues will go away.

The easiest way to make this happen is to do:

- (void)playingAudioOnSeparateThread: (NSString *) path
{
    if(_audioPlayer)
    {
       _audioPlayer = nil; // doing this while a sound is playing might crash... 
    }

    NSLog(@"start playing audio at path %@", path);
    NSError *error = nil;
    NSData *audioData = [NSData dataWithContentsOfFile:path];
    _audioPlayer = [[AVAudioPlayer alloc] initWithData:audioData error:&error];
    if (error == nil)
    {
        [_audioPlayer play];    
    }
}

- (void)playAudio:(NSString *)path
{
   [NSThread detachNewThreadSelector: @selector(playingAudioOnSeparateThread:) toTarget: self withObject: path];
}
like image 200
Hiren Patel Avatar answered Oct 26 '25 10:10

Hiren Patel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!