下载音频文件并保存在照片库中,最后播放该音频

时间:2019-07-17 10:41:54

标签: ios swift xcode cocoa-touch avaudioplayer

我想下载音频文件,将其保存在照片库中,然后在下载后播放。但是这段代码不能将视频保存在库中。

是否可以直接从照片库或外部任何其他文件夹中下载。

我的代码来自Swift - Download a video from distant URL and save it in an photo album

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!")
                    }
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

您无法将音频保存在照片库中,可以将其保存在app文件夹中并从此处播放。

示例:

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()
}