Swift: AVPlayerViewController will not play video from device - ios

URL
// What prints below for selectedMedia.videoPath
file:///private/var/mobile/Containers/Data/Application/9A7E21B7-81E7-4F4A-97FB-019AB99A3407/tmp/trim.4B1C07A3-0139-4AC3-B6DE-EB90F8CF582D.MOV
CODE
// From UIPickerViewController didFinishPickingMediaWithInfo
// To Populate a media
media.videoPath = info[UIImagePickerControllerMediaURL] as? URL
// To Load Player
self.selectedMedia = self.media[indexPath.row]
if self.selectedMedia?.isVideo == true {
let moviePlayer = AVPlayerViewController()
moviePlayer.delegate = self
print(self.selectedMedia!.videoPath!)
let url = URL(fileURLWithPath: self.selectedMedia!.videoPath! )
let player = AVPlayer(url: url)
moviePlayer.player? = player
self.present(moviePlayer, animated: true, completion: {
player.play()
})
}
else {
self.showMediaImage()
}
// Result of above code = AVPlayerViewController is displayed with no content.
QUESTION
Why is the video not playing?

Related

how to record uiview as Video with Audio iOS swift

in my app, i am playing video in AVView now i am doing some transition by view in that view now i want to record that view as Video, also i need Audio also, so how can i do this?
i tried this library but its getting stuck video multiple times
https://github.com/wess/Glimpse
i did enough R&D but i am not getting any possible solution.
here is my code:
{
guard let path = Bundle.main.path(forResource: "video2", ofType: "mov") else {
return
}
let videoURL = NSURL(fileURLWithPath: path)
// Create an AVPlayer, passing it the local video url path
let player = AVPlayer(url: videoURL as URL)
let controller = AVPlayerViewController()
controller.player = player
present(controller, animated: true) {
player.play()
self.createImageView()
controller.view.addSubview(self.viewForImage)
self.zoomAnimationCount = 0
self.zoomInAnimation()
DispatchQueue.main.async {
self.glimpse!.startRecording(controller.view, onCompletion: { fileOuputURL in
print("DONE WITH OUTPUT: \(fileOuputURL?.absoluteString ?? "")")
})
DispatchQueue.main.asyncAfter(deadline: .now() + 20.0, execute: {
self.glimpse!.stop()
})
}
}
}
please let me know how can i do it?

The URL given through the AVCaptureFileOutputRecordingDelegate function unable to be played

I'm trying to create a Snapchat-like app where the user can take a video by holding down a button. However, when the user is done taking a video, and the delegate calls fileOutput, the given url outputFileURL cannot be played using an AVPlayer. I know that the video was actually recorded though, because I can upload the file to Firebase and download it from there.
Here's my code for the fileOutput function:
func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) {
if error == nil {
videoURL = outputFileURL
flipHiddenViews()
// playback video
player = AVPlayer(url: outputFileURL)
playerLayer = AVPlayerLayer(player: player)
playerLayer?.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer!)
player?.play()
} else {
print(error?.localizedDescription)
}
}
Here's how I initialize the button that the user holds down:
let photoButton:UIButton = {
let but = UIButton(type: .custom)
but.layer.cornerRadius = 40
but.layer.borderColor = UIColor.white.cgColor
but.layer.borderWidth = 4
but.clipsToBounds = true
but.addTarget(self, action: #selector(takeVideo), for: .touchDown)
but.addTarget(self, action: #selector(stopVideo), for: [.touchUpInside, .touchUpOutside])
but.translatesAutoresizingMaskIntoConstraints = false
return but
}()
Here's the takeVideo function:
#objc func takeVideo() {
let recordingDelegate:AVCaptureFileOutputRecordingDelegate? = self
if captureSession?.outputs != nil && videoFileOutput != nil {
captureSession?.removeOutput(videoFileOutput!)
}
videoFileOutput = AVCaptureMovieFileOutput()
self.captureSession?.addOutput(videoFileOutput!)
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let filePath = documentsURL.appendingPathComponent("temp")
// Do recording and save the output to the `filePath`
videoFileOutput?.startRecording(to: filePath, recordingDelegate: recordingDelegate!)
}
And finally, the stopVideo function:
#objc func stopVideo() {
videoFileOutput?.stopRecording()
}
What am I doing wrong?
Try this instead:
// playback video
player = AVPlayer(url: outputFileURL)
let playerController = AVPlayerViewController()
playerController.player = player
present(playerController, animated: true) {
player?.play()
}
Adding a .mov at the end of the "temp" name did it for me:
let filePath = documentsURL.appendingPathComponent("temp.mov")

How to play video file from documentdirectory using avplayer

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)

Play video from data chunks

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

Video Player Controllers are not working After Playing Video Swift

I am trying to play video from local and put it in a slider, video is playing but one the play button are disappear nothing is working in the video.
playVideo () {
guard let videoPath = NSBundle.mainBundle().pathForResource(files.fileImage, ofType: "mp4")
else {
print ("Error")
break
}
let player = AVPlayer(URL: NSURL(fileURLWithPath: videoPath))
let playerController = AVPlayerViewController()
playerController.player = player
playerController.view.frame = svSlider.frame
playerController.showsPlaybackControls = true
let videoPlayerView = playerController.view
videoPlayerView.frame = svSlider.frame
self.svSlider.addSubview(videoPlayerView)
fromLeft += videoPlayerView.frame.width
}

Resources