Table of Contents
Swift で AVPlayer と AVPlayerViewController を使った簡単な動画再生を行う方法です。
これらを使って動画ファイルを再生すると、音量やシークバーなどのコントローラは自動的にシステム側が用意してくれます。
音声ファイルも全く動画と同じ方法で読み込み・再生ができます。
サンプルソースコード
画面中央のボタンを押すと、指定した動画ファイルを読み込んで再生するサンプルです。
ファイルはビルドの際アプリ内に組み込んだものでも、アプリの保存領域やネットワーク上のものでも再生可能です。
また、アプリの設定(info.plist)で画面の回転を制限していても、AVPlayerViewControllerでは動画を横向き(縦向き)にできます。
ライブラリは AVKit および AVFoundation をインポートする必要があります。
以下のサンプルは、プロジェクトを Simple View Application のテンプレートで新規作成した後にできる ViewController.swift を書き換えたものです。
ViewController.swift
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | import UIKit import AVKit import AVFoundation class ViewController : UIViewController { override func viewDidLoad () { super . viewDidLoad () let button = UIButton ( type : . system ) button . setTitle ( "Play" , for : . normal ) button . addTarget ( self , action : # selector ( self . playMovieFromProjectBundle ), for : . touchUpInside ) // Documentディレクトリから動画を読み込む場合はこちら // button.addTarget(self, action: #selector(self.playMovieFromLocalFile), for: .touchUpInside) button . sizeToFit () button . center = self . view . center self . view . addSubview ( button ) } // アプリ内に組み込んだ動画ファイルを再生 func playMovieFromProjectBundle () { if let bundlePath = Bundle . main . path ( forResource : "test" , ofType : "mp4" ) { let videoPlayer = AVPlayer ( url : URL ( fileURLWithPath : bundlePath )) // 動画プレイヤーの用意 let playerController = AVPlayerViewController () playerController . player = videoPlayer self . present ( playerController , animated : true , completion : { videoPlayer . play () }) } else { print ( "no such file" ) } } // アプリのDocumentディレクトリにある動画ファイルを再生 func playMovieFromLocalFile () { let path = "\( getDocumentDirectory () )/file.mp4" let videoPlayer = AVPlayer ( url : URL ( fileURLWithPath : path )) // 動画プレイヤーの用意 let playerController = AVPlayerViewController () playerController . player = videoPlayer self . present ( playerController , animated : true , completion : { videoPlayer . play () }) } // Documentディレクトリのパスを取得 func getDocumentDirectory () - > String { return NSSearchPathForDirectoriesInDomains ( FileManager . SearchPathDirectory . documentDirectory , FileManager . SearchPathDomainMask . userDomainMask , true ). last ! } override func didReceiveMemoryWarning () { super . didReceiveMemoryWarning () } } |
動画の再生画面の例
アプリを起動後、画面中央に表示されるボタンをタップすると、プロジェクトのリソースにある test.mp4 を読み込んだ動画プレイヤーが起動します。
動画や音声をバックグラウンドで再生する
そのままでは、アプリをバックグラウンドに移動させたり、端末をスリープ状態にしたりすると再生が止まってしまいます。
バックグラウンドでも音楽や動画の音声を再生し続けたい場合は、以下のコードを追加します。
1 2 3 4 5 6 7 8 9 | // バックグラウンドでも再生を続けるための設定 let audioSession = AVAudioSession . sharedInstance () do { try audioSession . setCategory ( AVAudioSessionCategoryPlayback ) try audioSession . setActive ( true ) } catch let error as NSError { print ( error ) } |
AVAudioSession のカテゴリとして AVAudioSessionCategoryPlayback を設定することで、バックグラウンドでも音声が再生され続けます。