Reputation: 371
I created a game that has a starting menu screen. In this menu screen, I want a video(I recorded me playing this game via iPhone 6 simulator) to play in the background of this menu screen. I got the video to play, but what happens is when the view loads, it will show the menu, then it will show the video replacing the menu itself.
import SpriteKit
import UIKit
import AVFoundation
class MenuScene: SKScene {
var player:AVPlayer!
var VideoSprite:SKVideoNode!
override func didMoveToView(view: SKView) {
let videoURL: NSURL = NSBundle.mainBundle().URLForResource("startTo32", withExtension: "mov")!
player = AVPlayer(URL: videoURL)
player?.actionAtItemEnd = .None
player?.muted = true
let playerLayer = AVPlayerLayer(player: player)
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
playerLayer.zPosition = -100
playerLayer.frame = view.frame
player?.play()
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(MenuScene.loopVideo),
name: AVPlayerItemDidPlayToEndTimeNotification,
object: nil)
view.layer.addSublayer(playerLayer)
}
func loopVideo() {
player?.seekToTime(kCMTimeZero)
player?.play()
}
--------UPDATE--------
Here's the link to see what I'm talking about. the screen with the words is where I'm trying to get the video to play, but instead it just makes the screen go white and then plays the video itself.
Any questions or need for me to add information, just comment.
Thanks, Jordan.
Upvotes: 0
Views: 661
Reputation: 332
Here is your updated video player for Swift 4 and Spritekit:
import SpriteKit
import UIKit
import AVFoundation
class MenuScene: SKScene {
var player:AVPlayer!
var VideoSprite:SKVideoNode!
override func didMoveToView(view: SKView) {
let videoURL: NSURL = Bundle.main.url(forResource: "yourvideonamehere", withExtension: "mp4")! as NSURL
VideoSprite = SKVideoNode(url: videoURL as URL)
self.addChild(VideoSprite)
VideoSprite.play()
player = AVPlayer(url: videoURL as URL)
player?.actionAtItemEnd = .none
player?.isMuted = true
let playerLayer = AVPlayerLayer(player: player)
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
playerLayer.zPosition = 100
playerLayer.frame = view.frame
player?.play()
}
func loopVideo() {
player?.seek(to: CMTime.zero)
player?.play()
}
}
I hope this helps.
Upvotes: 0
Reputation: 9777
Try using your SKVideoNode
instead of adding a layer to your view.
Something like this:
let videoURL: NSURL = NSBundle.mainBundle().URLForResource("startTo32", withExtension: "mov")!
VideoSprite = SKVideoNode(url: videoURL)
self.addChild(VideoSprite)
VideoSprite.play()
SKVideoNode
documentation is available here.
Upvotes: 1