应该使用AVAudioPlayer在后台还是在主线程中播放声音?使用后台线程播放声音而不阻塞UI是不是一种更好的做法?
发布于 2017-03-25 01:18:31
在单独的线程上播放你的声音,我怀疑你的阻塞问题将会消失。
要实现这一点,最简单的方法是:
- (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];
}
https://stackoverflow.com/questions/43004731
复制相似问题