How to play a local video with Swift?
another Swift 3 Example. The provided solution did not work for me.
private func playVideo(from file:String) {
let file = file.components(separatedBy: ".")
guard let path = Bundle.main.path(forResource: file[0], ofType:file[1]) else {
debugPrint( "\(file.joined(separator: ".")) not found")
return
}
let player = AVPlayer(url: URL(fileURLWithPath: path))
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
player.play()
}
useage:
playVideo(from: "video.extension")
Note: Check Copy Bundle Resources under Build Phases to ensure that the video is available to the Project.
Sure you can use Swift!
1. Adding the video file
Add the video (lets call it video.m4v
) to your Xcode project
2. Checking your video is into the Bundle
Open the Project Navigator
cmd + 1
Then select your project root
> your Target
> Build Phases
> Copy Bundle Resources
.
Your video MUST be here. If it's not, then you should add it using the plus button
3. Code
Open your View Controller and write this code.
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
playVideo()
}
private func playVideo() {
guard let path = Bundle.main.path(forResource: "video", ofType:"m4v") else {
debugPrint("video.m4v not found")
return
}
let player = AVPlayer(url: URL(fileURLWithPath: path))
let playerController = AVPlayerViewController()
playerController.player = player
present(playerController, animated: true) {
player.play()
}
}
}