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?
Asked
Active
Viewed 1,474 times
3
-
it won't block ui will it? – jokeman Mar 24 '17 at 16:54
-
It's a async call right? I think you can just call it in main thread. – jokeman Mar 24 '17 at 16:54
-
For some reasons it blocks my UI, maybe prepareOrPlay or play isn't async. – user1615898 Mar 24 '17 at 17:10
-
1check this out: http://stackoverflow.com/questions/18419249/ios-audiosessionsetactive-blocking-main-thread – d4Rk Mar 24 '17 at 19:01
1 Answers
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