Download audio file and save in Photo Library and finally play that audio
我想下载音频文件,将其保存在照片库中,然后在下载后播放。但是此代码未将视频保存在库中。
是否可以直接从照片库或外部任何其他文件夹中下载。
我的代码来自这里Swift-从遥远的URL下载视频并将其保存在相册中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | DispatchQueue.global(qos: .background).async { if let url = URL(string: self.audioURL!), let urlData = NSData(contentsOf: url) { let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]; let filePath="\\(documentsPath)/tempFile.mp3" print(filePath) DispatchQueue.main.async { urlData.write(toFile: filePath, atomically: true) PHPhotoLibrary.shared().performChanges({ PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(fileURLWithPath: filePath)) }) { completed, error in if completed { print("Video is saved!") } } } } } |
您无法将音频保存在照片库中,可以将其保存在app文件夹中并从此处播放。
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | func saveAudioFile(url:URL){ let docUrl: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL! let desURL = docUrl.appendingPathComponent("song.m4a") var task: URLSessionDownloadTask = URLSession.shared.downloadTask(with: url, completionHandler: { [weak self] (URLData, response, error) -> Void in do { let isFileExists: Bool? = FileManager.default.fileExists(atPath: desURL.path) if isFileExists == true{ print(desURL) } else { try FileManager.default.copyItem(at: URLData!, to: desURL) } } catch let error { print(error.localizedDescription) } }) task.resume() } |