AVAudioPlayer应该用于在后台或主线程中播放声音吗?使用后台线程播放声音以阻止UI是一种更好的做法吗?
答案 0 :(得分:3)
在单独的帖子中播放您的声音,我怀疑您的阻止问题会消失。
实现这一目标的最简单方法是:
- (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];
}