32
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swiftを使ってMacで動画再生するメモ(AVPlayerView)

Posted at

参考: 006 動画の再生 - Swift Docs

Swiftを使ってMacで動画再生するアプリを作りたいので、とりあえずAVPlayerViewというやつを使ってみた。
ほぼ上のiOS用ドキュメント通りで動いた。

StoryboardからAVPlayerViewを設置してOutletを作って以下の通りでバンドルした動画リソースの再生までできた。お手軽。

import Cocoa
import AVKit
import Foundation
import AVFoundation

class ViewController: NSViewController {

    @IBOutlet weak var playerView: AVPlayerView!
    
    var videoPlayer:AVPlayer!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // パスからassetを生成.
        let path = NSBundle.mainBundle().pathForResource("sample", ofType: "mov")
        let fileURL = NSURL(fileURLWithPath: path!)
        let avAsset = AVURLAsset(URL: fileURL, options: nil)
        
        // AVPlayerに再生させるアイテムを生成.
        let playerItem = AVPlayerItem(asset: avAsset)
        
        // AVPlayerを生成.
        videoPlayer = AVPlayer(playerItem: playerItem)
        
        playerView.player = videoPlayer
        
        videoPlayer.play()
        
    }

    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }
}

名称未設定 2.png

気づいたこと

  • 上ではvideoPlayer.play()してるけど、別になくても勝手に再生が始まる
    • むしろ自動再生させない方法がわからない
  • 再生・一時停止、シークバー操作、タイムコードなどは特に何もしなくても動作する
  • playerView.showsFullScreenToggleButton = trueを追加すると最大化ボタンが出てきて、実際に動作する
32
27
1

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
32
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?