Last active
December 28, 2018 08:54
-
-
Save lanserxt/0640cf017e925604e312d34137c29a62 to your computer and use it in GitHub Desktop.
Loop playback with AVQueuePlayer
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
//: [Previous](@previous) | |
import UIKit | |
import PlaygroundSupport | |
import AVFoundation | |
import AVKit | |
let frame = CGRect(x: 0, y: 0, width: 400, height: 400) | |
final class LoopedVideoPlayerView: UIView { | |
fileprivate var videoURL: URL? | |
fileprivate var queuePlayer: AVQueuePlayer? | |
fileprivate var playerLayer: AVPlayerLayer? | |
func playViewURL(_ videoURL: URL) { | |
let playerItem = AVPlayerItem(url: videoURL) | |
self.queuePlayer = AVQueuePlayer(playerItem: playerItem) | |
NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil, queue: nil) {[weak self] notif in | |
print("Video playback ended") | |
self?.queuePlayer?.insert(AVPlayerItem(url: videoURL), after: nil) | |
} | |
self.playerLayer = AVPlayerLayer(player: self.queuePlayer) | |
guard let playerLayer = self.playerLayer else {return} | |
playerLayer.videoGravity = .resizeAspectFill | |
playerLayer.frame = self.frame | |
self.layer.addSublayer(playerLayer) | |
self.queuePlayer?.play() | |
} | |
override init(frame: CGRect) { | |
super.init(frame: frame) | |
} | |
required init?(coder aDecoder: NSCoder) { | |
super.init(coder: aDecoder) | |
} | |
} | |
let container = LoopedVideoPlayerView(frame: frame) | |
PlaygroundPage.current.liveView = container | |
PlaygroundPage.current.needsIndefiniteExecution = true | |
PlaygroundPage.current.liveView = container | |
if let videoURL = Bundle.main.url(forResource: "31", withExtension: "mp4") { | |
container.playViewURL(videoURL) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment