I have recorded a video from my app which saves the video in Photos app in iPhone. The file path of the video saved is:
file:///var/mobile/Containers/Data/Application/0A8F1D57-7336-4D52-8B64-928C381DBC4F/Documents/2022-04-14#14-26-59GMT+05:00ARVideo.mp4
How can I play the video from the file path in AVPlayer?
class SecondViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
playVideo()
}
private func playVideo() {
guard let filePath = Bundle.main.path(forResource: "file:///var/mobile/Containers/Data/Application/0A8F1D57-7336-4D52-8B64-928C381DBC4F/Documents/2022-04-14#14-26-59GMT+05:00ARVideo.mp4", ofType: "mp4") else { return}
let player = AVPlayer(url: URL(fileURLWithPath: filePath))
let vc = AVPlayerViewController()
vc.player = player
present(vc, animated: true)
}
}
import AVKit
func playVideo(){
let player = AVPlayer(url: URL(video url string) ?? URL(fileURLWithPath: "") )
let playerController = AVPlayerViewController()
playerController.player = player
self.addChild(playerController)
self.view.addSubview(playerController.view)
playerController.view.frame = self.view.frame
playerController.exitsFullScreenWhenPlaybackEnds = true
player.play()
}
class SecondViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
playVideo()
}
// if u have video in app directory/ document directory
private func playVideo() {
guard let url = URL(string: "file:///var/mobile/Containers/Data/Application/0A8F1D57-7336-4D52-8B64-928C381DBC4F/Documents/2022-04-14#14-26-59GMT+05:00ARVideo.mp4")
else {
print("url not exist")
return
}
let player = AVPlayer(url: url)
let vc = AVPlayerViewController()
vc.player = player
present(vc, animated: true)
}
// if u have video locally that u put in ur project then
private func playVideoFromLocal() {
guard let fileURL = Bundle.main.url(forResource: "file_example_MOV_480_700kB", withExtension: "mov") else {return}
let player = AVPlayer(url: fileURL)
let playerController = AVPlayerViewController()
let vc = AVPlayerViewController()
vc.player = player
present(vc, animated: true)
}
}
The path of the documents changes for the app each time it is launched, which changes the first part of the URL.
Try the following updated function to get the current location of the file:
private func playVideo() {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let playerItem = AVPlayerItem(url: URL(fileURLWithPath: documentsPath.appendingFormat("/your-video-name-here.mp4")))
let player = AVPlayer(playerItem: playerItem)
let vc = AVPlayerViewController()
vc.player = player
present(vc, animated: true)
}
Related
What I want is basically reverse an AVAsset and output video file and I found this link -
https://github.com/tempire/ReverseAVAsset/blob/master/AVAsset.swift
This is what I did:
import UIKit
import AVFoundation
import AVKit
class ViewController: UIViewController {
var playerViewController = AVPlayerViewController()
var playerView = AVPlayer()
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let path = Bundle.main.path(forResource: "video", ofType: "mov")
let outputUrl = URL(fileURLWithPath: "\(NSUUID().uuidString)video.mov")
let originalAsset = AVAsset(url: URL(fileURLWithPath: path!))
let reversedAsset = originalAsset.reversedAsset(outputUrl)
playerView = AVPlayer(playerItem: AVPlayerItem(asset: reversedAsset!))
playerViewController.player = playerView
present(playerViewController, animated: true) {
self.playerViewController.player?.play()
}
}
}
But its not working and this is what I end up with:
I think I'm doing something wrong with outputURL, please help if you know what to do
Problem was with output URL, this is the correct way to do
import UIKit
import AVFoundation
import AVKit
class ViewController: UIViewController {
var playerViewController = AVPlayerViewController()
var playerView = AVPlayer()
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let path = Bundle.main.path(forResource: "video", ofType: "mov")
//Correct way
var outputURL: URL?
do {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
outputURL = documentsURL.appendingPathComponent("\(NSUUID().uuidString)newvideo.mp4")
}
let originalAsset = AVAsset(url: URL(fileURLWithPath: path!))
let reversedAsset = originalAsset.reversedAsset(outputUrl)
playerView = AVPlayer(playerItem: AVPlayerItem(asset: reversedAsset!))
playerViewController.player = playerView
present(playerViewController, animated: true) {
self.playerViewController.player?.play()
}
}
}
The main issue was there in Method: reversedAsset(outputUrl)
There we try to write the file with a completion handler, and meanwhile we try to play the asset returned by the same method which is not even completely written on disc.
In order to resolve the issue, You've to wait for the method reversedAsset(outputUrl) to finish writing the file.
So I have a view on my HomeViewController that I want to play a video inside of. on viewDidLoad() I am calling playVideo() here is my code:
func playVideo() {
guard let filePath = Bundle.main.path(forResource: "video", ofType: "mov") else {
debugPrint("video.mov not found.")
return
}
let avPlayer = AVPlayer(url: URL(fileURLWithPath: filePath))
let avPlayerController = AVPlayerViewController()
avPlayerController.player = avPlayer
avPlayerController.view.frame = playerView.bounds
avPlayerController.showsPlaybackControls = false
avPlayerController.player?.play()
playerView.addSubview(avPlayerController.view)
playerView.bringSubview(toFront: QRButton)
}
All I get is a black background and no video. What am I doing wrong? I have tried to solve this for a while now.
iOS: 11.2 beta
Xcode: 9.2 beta
Try to use avPlayer as a class variable, maybe it has been released before it can start to play.
class ViewController: UIViewController {
var avPlayer:AVPlayer?
func playVideo() {
guard let filePath = Bundle.main.path(forResource: "video", ofType: "mov") else {
debugPrint("video.mov not found.")
return
}
avPlayer? = AVPlayer(url: URL(fileURLWithPath: filePath))
let avPlayerController = AVPlayerViewController()
avPlayerController.player = avPlayer
avPlayerController.view.frame = playerView.bounds
avPlayerController.showsPlaybackControls = false
avPlayerController.player?.play()
playerView.addSubview(avPlayerController.view)
playerView.bringSubview(toFront: QRButton)
}
}
I am creating video player application in ios,if i store mp4 file in bundle resource or if i stream url it is working fine but if i store a file in document direcory and i am trying to play with avplayer it is not playing should i handle differently with offline file in document directory
code:
let fileManager = FileManager()
let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appendingFormat("/myvideo.mp4"))
self.playVideo(filePath: destinationURLForFile.path)
func playVideo(filePath:String)
{
var playerItem = AVPlayerItem.init(url:URL.init(string: filePath)!)
var player = AVPlayer(playerItem: playerItem)
var playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.frame
self.view.layer.addSublayer(playerLayer)
player.play()
}
Try this, written in Swift 3.0,
let fm = FileManager.default
let docsurl = try! fm.url(for:.documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let path = docsurl.appendingPathComponent("myvideo.mp4")
playVideo(filePath: path)
func playVideo(filePath:String)
{
var playerItem = AVPlayerItem(url: URL(fileURLWithPath: filePath)
var player = AVPlayer(playerItem: playerItem)
var playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.frame
self.view.layer.addSublayer(playerLayer)
player.play()
}
swift 3/4 100%%%%%%% workable
Recorder open video camera
#IBAction func RecordAction(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera){
print("CameraAvailable")
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera
imagePicker.mediaTypes = [kUTTypeMovie as String]
imagePicker.allowsEditing = false
imagePicker.showsCameraControls = true
self.present(imagePicker,animated: true, completion: nil)
}
else{
print("CameraNotAvailable")
}
}
save to document directory
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
// recover video URL
let url = info[UIImagePickerControllerMediaURL] as? URL
// check if video is compatible with album
let compatible: Bool = UIVideoAtPathIsCompatibleWithSavedPhotosAlbum((url?.path)!)
// save
if compatible {
UISaveVideoAtPathToSavedPhotosAlbum((url?.path)!, self, nil, nil)
print("saved!!!! \(String(describing: url?.path))")
}
videopath = url //save url to send next function play video
dismiss(animated: true, completion: nil)
}
// error
func video(_ videoPath: String, didFinishSavingWithError error: Error?, contextInfo: UnsafeMutableRawPointer) {
}
play video from Document directory
#IBAction func playvideo(_ sender: Any)
{
let player = AVPlayer(url: videopath!) // video path coming from above function
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
playerViewController.player!.play()
}
}
I tried several methods including the above, but found that the documents path changes for the app each time it is launched, which changes the first part of the URL.
This helped me to get the current location of my file:
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let playerItem = AVPlayerItem(url: URL(fileURLWithPath: documentsPath.appendingFormat("/\(clipId).mp4")))
player = AVPlayer(playerItem: playerItem)
i want to show .mov file in custom size. i have an xib file for my controller.
thats top view is subclass of UIView. i want to show video in this view.
there is my code for create video view. but there is problem in size of my video player. how can solve this problem.
there is my code :
private func playVideo() {
guard let path = Bundle.main.path(forResource: "video_2017-06-30_15-49-05", ofType:"mov") else {
debugPrint("video.m4v not found")
return
}
let player = AVPlayer(url: URL(fileURLWithPath: path))
let playerController = AVPlayerViewController()
playerController.player = player
let avPlayerLayer = AVPlayerLayer(player: player)
avPlayerLayer.frame = videoView.layer.frame
videoView.layer.insertSublayer(avPlayerLayer, at: 0)
}
If you want a native player to be added to your view with the seek bar and play pause button then use following code:
private func playVideo() {
guard let path = Bundle.main.path(forResource: "SampleVideo", ofType:"mp4") else {
debugPrint("video.m4v not found")
return
}
let player = AVPlayer(url: URL(fileURLWithPath: path))
let playerController = AVPlayerViewController()
playerController.player = player
playerController.view.frame = videoView.bounds
videoView.addSubview(playerController.view)
player.play()
}
and if you want just the video to be played in your view with AVPlayerLayer then you can do something like below:
var player : AVPlayer!
var avPlayerLayer : AVPlayerLayer!
#IBOutlet weak var videoView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
guard let path = Bundle.main.path(forResource: "SampleVideo", ofType:"mp4") else {
debugPrint("video.m4v not found")
return
}
player = AVPlayer(url: URL(fileURLWithPath: path))
avPlayerLayer = AVPlayerLayer(player: player)
avPlayerLayer.videoGravity = AVLayerVideoGravity.resize
videoView.layer.addSublayer(avPlayerLayer)
playVideo()
}
override func viewDidLayoutSubviews() {
avPlayerLayer.frame = videoView.layer.bounds
}
private func playVideo() {
player.play()
}
This worked perfect for me hope it works for you :)
I received video from node sever in chunks of data. But video does not play in AVPlayer. Here is my code.
let videoUrl = http://staging.teemo.me/api/video/stream/sample12.MOV
playVideo(path:videoUrl, self)
func playVideo(path:String, controller:UIViewController){
let yourFinalVideoURL = path
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: [])
if (yourFinalVideoURL != "") {
let player = AVPlayer(url: NSURL(fileURLWithPath: yourFinalVideoURL) as URL)
let playerController = AVPlayerViewController()
playerController.player = player
controller.present(playerController, animated: true) {
//player.play()
if #available(iOS 10.0, *) {
player.playImmediately(atRate: 1.0)
} else {
player.play()
}
}
}
}
The follow code works for me:
let videoURL = URL(string: "Some url")
let player = AVPlayer(url: videoURL!)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
playerViewController.player!.play()
}
However when I tried to use your url it doesn't work.
I added the NSAppTransportSecurity in .plist, but it didn't work either.
It is obvious that you have a problem with the url, try to change the extension of the file sample12.MOV to sample12.mp4