I am playing video using avkit. so I have multiple video files and i want to play next and previous song on the button click. i am doing this to play video -:
func playVideo(){
let url = URL(string: historyArray[videoUrlIndex].value(forKey:kConstant.keyName.urlString) as! String)
player = AVPlayer(url: url!)
playerLayer = AVPlayerLayer(player: player)
playerLayer.videoGravity = .resize
player.currentItem?.addObserver(self, forKeyPath: "duration", options: [.new,.initial], context: nil)
addTimeObserver()
videoView.layer.sublayers?.removeAll()
playerLayer.removeFromSuperlayer()
videoView.layer.addSublayer(playerLayer)
pip = AVPictureInPictureController(playerLayer: playerLayer)
}
and in view will appear i am doing this -:
playVideo()
player.play()
This is what i am doing on next and previous button -:
@IBAction func rewindButtonPressed(_ sender: AnyObject) {
if videoUrlIndex > 0 {
videoUrlIndex = videoUrlIndex - 1
playVideo()
player.play()
}
}
@IBAction func fastforwardButtonPressed(_ sender: Any) {
if videoUrlIndex >= 0 {
videoUrlIndex = videoUrlIndex + 1
playVideo()
player.play()
}
}
But this is not working fine what is wrong with this code
Declare class variable var player = AVPlayer?
and in you playVideo()
function add self.player = player
. When you want to replace video try this:
func replaceVideo() {
let playerItem = AVPlayerItem(url: URL(string: "videoURL")!)
self.player.replaceCurrentItem(with: playerItem)
}