Pierro787 Pierro787 - 1 year ago 216
iOS Question

ios - Swift 2.2 - SpriteKit - Looping a video with SpriteKit

When I create a video object with SpriteKit

let background = SKVideoNode(videoFileNamed: "Video.mov")

I get only one play with the command:


How can I create an infinite loop to make it play all the time ?

I have found some replies about this question, but only in Objective-C, not in Swift. I have to use AVPlayer() but how ?

Thanks for your help,

Answer Source

I found the solution by compiling different precedent responses from stackoverflow. Here is the working code (swift 2.2). This code loops seamlessly the video playback with a SKSVideoNode object on the scene (with an AVPlayer initializer):

override func didMoveToView(view: SKView) {

    let urlStr = NSBundle.mainBundle().pathForResource("Video_Socle", ofType: "mov")
    let url = NSURL(fileURLWithPath: urlStr!)

    player = AVPlayer(URL: url)

 NSNotificationCenter.defaultCenter().addObserverForName(AVPlayerItemDidPlayTo     EndTimeNotification
   , object: player!.currentItem, queue: nil)
    { notification in
        let t1 = CMTimeMake(5, 100);

    videoNode = SKVideoNode(AVPlayer: player!)
    videoNode!.position = CGPointMake(frame.size.width/2, frame.size.height/2)
    videoNode!.size = CGSize(width: 2048, height: 1536)
    videoNode!.zPosition = 0

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download