【问题标题】:Download audio file and save in Photo Library and finally play that audio下载音频文件并保存在照片库中,最后播放该音频
【发布时间】:2019-11-26 04:17:39
【问题描述】:

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

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

我的代码来自这里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!")
                    }
                }
            }
        }
    }

【问题讨论】:

  • 有什么问题
  • 这个是不是下载我不知道,它存储在哪里,它在照片中不可见。

标签: ios swift xcode cocoa-touch avaudioplayer


【解决方案1】:

你不能把音频保存在照片库里,你可以把它保存在应用文件夹里,然后从这里播放。

示例:

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

【讨论】:

  • 谢谢您,我们可以在外部保存在任何其他文件夹中。有可能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-07
  • 2014-10-26
  • 1970-01-01
  • 1970-01-01
  • 2019-11-02
  • 2014-11-16
相关资源
最近更新 更多