I am using a library called Gallery to select one video from Photos. Whenever a video is selected, I would like to play that selected video (silently) somewhere in my UIViewController.
The for this question relevant part of the plugin is the function func galleryController(_ controller: GalleryController, didSelectVideo video: Video) which is called when a video is selected. I initially tried using the function which you'll find under this link (presented by the library) to test if it would work but nothing happened: No controller was presented. After having done some research I believed I needed to transfer the temporary file (found under tempPath) to the documents directory - which doesn't seem to work either. You'll find the code I am currently using below.
If I print tempPath (the temporary path) and videoFileUrl (the URL the file is supposed to be transferred to) I get the following URLs respectively:
tempPath:
Optional(file:///private/var/mobile/Containers/Data/Application/D9B0DCB6-8F99-4284-9BFF-52A284C6F1AE/tmp/F3DC43D0-491A-4548-9960-D01686B54ACB.mp4)
videoFileUrl:
file:///var/mobile/Containers/Data/Application/D9B0DCB6-8F99-4284-9BFF-52A284C6F1AE/Documents/F3DC43D0-491A-4548-9960-D01686B54ACB.mp4
Code
internal var gallery: GalleryController?
internal let editor: VideoEditing = VideoEditor()
func galleryController(_ controller: GalleryController, didSelectVideo video: Video) {
controller.dismiss(animated: true, completion: nil)
editor.edit(video: video) { (editedVideo: Video?, tempPath: URL?) in
DispatchQueue.main.async {
guard let temporaryPath = tempPath else { return }
let fileName = temporaryPath.lastPathComponent
let fileManager = FileManager.default
let videoFileUrl = try! fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent(fileName)
if fileManager.fileExists(atPath: videoFileUrl.path) == false {
try! fileManager.copyItem(at: temporaryPath, to: videoFileUrl)
}
let player = AVPlayer(url: videoFileUrl)
//print(tempPath)
//print(videoFileUrl)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.frame
self.view.layer.addSublayer(playerLayer)
}
}
gallery = nil
}
Related
My objective is to read a video media I downloaded and stored to my iOS device file system. Unfortunately, the video player stalls with the following code:
#IBAction func playVideo(_ sender: UIButton) {
if let video = detailItem {
do {
let url = try FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false)
.appendingPathComponent(video.uuid)
debugPrint("url: \(url)")
// Create an AVPlayer, passing it the HTTP Live Streaming URL.
let player = AVPlayer(url: url)
// Create a new AVPlayerViewController and pass it a reference to the player.
let controller = AVPlayerViewController()
controller.player = player
// Modally present the player and call the player's play() method when complete.
present(controller, animated: true) {
player.play()
}
} catch {
print("Error: \(error)")
}
}
}
I assumed it was a video format problem and the codec of my video wasn't supported.
But, when I bundle the exact same video within the app, and switch to this code, everything works fine:
#IBAction func playVideo(_ sender: UIButton) {
let url = Bundle.main.url(forResource: "myvideo", withExtension: "mp4")!
// if let video = detailItem {
do {
// let url = try FileManager.default.url(for: .documentDirectory,
// in: .userDomainMask,
// appropriateFor: nil,
// create: false).appendingPathComponent(video.uuid)
debugPrint("url: \(url)")
// Create an AVPlayer, passing it the HTTP Live Streaming URL.
let player = AVPlayer(url: url)
// Create a new AVPlayerViewController and pass it a reference to the player.
let controller = AVPlayerViewController()
controller.player = player
// Modally present the player and call the player's play() method when complete.
present(controller, animated: true) {
player.play()
}
} catch {
print("Error: \(error)")
}
// }
}
I have no idea what I am missing here and could get some help. 🙏
EDIT: The code in charge of the download is here:
let downloadTask = URLSession.shared.downloadTask(with: video.downloadURL, completionHandler: { (tempPathURL, urlResponse, error) in
guard let tempPathURL = tempPathURL else {
return
}
do {
let documentsDirectoryURL = try FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false)
try FileManager.default.moveItem(at: tempPathURL, to: documentsDirectoryURL.appendingPathComponent(video.uuid))
} catch {
print("Error: \(error)")
}
})
downloadTask.resume()
You are using the wrong URL for playing downloaded video. Please check your code carefully and notice that you are using the documents directory URL for the player, instead of the actual video.
you should use fileURLWithPath to run video from app files, like this:
func PlayVideo() {
let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let player = AVPlayer(url: URL(fileURLWithPath: docPath).appendingPathComponent("IMG_3039.mp4"))
let controller = AVPlayerViewController()
controller.player = player
self.present(controller, animated: true) {
player.play()
}
}
I am working in an audio player application, and also I am having a offline download option, when the user click the download button it should start download and save it into local. I have saved it using file manager URLSession.
I have tried of taking and separating the destination url. I am using a jukebox third party for playing the song. the sample file location is
file:///var/mobile/Containers/Data/Application/BBB9AF1C-D87C-4C40-9F29-AD89062A20E2/Documents/05-KARMA-YOGA.mp3
if let audioUrl = URL(string: audioTobedownloaded) {
// then lets create your document folder url
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// lets create your destination file url
let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
print(destinationUrl)
the actual thing is how should I play the audio which I have downloaded in file manager.
func findFilesWith(extensionType: String) -> [URL]{
var matches = [URL]()
let fileManager = FileManager.default
let files = fileManager.enumerator(atPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
// *** this section here adds all files with the chosen extension to an array ***
for item in files!
{
let fileURL = item as! URL
if (fileURL.pathExtension == extensionType)
{
matches.append(fileURL)
}
}
return matches
}
You can use this method to get all kinds of file with respective to the extension type.
In your case use mp3 as extension type
Try the below method to play audio from the fetched url
func play(url:URL) {
print("playing \(url)")
do {
let player = try AVAudioPlayer(contentsOf: url)
player.prepareToPlay()
player.volume = 1.0
player.play()
} catch let error as NSError {
print(error.localizedDescription)
} catch {
print("AVAudioPlayer init failed")
}
}
I am trying to play a video form my Server but when I try to do so I get a Crossed mark on pay button.
All other files like .ppt,.keynote etc work fine when I use them with my Server url and use a WKWebview to show them but .mp4 files are not working.
I tried 2 methods.
1) Playing directly using WKWebview.
2) Download the file and saving it in a local path and then using AVPlayer to play the file.
In both cases I get same crossed mark on the play button.
func playVideo(url:String){
var newUrl:String = url
if !( url.hasPrefix("http") || url.hasPrefix("https") ){
let host = kGetHostName()
newUrl = host + newUrl
}
do
{
let videoData = NSData(contentsOf: URL(string: newUrl)!)
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let path = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("myMove.mp4")
if videoData == nil{
print("No data in this")
return
}
videoData?.write(toFile: path.absoluteString, atomically: true)
let playeritem = AVPlayerItem(url: path)
let player = AVPlayer(playerItem: playeritem)
let controller = AVPlayerViewController()
controller.player = player
self.present(controller, animated: true) {
player.play()
}
} catch {
print(error)
}
And when trying with WKWebview
func loadWebView(url:String){
var newUrl:String = url
if !( url.hasPrefix("http") || url.hasPrefix("https") ){
let host = kGetHostName()
newUrl = host + newUrl
}
self.webView.load(URLRequest(url: URL(string: newUrl)!))
}
Both cases fail and get this. Is there any way I can play the video without changing my plist settings as I want to download and play ?
1.Screen Shot
2.Screen Shot
I'm working on a project in swift3 and I have a particular UIViewController to download an mp3 to my filemanager and using that path saved I wants to play an mp3 using AVPlayer. My code doesn't work, I think Im missing something. How would I achieve this?. My code to download the file to the filemanager as below
func downloadSong() {
if let audioUrl = URL(string: "https://www.googleapis.com/download/storage/v1/b/feisty-beacon-159305.appspot.com/o/Aal%20Izz%20Well%20-%20Remix(MyMp3Song).mp3?generation=1490097740630162&alt=media") {
// then lets create your document folder url
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!//since it sys first this may only plays the first item
// destination file url
let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
print("destinationUrl is :",destinationUrl)
// to check if it exists before downloading it
if FileManager.default.fileExists(atPath: destinationUrl.path) {
print("The file already exists at path")
self.dest = destinationUrl.path
// if the file doesn't exist
} else {
// you can use NSURLSession.sharedSession to download the data asynchronously
URLSession.shared.downloadTask(with: audioUrl, completionHandler: { (location, response, error) -> Void in
guard let location = location, error == nil else { return }
do {
// after downloading your file you need to move it to your destination url
try FileManager.default.moveItem(at: location, to: destinationUrl)
print("file path is :",destinationUrl.path)
print("File moved to documents folder")
} catch let error as NSError {
print(error.localizedDescription)
}
}).resume()
}
}
}
And once I save that file, using its file path which is "destinationUrl.path" I initiate my player as bellow in a different UIViewController. As for now I have hardcoded the path I save. The code as bellow.
override func viewDidLoad() {
super.viewDidLoad()
//path I have saved in file manager is set to the url
let url = NSURL.fileURL(withPath:"/Users/auxenta/Library/Developer/CoreSimulator/Devices/F3840294-04AA-46BE-9E46-4342452AFB69/data/Containers/Data/Application/670C0EA1-B375-498E-8847-8707D391D7BF/Documents/Aal Izz Well - Remix(MyMp3Song).mp3") as NSURL
self.playerItem = AVPlayerItem(url: url as URL)
self.player=AVPlayer(playerItem: self.playerItem!)
let playerLayer=AVPlayerLayer(player: self.player!)
playerLayer.frame = CGRect(x: 0, y: 0, width: 10, height: 50) // actually this player layer is not visible
self.view.layer.addSublayer(playerLayer)
}
#IBAction func playBtnPressed(_ sender: Any) {
if player?.rate == 0 // this means if its not playing
{
player!.play()
print("playing")
playbutton.setImage(UIImage(named: "pausebutton"), for: UIControlState.normal)
//trackTime
trackTime()
} else {
// getFileFromFieManager()
print("pause")
player!.pause()
playbutton.setImage(UIImage(named: "playbutton"), for: UIControlState.normal)
}
}
Your problem is the URL set to the AVPlayer. In fact hardcoding a path in iOS doesn't work, it can change at any time.
You need to use code it the same way as you destinationUrl:
if let audioUrl = URL(string: "https://www.googleapis.com/download/storage/v1/b/feisty-beacon-159305.appspot.com/o/Aal%20Izz%20Well%20-%20Remix(MyMp3Song).mp3?generation=1490097740630162&alt=media") {
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!//since it sys first this may only plays the first item
// destination file url
let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
print("destinationUrl is :",destinationUrl)
self.playerItem = AVPlayerItem(url: destinationUrl)
self.player=AVPlayer(playerItem: self.playerItem!)
let playerLayer=AVPlayerLayer(player: self.player!)
.
.
.
}
Normally it should work. Hope it helps.
You can use codes in the below. I hope I could helped you out. First you need to create path for the source file that you wanted to be play
let path = Bundle.main.path(forResource: "yourFileName", ofType: "mp3")
let soundUrl = URL(fileURLWithPath: path!)
do{
try btnSound = AVAudioPlayer(contentsOf: soundUrl)
btnSound.prepareToPlay()
}
catch let err as NSError{
print(err.debugDescription)
}
After you created these in the viewDidLoad method. You can create function for the playing sound like;
func playSound() {
if btnSound.isPlaying {
btnSound.stop()
}
btnSound.play()
}
after all of these you can able to play mp3 files in swift.
I've been working on a small project that involves downloading a video file from a web server, copying said file to the documents directory and then playing it via AVPlayer.
Downloading the file to the documents directory hasn't been an issue. I'm able to download the file and save it without issue. However, when it comes to loading the file into AVPlayer, and in doing that I'm playing it in an instance of AVPlayerViewController, the vide controller pops up as it should, but video doesn't load.
I realize that when testing in the simulator the documents directory changes each time you rebuild the project. Which is why I check to see if the file is present before I play, and though I know the file is present, it still refuses to play.
Here is what my player code looks like:
let fileName = downloadURL.characters.split("/").map(String.init).last as String!
let fileNameHD = downloadURLHD.characters.split("/").map(String.init).last as String!
let downloadFilePath = getDocumentsDirectory() + "/" + "\(fileNameHD)"
let checkValidation = NSFileManager.defaultManager()
if checkValidation.fileExistsAtPath(downloadFilePath){
print("video found")
}
let videoFile = NSURL(string:downloadFilePath)
let player = AVPlayer(URL: videoFile!)
let playerController = AVPlayerViewController()
playerController.player = player
playerController.view.frame = self.view.frame
player.play()
self.presentViewController(playerController, animated: true) {
playerController.player!.play()
}
Every time when we rebuild the application Our Document Directory Path change.
So you can't play the video from the old document directory path. So instead of that you have to save the last path component of your URL. Like your document directory url look like this after downloaded the video on this path:-
let videoURL = "/var/mobile/Containers/Data/Application/1F6CDF42-3796-4153-B1E8-50D09D7F5894/Documents/2019_02_20_16_52_47-video.mp4"
var videoPath = ""
if let url = videoURL {
videoPath = url.lastPathComponent
}
print(videoPath)
// It will print the last path of your video url: - "2019_02_20_16_52_47-video.mp4"
Now save this path either in the Core Database or Sqlite or User Defaults where ever you want. Then if you want to play the video again. So you have to get this path from where you save it.
Note:- In Below function you have to pass the last path component of your video. How to call this function.
func playVideo() {
self.startVideoFrom(videoPath:"2019_02_20_16_52_47-video.mp4")
}
// Play Video from path
func startVideoFrom(videoPath: String) {
let outputMineURL = self.createNewPath(lastPath: videoPath)
let player = AVPlayer(url: outputMineURL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
playerViewController.player!.play()
}
}
/// Generate the new document directory path everytime when you rebuild the app and you have to append the last component of your URL.
func createNewPath(lastPath: String) -> URL {
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let destination = URL(fileURLWithPath: String(format: "%#/%#", documentsDirectory,lastPath))
return destination
}
For more reference, you can see this question:- https://stackoverflow.com/q/47864143/5665836
Try AVPlayer instead of AVPlayerViewController like,
let videoURL = NSURL(string: "your url string")
let player = AVPlayer(URL: videoURL!)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
player.play()
And import AVKit, import AVFoundation.
OR With viewController like this,
let player = AVPlayer(URL: url)
let playerController = AVPlayerViewController()
playerController.player = player
self.addChildViewController(playerController)
self.view.addSubview(playerController.view)
playerController.view.frame = self.view.frame
player.play()
func listVideos() -> [URL] {
let fileManager = FileManager.default
let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
let files = try? fileManager.contentsOfDirectory(
at: documentDirectory,
includingPropertiesForKeys: nil,
options: [.skipsSubdirectoryDescendants, .skipsHiddenFiles]
).filter {
[".mp4", ".mkv"].contains($0.pathExtension.lowercased())
}
return files ?? []
}
And Then Play Video Like this I am only playing first URL
let videosURLs = self.listVideos()
let player = AVPlayer(url: videosURLs[0])
let playerViewController = AVPlayerViewController()
playerViewController.player = player
present(playerViewController, animated: true) { () -> Void in
player.play()
}