This is the 8th day of my participation in the August More Text Challenge. For details, see:August is more challenging

preface

In the last post we had the screen rotation of the video page done, now let’s start playing the video

Video playback

For video playback, we use the Swift version of Player library. Below is a rendering

1. Import the required icon into the project according to the effect drawing

2, inPlayerViewControllerIncrease inurlandidProperties,urlIt’s a videourl.idIs to request the data on the rightid

private var url: String
private var id: String

init(url: String, id: String) {
    self.url = url
    self.id = id
    if let delegate = UIApplication.shared.delegate as? AppDelegate {
        delegate.orientationMask = .landscapeRight
    }
    super.init(nibName: nil, bundle: nil)
}
Copy the code

3,PlayerThe use of

  • PlayerSome of the properties
/// Player delegate. open weak var playerDelegate: PlayerDelegate? /// Playback delegate. open weak var playbackDelegate: PlayerPlaybackDelegate? /// - Parameter url: URL of the asset. open var url: URL? /// Ranging from 0.0 to 1.0 on a linear scale. Float /// Pauses playback automatically when resigning active. open var playbackPausesWhenResigningActive: Bool = true /// Pauses playback automatically when backgrounded. open var playbackPausesWhenBackgrounded: Bool = true /// Resumes playback when became active. open var playbackResumesWhenBecameActive: Bool = true /// Resumes playback when entering foreground. open var playbackResumesWhenEnteringForeground: Bool = true /// Playback freezes on last frame frame when true and does not reset seek position timestamp.. open var playbackFreezesAtEnd: Bool = false /// Current playback state of the Player. open var playbackState: PlaybackState = .stopped /// Current buffering state of the Player. open var bufferingState: BufferingState = .unknown /// Maximum duration of playback. open var maximumDuration: TimeInterval /// Media playback's current time interval in seconds. open var currentTimeInterval: TimeInterval /// Media playback's current time. open var currentTime: CMTimeCopy the code
  • PlayerA method of
/// Playback Begins from the beginning. Open func playFromBeginning( Pauses for the media from the current time. open func playFromCurrentTime() /// Pauses for the media Stop () Stops playback of the media. open func stop() Stops playback of the media. open func stop() Stops playback of the media. open func stop() Stops playback of the media. open func stop() Stops playback of the media. open func stop() Stops playback of the media. open func stop() Stops playback of the media. open func stop() Stops playback  /// - Parameters: /// - time: The time to switch to move the playback. /// - completionHandler: Call block handler after seeking/ open func seek(to time: CMTime, completionHandler: ((Bool) -> Swift.Void)? = nil)Copy the code
  • PlayerthePlayerDelegateandPlayerPlaybackDelegate
/// Player delegate protocol
public protocol PlayerDelegate: AnyObject {
    func playerReady(_ player: Player)
    func playerPlaybackStateDidChange(_ player: Player)
    func playerBufferingStateDidChange(_ player: Player)

    // This is the time in seconds that the video has been buffered.
    // If implementing a UIProgressView, user this value / player.maximumDuration to set progress.
    func playerBufferTimeDidChange(_ bufferTime: Double)
    func player(_ player: Player, didFailWithError error: Error?)
}

/// Player playback protocol
public protocol PlayerPlaybackDelegate: AnyObject {
    func playerCurrentTimeDidChange(_ player: Player)
    func playerPlaybackWillStartFromBeginning(_ player: Player)
    func playerPlaybackDidEnd(_ player: Player)
    func playerPlaybackWillLoop(_ player: Player)
    func playerPlaybackDidLoop(_ player: Player)
}
Copy the code

3.1. Lazy loadingplayer

Private lazy var player: Player = { let player = Player() player.playerDelegate = self player.playbackDelegate = self player.playbackFreezesAtEnd = true / / / play in the final frame stop player. The playerView. PlayerBackgroundColor =. The black player. The backgroundColor = UIColor. Black player.playbackResumesWhenBecameActive = false return player }()Copy the code

3.2, layout,player

Player private func addSubviews() {view. BackgroundColor = uicolor.black addChild(player) view.addSubview(player.view) player.didMove(toParent: self) player.view.snp.makeConstraints { (make) in make.edges.equalToSuperview() } }Copy the code

3.3, addPlayerDelegate

PlayerViewController: PlayerDelegate {// start playc playerReady(_ player: Player) {} / / / play state func playerPlaybackStateDidChange (_ Player: Player) {} / / / the buffer state func playerBufferingStateDidChange (_ Player: Player) {} / / / the buffer progress func playerBufferTimeDidChange (_ bufferTime: Double) {} / / / playback error func Player (_ Player: Player, didFailWithError error: Error?) {}}Copy the code

Both play state and recosive state are enumerations, so let’s look at their definitions

PlaybackState

/// Asset playback states. public enum PlaybackState: Int, CustomStringConvertible {case stopped = 0 // Stop playing Case playing /// Play case paused // pause case failed /// Play error public var description: String { get { switch self { case .stopped: return "Stopped" case .playing: return "Playing" case .failed: return "Failed" case .paused: return "Paused" } } } }Copy the code

BufferingState

/// Asset buffering states.
public enum BufferingState: Int, CustomStringConvertible {
    case unknown = 0
    case ready
    case delayed
    
    public var description: String {
        get {
            switch self {
            case .unknown:
                return "Unknown"
            case .ready:
                return "Ready"
            case .delayed:
                return "Delayed"
            }
        }
    }
}
Copy the code

3.4, addPlayerPlaybackDelegate

The extension PlayerViewController: PlayerDelegate {/ / / broadcast pace func playerCurrentTimeDidChange (_ player: Player) { } func playerPlaybackWillStartFromBeginning(_ player: Func playerPlaybackDidEnd(_ Player: Player) {} func playerPlaybackWillLoop(_ Player: Player) Player) {} func playerPlaybackDidLoop(_ player: Player) {} }Copy the code

3.5, play

player.url = URL(string: url)
player.playFromBeginning()
Copy the code

With the video playing done, the next step is to add the control layer to control the playback