我有一个AVPlayer设置,但是当手机被锁定或在主屏幕上时,我似乎无法继续播放视频音频。我已经编辑了info.plist并启用了音频后台模式,但我认为需要添加一些代码。请你救我。感谢
这是我的代码:
import UIKit
import AVFoundation
import AVKit
class ViewController: UIViewController {
@IBAction func WarmUp(sender: UIButton)
{
WarmUpVideo()
}
func WarmUpVideo()
{
let filePath = NSBundle.mainBundle().pathForResource("132", ofType: "MOV")
let videoURL = NSURL(fileURLWithPath: filePath!)
let player = AVPlayer(URL: videoURL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.presentViewController(playerViewController, animated: true) { () -> Void in playerViewController.player!.play()
}
}
func playExternalVideo()
{
}
@IBAction func CoolDown(sender: UIButton)
{
CoolDownVideo()
}
func CoolDownVideo()
{
let filePath = NSBundle.mainBundle().pathForResource("132", ofType: "mp4")
let videoURL = NSURL(fileURLWithPath: filePath!)
let player = AVPlayer(URL: videoURL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.presentViewController(playerViewController, animated: true) { () -> Void in playerViewController.player!.play()
}
}
}
答案 0 :(得分:6)
我认为你错过了以下代码:
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
print("AVAudioSession Category Playback OK")
do {
try AVAudioSession.sharedInstance().setActive(true)
print("AVAudioSession is Active")
} catch let error as NSError {
print(error.localizedDescription)
}
} catch let error as NSError {
print(error.localizedDescription)
}
将此添加到viewDidLoad。
答案 1 :(得分:0)
我在Apple的文档中找到了解决方案。除背景模式外,您还需要将播放器设置为nil以避免自动暂停。
这是链接: