根据苹果公司的说法
https://developer.apple.com/documentation/avfoundation/media_assets_playback_and_editing/creating_a_basic_video_player_ios_and_tvos/playing_audio_from_a_video_asset_in_the_background
如果您想继续播放音频,则在进入后台时将AVPlayer实例与演示文稿断开连接,并在返回前台时重新连接它。
func applicationDidEnterBackground(_ application: UIApplication) {
playerViewController.player = nil
playerLayer.player = nil
}
func applicationWillEnterForeground(_ application: UIApplication) {
playerViewController.player = player
playerLayer.player = player
}
以您的ViewController为例,使用AVPlayer
步骤:1
在“功能”中启用背景模式,包括音频、AirPlay和画中画
步骤:2
AppDelegate.swift
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .mixWithOthers)
print("Playback OK")
try AVAudioSession.sharedInstance().setActive(true)
print("Session is Active")
} catch {
print(error)
}
步骤:3
YourViewcontroller.swift
override func viewDidLoad() {
super.viewDidLoad()
addPlayerNotifications()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
removePlayerNotifations()
}
func addPlayerNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
}
func removePlayerNotifations() {
NotificationCenter.default.removeObserver(self, name:NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
NotificationCenter.default.removeObserver(self, name:NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
}
@objc func applicationWillEnterForeground(_ notification: Notification) {
yourPlayerLayer.player = yourplayer
}
@objc func applicationDidEnterBackground(_ notification: Notification) {
yourPlayerLayer.player = nil
}