尝试播放背景音频时出现奇怪的错误
我已完成以下操作:
功能✅
框架✅
我的代码:
var player = AVPlayer()
var playerViewController = AVPlayerViewController()
override func viewDidLoad() {
super.viewDidLoad()
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.mixWithOthers, .allowAirPlay])
print("Playback OK")
UIApplication.shared.beginReceivingRemoteControlEvents()
addPlayerNotifications()
try AVAudioSession.sharedInstance().setActive(true)
print("Session is Active")
} catch {
fatalError(error.localizedDescription)
}
}
addPlayerNotifications()
:
func addPlayerNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidPlayToEnd), name: .AVPlayerItemDidPlayToEndTime, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
}
但是,这是一个标签栏应用程序,当切换到相应的部分时,我因以下错误而崩溃:
线程1:致命错误:该操作无法完成。 (OSStatus错误-50。)在此行:
fatalError(error.localizedDescription)
更奇怪的是,
此代码适用于:
模拟器✅
物理iPhone X(iOS 12.4.1)❌
在另一个没有Tabbar的Xcode项目中
这是一个带有2个视图控制器的简单选项卡。我真的不知道我在做什么错
答案 0 :(得分:1)
我建议在后台运行时使用isOn = false
调用此功能,而在前景运行时则使用true
调用此功能。这样会关闭轨道媒体,但会保持声音。
func setPlayerMediaCharacteristic(isOn: Bool) {
guard let currentPlayerItem = playerViewController.player?.currentItem else { return }
for track in currentPlayerItem.tracks where track.assetTrack.hasMediaCharacteristic(.visual) {
track.isEnabled = isOn
}
}