我有一个没有音乐的视频,即使在另一个应用中播放音乐,我也希望向用户显示。如果播放音乐,我的下面代码会中断视频播放。
在视图控制器中:
if let filePath = Bundle.main.path(forResource: "streamVideo", ofType: "mp4") {
print("handled video: \(filePath)")
let videoURL = NSURL(fileURLWithPath: filePath)
avPlayer = AVPlayer(url: videoURL as URL)
avPlayerLayer = AVPlayerLayer(player: avPlayer)
avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
avPlayer.volume = 0
avPlayer.actionAtItemEnd = AVPlayerActionAtItemEnd.none
avPlayerLayer.frame = view.layer.bounds
view.backgroundColor = UIColor.clear;
view.layer.insertSublayer(avPlayerLayer, at: 0)
NotificationCenter.default.addObserver(self,
selector: #selector(FirstVC.playerItemDidReachEnd),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: avPlayer.currentItem)
avPlayer.play()
}
在app delegate:
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
} catch let error as NSError {
print(error)
}
do {
try AVAudioSession.sharedInstance().setActive(true)
} catch let error as NSError {
print(error)
}