Created
October 19, 2019 16:33
-
-
Save bannzai/b1436d1890893f949bc7c8b9fc3c440f to your computer and use it in GitHub Desktop.
InfinitePlayView
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class VideoPlayerView: UIView { | |
fileprivate let resourcePath: String | |
fileprivate let fileExtension: String | |
fileprivate let asset: AVAsset | |
fileprivate let playerItem: AVPlayerItem | |
fileprivate let player: AVPlayer | |
public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } | |
public init(resourcePath: String, ofType: String) { | |
self.resourcePath = resourcePath | |
self.fileExtension = ofType | |
let path = Bundle.main.path(forResource: self.resourcePath, ofType: self.fileExtension) | |
let fileURL = URL(fileURLWithPath: path!) | |
let asset = AVAsset(url: fileURL) | |
self.asset = asset | |
let playerItem = AVPlayerItem(asset: asset) | |
self.playerItem = playerItem | |
player = AVPlayer(playerItem: playerItem) | |
super.init(frame: .zero) | |
videoLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill | |
videoLayer.player = player | |
} | |
public override class var layerClass: AnyClass { | |
return AVPlayerLayer.self | |
} | |
public var videoLayer: AVPlayerLayer { | |
return layer as! AVPlayerLayer | |
} | |
public func start() { | |
let time = CMTime(seconds: 0, preferredTimescale: Int32(NSEC_PER_SEC)) | |
player.seek(to: time) | |
player.play() | |
} | |
public func videoSize() -> CGSize { | |
guard let videoTrack = asset.tracks(withMediaType: AVMediaType.video).first else { | |
return .zero | |
} | |
return videoTrack.naturalSize.applying(videoTrack.preferredTransform) | |
} | |
} | |
public class InfinitePlayerView: VideoPlayerView { | |
public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } | |
public override init(resourcePath: String, ofType: String) { | |
super.init(resourcePath: resourcePath, ofType: ofType) | |
NotificationCenter.default.addObserver( | |
self, | |
selector: #selector(restart(notification:)), | |
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, | |
object: nil | |
) | |
} | |
@objc func restart(notification: Notification) { | |
start() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment