Customized video participant in swift utilizing AVPlayer – iOSTutorialJunction

0
41


Apple offered AVKit framework, to permit builders play multimedia content material inside their apps. With AVPlayerViewController, we are able to use Apple default playback controls. However in case if we need to play video in our personalized participant, then AVPlayer class involves rescue. On this tutorial, we’ll discover ways to play video utilizing AVPlayer in swift. You may verify the way to play video utilizing AVPlayerViewController from right here

Creating video participant in swift

On this tutorial we’ll create, a customized class inherited from UIView and add our AVPlayer to it. You may discover ways to create customized UIView class in swift from under hyperlink

Create customized UIView class with xib in swift

Creating UIView class for video participant

Create a brand new file in xcode and choose cocoa contact class, title it VideoPlayer. This class needs to be subclass of UIView as proven in under picture

Creating video player class a subclass of UIView
Creating video participant class a subclass of UIView

Now we have to create a xib file for our participant, so create a brand new file in xcode, however this time we have to choose view class underneath Consumer Interface part. We are going to title it “VideoPlayer“.

Adding UIView xib

Steps to create customized video participant utilizing AVPlayer

1. Open VIdeoPlayer.xib and add a UIView object from object library on to the view. Add constraint’s main, trailing, high, backside having fixed worth 0 with respect to superview.

2. In VideoPlayer.swift create an IBOutlet of UIView and title it as vwPlayer

class VideoPlayer: UIView {
    @IBOutlet weak var vwPlayer: UIView!
}

3. Join IBOutlet created in step 2 with view object in VideoPlayer.xib.

4. Open VideoPlayer.swift, now we’ll first import AVKit framework and create an occasion of AVPlayer

import UIKit
import AVKit

class VideoPlayer: UIView {
    @IBOutlet weak var vwPlayer: UIView!
    var participant: AVPlayer?
}

5. Add required intializer’s to our class. And in addition create a perform that can be answerable for getting view from VideoPlayer.xib class.

import UIKit
import AVKit

class VideoPlayer: UIView {
    @IBOutlet weak var vwPlayer: UIView!
    var participant: AVPlayer?
    
    override init(body: CGRect) {
        tremendous.init(body: body)
        commonInit()
    }
    
    required init?(coder: NSCoder) {
        tremendous.init(coder: coder)
        commonInit()
    }

    fileprivate func commonInit() {
        let viewFromXib = Bundle.most important.loadNibNamed("VideoPlayer", proprietor: self, choices: nil)![0] as! UIView
        viewFromXib.body = self.bounds
        addSubview(viewFromXib)
    }
}

Utilizing AVPlayer inside VideoPlayer.swift

6. Create a brand new perform that may initialize AVPlayer occasion and, add participant to VideoPlayer as a sub view. Body of AVPlayer can be identical as per of our view object of VideoPlayer class.

 fileprivate func addPlayerToView(_ view: UIView) {
        participant = AVPlayer()
        let playerLayer = AVPlayerLayer(participant: participant)
        playerLayer.body = self.bounds
        playerLayer.videoGravity = .resizeAspectFill
        view.layer.addSublayer(playerLayer)
    }

7. We are going to name our addPlayerToView perform from inside commonInit perform. As a result of participant ought to get intialized and added as quickly as an object of VideoPlyer will get created.

8. Subsequent, we’ll create a perform named playVideoWithFileName. Perform settle for two parameters, file title as considered one of its parameter and different parameter can be file kind. On this perform, first participant will attempt to get file path of the filename participant was requested to play. Secondly, if participant discovered the file, it’s going to will get performed by participant.

 func playVideoWithFileName(_ fileName: String, ofType kind:String) {
        
        guard let filePath = Bundle.most important.path(forResource: fileName, ofType: kind) else { return }
        let videoURL = URL(fileURLWithPath: filePath)
        let playerItem = AVPlayerItem(url: videoURL)
        participant?.replaceCurrentItem(with: playerItem)
        participant?.play()
    }

Get notified when participant stops taking part in video

Until now, we efficiently added code that may play video from the file laid out in playVideoWithFileName perform. So, query arises how the system will get to know as quickly as participant end taking part in video. Reply to final query is utilizing AVPlayerItemDidPlayToEndTime notification. Notification observer can be added to perform addPlayerToView and thus permitting VideoPlayer to hear for AVPlayer finish taking part in notification.

 NotificationCenter.default.addObserver(self, selector: #selector(playerEndPlay), title: .AVPlayerItemDidPlayToEndTime, object: nil)

  @objc func playerEndPlay() {
        print("Participant ends taking part in video")
    }

Full code for VideoPlayer.swift

import UIKit
import AVKit

class VideoPlayer: UIView {
    @IBOutlet weak var vwPlayer: UIView!
    var participant: AVPlayer?

    override init(body: CGRect) {
        tremendous.init(body: body)
        commonInit()
    }
    
    required init?(coder: NSCoder) {
        tremendous.init(coder: coder)
        commonInit()
    }

    fileprivate func commonInit() {
        let viewFromXib = Bundle.most important.loadNibNamed("VideoPlayer", proprietor: self, choices: nil)![0] as! UIView
        viewFromXib.body = self.bounds
        addSubview(viewFromXib)
        addPlayerToView(self.vwPlayer)
    }
    
    fileprivate func addPlayerToView(_ view: UIView) {
        participant = AVPlayer()
        let playerLayer = AVPlayerLayer(participant: participant)
        playerLayer.body = self.bounds
        playerLayer.videoGravity = .resizeAspectFill
        view.layer.addSublayer(playerLayer)
        NotificationCenter.default.addObserver(self, selector: #selector(playerEndPlay), title: .AVPlayerItemDidPlayToEndTime, object: nil)
    }
    
    func playVideoWithFileName(_ fileName: String, ofType kind:String) {
        guard let filePath = Bundle.most important.path(forResource: fileName, ofType: kind) else { return }
        let videoURL = URL(fileURLWithPath: filePath)
        let playerItem = AVPlayerItem(url: videoURL)
        participant?.replaceCurrentItem(with: playerItem)
        participant?.play()
    }
    
    @objc func playerEndPlay() {
        print("Participant ends taking part in video")
    }
}

Utilizing customized video participant class inside most important venture

Open Most important.storyboard and drag a UIView object to it. Add constraints to it and eventually change UIView class title to VideoPlayer from Id inspector.

Identity inspector changing UIView class name

In ViewController.swift, create IBOutlet of VideoPlayer and join this IBOutlet with VideoPlayer object added to storyboard. From viewDidLoad perform, name playVideoWithFileName perform. That’s it.

class ViewController: UIViewController {

    @IBOutlet weak var participant:VideoPlayer!
    
    override func viewDidLoad() {
        tremendous.viewDidLoad()
        // Do any extra setup after loading the view.
        participant.playVideoWithFileName("videoTutorial1", ofType: "mp4")
    }
}