3

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?

user1615898
  • 1,185
  • 1
  • 10
  • 20

1 Answers1

4

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];
}
Libin Varghese
  • 1,506
  • 13
  • 19
Hiren Patel
  • 190
  • 7