17
15

More than 5 years have passed since last update.

動画の再生をSpriteKitで行うという発想

Last updated at Posted at 2015-02-09

SKVideoNodeの概要

SpriteKitにはSKVideoNodeというクラスが存在し、その名の通りビデオの再生を実現するクラスです。
他のSKNodeのサブクラス同様にSKSceneにaddChildすることで利用することが出来ます。

SKVideoNodeの初期化

AVPlayerから初期化する場合

SKVideoNodeはAVPlayerを初期化の際に渡すことで再生するリソースを指定することが可能。

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

playerItem = AVPlayerItem(asset: asset)
player = AVPlayer(playerItem: playerItem)

videoNode = SKVideoNode(AVPlayer: player)
videoNode?.position = CGPointMake(scene.size.width/2, scene.size.height/2)

scene.addChild(videoNode!)

NSURLから初期化する場合

SKVideoNodeはNSURLを渡すだけでも初期化することができる。

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

videoNode = SKVideoNode(videoURL: url!)
videoNode?.position = CGPointMake(scene.size.width/2, scene.size.height/2)        

scene.addChild(videoNode!)

ファイル名だけで初期化も出来るぜ

この書き方が一番シンプルです。
リソースがmainBundleの中に入っていれば、ファイル名を指定するだけでSKVideoNodeは作成出来ます。

videoNode = SKVideoNode(videoFileNamed: "sample.mp4")
videoNode?.position = CGPointMake(scene.size.width/2, scene.size.height/2)      

scene.addChild(videoNode!)

SKVideoNodeの再生方法

SKVideoNodeで再生と停止するのはplay()pause()を利用するだけ。

videoNode?.play()
videoNode?.pause()

応用として

前述にもあるようにSKVideoNodeはAVPlayerから初期化出来るため、AVPlayerItemのObserverを設定することが出来る。

なので、再生が終了した際のコールバック処理などもカンタンに書くことが出来るよ。

SKVideoNodeはplayとpauseくらいしか出来ることがないので、複雑なプレイヤーを作成するのはあまり向いていないけれど、アプリ内でちょっとしたアニメーションなどを表現する際や、背景などを動かしたい場合などはかなり活躍するクラスだと思いました。

サンプルコード

reoy/SKVideoNodeSample

17
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
15