Skip to content

Instantly share code, notes, and snippets.

@alexpersian
Last active June 5, 2017 15:33
Show Gist options
  • Save alexpersian/4018426176ba51a21afc4347f1c16e73 to your computer and use it in GitHub Desktop.
Save alexpersian/4018426176ba51a21afc4347f1c16e73 to your computer and use it in GitHub Desktop.
Implementation of a looping video player using AVPlayerQueue
import AVFoundation
struct Video {
let path: URL
let title: String
}
final class LoopingVideoPlayer: AVQueuePlayer {
private let videos: [Video]
private let videoQueue: [AVPlayerItem]
init(with videos: [Video]) {
self.videos = videos
self.videoQueue = videos.map { AVPlayerItem(url: $0.path) }
super.init(items: videoQueue)
}
var currentVideo: AVPlayerItem? {
return self.items().first
}
var currentVideoTitle: String? {
guard
let path = (self.items().first?.asset as? AVURLAsset)?.url,
let video = videos.filter({ $0.path == path }).first
else {
return nil
}
return video.title
}
/**
Plays the next video in the queue and moves the previously playing video to the back of the queue.
This allows for the video queue to loop.
- returns: Boolean value indicating the success of the video advance
*/
func playNextVideo() -> Bool {
guard let tempVideo = currentVideo else { return false }
self.advanceToNextItem()
tempVideo.seek(to: kCMTimeZero)
self.insert(tempVideo, after: nil)
return true
}
}
@alexpersian
Copy link
Author

alexpersian commented Jun 5, 2017

Oddly this doesn't quite work right because of something with the NSObject initializer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment