Objective-C中AVPlayer直播时快照音效播放异常及双音频同时播放问题
问题原因分析
你的问题核心在于AVAudioPlayer的生命周期问题:在screenFlash方法里,player是局部变量,当方法执行到末尾时,这个局部对象会被ARC自动释放。而[player play]是异步执行的,方法结束后player被销毁,音频自然就中断了。
为什么加断点能播放?因为断点会让方法暂停执行,player还没被释放,音频有足够时间完成播放,所以能听到声音。
解决方案
把AVAudioPlayer改成实例变量,让它被当前控制器强引用,保证音频播放过程中不会被释放:
- 先在控制器的类扩展(或头文件)里声明属性:
@property (nonatomic, strong) AVAudioPlayer *snapshotSoundPlayer;
- 修改
screenFlash方法的代码:
- (void)screenFlash { NSString *soundFilePath = [NSString stringWithFormat:@"%@/Snapshoot.m4a",[[NSBundle mainBundle] resourcePath]]; NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath]; self.snapshotSoundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil]; self.snapshotSoundPlayer.numberOfLoops = 1; // 注意:numberOfLoops=1是播放2次,0是播放1次,可根据需求调整 [self.snapshotSoundPlayer play]; UIView *flash = [[UIView alloc] initWithFrame:self.view.frame]; flash.backgroundColor = UIColor.whiteColor; flash.alpha=1; [self.view addSubview:flash]; [UIView animateWithDuration:0.3 animations:^{ flash.alpha=0; } completion:^(BOOL finished) { [flash removeFromSuperview]; // 播放完成后置空释放player,避免不必要的内存占用 self.snapshotSoundPlayer = nil; }]; }
关于同时播放直播音频与快照音效的问题
完全可以实现,只需要配置AVAudioSession的类别,允许音频混合播放:
在控制器的viewDidLoad(或初始化阶段)添加以下代码:
#import <AVFoundation/AVFoundation.h> // ... - (void)viewDidLoad { [super viewDidLoad]; // 配置音频会话 AVAudioSession *session = [AVAudioSession sharedInstance]; NSError *error = nil; // 设置为播放类别,允许和其他音频混合 [session setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&error]; if (error) { NSLog(@"配置音频会话失败:%@", error.localizedDescription); } [session setActive:YES error:&error]; }
这样你的AVPlayer(摄像头直播流的音频)和AVAudioPlayer(快照音效)就能同时播放了。
内容的提问来源于stack exchange,提问作者Ivan Schaab
相关产品推荐
相关产品推荐

