我正在使用AVPLayer在videoView中播放视频,但是当应用进入后台模式并再次打开该应用时,视频会暂停。
func playVideo() {
if let filePath = Bundle.main.path(forResource: "Audios/copy1", ofType:"mp4") {
let filePathUrl = NSURL.fileURL(withPath: filePath)
videoPlayer = AVPlayer(url: filePathUrl)
let playerLayer = AVPlayerLayer(player: videoPlayer)
playerLayer.frame = self.videoView.bounds
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.videoPlayer?.currentItem, queue: nil) { (_) in
self.videoPlayer?.seek(to: kCMTimeZero)
self.videoPlayer?.play()
self.videoPlayer.rate = 0.5
self.videoPlayer.actionAtItemEnd = .none
}
self.videoView.layer.addSublayer(playerLayer)
videoPlayer?.play()
}
}
答案 0 :(得分:0)
是可以的,但是您必须正确设置。
AVAudioSession
首先,您必须将“音频背景”模式设置为“开”并配置音频会话:
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
let _ = try AVAudioSession.sharedInstance().setActive(true)
} catch let error as NSError {
print("an error occurred when audio session category.\n \(error)")
}
第二次:
func applicationDidEnterBackground(_ application: UIApplication) {
// Disconnect the AVPlayer from the presentation when entering background
// If presenting video with AVPlayerViewController
playerViewController.player = nil
// If presenting video with AVPlayerLayer
playerLayer.player = nil
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Reconnect the AVPlayer to the presentation when returning to foreground
// If presenting video with AVPlayerViewController
playerViewController.player = player
// If presenting video with AVPlayerLayer
playerLayer.player = player
}