Thursday, February 21, 2019

Swift play video file

We can play video file with mov and mp4 format in Swift.
Drag video file in to project tree folder.
Import libraries..
import UIKit
import AVFoundation
import AVKit
Copy in to viewDidLoad.
let url = NSBundle.mainBundle().pathForResource("video", ofType: "mp4")!
let play = AVPlayer(URL: NSURL(fileURLWithPath: url))
let playerViewController = AVPlayerViewController()
 playerViewController.player = play
self.addChildViewController(playerViewController)
self.view.addSubview(playerViewController.view)
playerViewController.view.frame = self.view.frame
play.play()

Run to see this screen.

If don’t want play full screen, repalce line playerViewController.view.frame = self.view.frame
by playerViewController.view.frame =  CGRectMake(30,80,300,400)
Screen play now width 300dp and height 400dp.
If app crash, check Bundle Resource.
Click top tree folder, choose Build Phases, extend Copy Bundle Resources by click to left triangle symbol, scroll down and Click + .

Choose video file, click Add.

If a file format not support, screen will look like this.

No comments:

Post a Comment