我已经设置了 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()
}
}
}
最佳答案
我认为您缺少以下代码:
do {
try AVAudioSession.sharedInstance()
.setCategory(AVAudioSession.Category.playback)
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 中。
关键代码行的典型 2019 语法:
try AVAudioSession.sharedInstance().setCategory(.playback)
在某些情况下,您可能需要:
try AVAudioSession.sharedInstance().setCategory(.playback, options: .mixWithOthers)
<小时/>
您必须在 plist 中添加此一个项(仅限一项,请注意旧示例);
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>
这是:
注意:几年前您还必须添加UIApplicationExitsOnSuspend - 今天不要添加它。
关于ios - Xcode swift - 后台模式 - 锁定时 AVPlayer 中的音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37766625/