我正在下载音频文件并将其保存在目录中,但无法播放。 (OSStatus 错误 2003334207。)

Posted

技术标签:

【中文标题】我正在下载音频文件并将其保存在目录中,但无法播放。 (OSStatus 错误 2003334207。)【英文标题】:I am downloading an audio file and saving it in directory but I couldn't play it. (OSStatus error 2003334207.) 【发布时间】:2019-07-17 07:27:12 【问题描述】:

这是我下载的代码

if let audioUrl = URL(string: UrlTextfield.text!) 

        // then lets create your document folder url
                        let documentsDirectoryURL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
//            let documentsDirectoryURL  = URL(fileURLWithPath: Bundle.main.resourcePath!)

        // lets create your destination file url
        let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)

        print(destinationUrl)


        // to check if it exists before downloading it
        if FileManager.default.fileExists(atPath: destinationUrl.path) 
            print("The file already exists at path")

            // if the file doesn't exist
         else 

            // you can use NSURLSession.sharedSession to download the data asynchronously
            URLSession.shared.downloadTask(with: audioUrl)  location, response, error 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: documentsDirectoryURL)

                    print("File moved to documents folder")
                    self.gettingSongNames()

                 catch 
                    print("Error is \(error.localizedDescription)")
                
                .resume()

这里是在tableview单元格中播放的

let audioPath =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let audioPath1 = audioPath.appendingPathComponent(songs[indexPath.row])

        try audioPlayer = AVAudioPlayer(contentsOf: audioPath1)
        audioPlayer.play()

        thisSong = indexPath.row
        audiostaff = true

【问题讨论】:

【参考方案1】:
let audioFileURL = NSURL(fileURLWithPath: destinationUrl.path)


do 
            audioFile = try AVAudioPlayer(contentsOf: audioFileURL as URL )

            audioFile.enableRate = true
            audioFile.prepareToPlay()
            audioFile.play()

         catch let err as NSError 
            print(err.debugDescription)
        

【讨论】:

以上是关于我正在下载音频文件并将其保存在目录中,但无法播放。 (OSStatus 错误 2003334207。)的主要内容,如果未能解决你的问题,请参考以下文章

将音频文件下载到文件管理器需要从本地路径播放

录制音频并保存到文档目录后无法使用 AVAudioPlayer 播放音频文件

如何录制音频并将其保存到沙盒?

iPhone音频流 - 保存状态?

从 mp4 中提取音轨并将其保存到可播放的音频文件中

保存录制的音频 blob [JS]