Last active
June 5, 2017 15:33
-
-
Save alexpersian/4018426176ba51a21afc4347f1c16e73 to your computer and use it in GitHub Desktop.
Implementation of a looping video player using AVPlayerQueue
This file contains 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
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Oddly this doesn't quite work right because of something with the
NSObject
initializer.