斯威夫特 3
我有同样的问题。每次我的应用程序进入后台然后回到前台时,我的 AVPlayer 都会消失。下面是一个更简单的代码版本,适用于我……我需要在 UIApplicationWillEnterForeground 上重置播放器。如果您需要,我可以添加更多代码,请告诉我。它现在似乎正在工作。干杯!
import UIKit
import AVFoundation
class ViewController: UIViewController {
var avPlayer: AVPlayer!
var avPlayerLayer: AVPlayerLayer!
var paused: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
// Be sure to add your file to your app (not in the assets folder) and add it to your target
let theURL = Bundle.main.url(forResource:"yourVideoFile", withExtension: "mp4")
avPlayer = AVPlayer(url: theURL!)
avPlayerLayer = AVPlayerLayer(player: avPlayer)
avPlayerLayer.frame = view.layer.bounds
avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
// .none is for looping videos if you uncomment "p: AVPlayerItem" below.
// .pause is to pause at the end of the video and hold the last frame
avPlayer.actionAtItemEnd = .pause
view.layer.insertSublayer(avPlayerLayer, at: 0)
NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd(notification:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,object: avPlayer.currentItem)
NotificationCenter.default.addObserver(self, selector: #selector(appMovingToForeground), name: Notification.Name.UIApplicationWillEnterForeground, object: nil)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
avPlayer.play()
paused = false
}
func playerItemDidReachEnd(notification: Notification) {
print("THE END")
// uncomment the following line for a looping video
// let p: AVPlayerItem = notification.object as! AVPlayerItem
// p.seek(to: kCMTimeZero)
}
func appMovingToForeground() {
print("App moved to foreground!")
avPlayerLayer = AVPlayerLayer(player: avPlayer)
view.layer.insertSublayer(avPlayerLayer, at: 0)
// If you want your video or video loop to continue playing when app moves to foreground add:
// avPlayer.play()
// paused = false
}
}