ios14 - iOS 14 在后台播放视频中的音频
问题描述
iOS 14 在后台播放视频中的音频:当应用程序进入后台时音频暂停(即使我在 Capability 中打开了后台模式)。
如果 avPlayer 在前台播放,用户按下设备锁定按钮,它就会发生。
解决方案
如果您正在使用 avplayer 播放视频,并且还想在应用程序处于后台时播放音频。
试试这个代码,它适用于我的机器:
- Xcode 版本:12.0
- iOS版本:iOS 14
//first, observe the relative notification
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationWillResignActive:)
name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(applicationWillEnterForeground:)
name:UIApplicationWillEnterForegroundNotification object:nil];
//Add an observer to AVPlayerItem,this is the key point!!!
[playerItem addObserver:self forKeyPath:@"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionNew context:nil];
-(void)applicationWillResignActive:(NSNotification *)notification{
//1 make sure the category of AVAudioSession is AVAudioSessionCategoryPlayback
AVAudioSession *session=[AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
[session setActive:YES error:nil];
//2 This is important!!!
//set the avplayerlayer.player = nil.
mavPlayerLayer.player = nil;
}
//when app becomes active,we should add the player to the avplayerlayer.
-(void)applicationWillEnterForeground:(NSNotification *)notification{
// restore the avPlayerLayer.player
mavPlayerLayer.player = mavPlayer;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if ([keyPath isEqualToString:@"playbackLikelyToKeepUp"]) {
NSLog(@"playbackLikelyToKeepUp");
[mavPlayer play];
}
}
当然,不要忘记在 info.plist 文件中添加相关属性以支持后台播放。
推荐阅读
- wpf - 在 WPF 中更改 ListBoxItem 的选择颜色
- python - 有没有办法通过导入来从我创建另一个类的实例的地方获取类名称?
- javascript - 在 react/Javscript 中使用动态键构造对象数组
- javascript - 角度 PNPM 样式问题
- java - 在 Spring Boot webapp 中找不到 .jsp 文件
- python - Apache 上的 Flask-login 在点击几下并重新加载几页后将用户设置为匿名
- r - 行总和作为 R 表中的额外列
- html - 如何从表格中删除单元格分隔线,同时使用 CSS 保留最后一个单元格的水平线?
- javascript - 从电话号码中删除前导“0”并替换为 +44
- linux - 如何通过curl指定和提取html元素