在Swift 3中将AVAudioPlayer与动态URL结合使用会导致线程错误 [英] Using AVAudioPlayer with Dynamic URL in Swift 3 causing Thread Errors

查看:107
本文介绍了在Swift 3中将AVAudioPlayer与动态URL结合使用会导致线程错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Swift的新手,正在使用AVAudioPlayer制作音频应用.我正在使用远程URL mp3文件作为音频,并且在静态时可以使用.

I am new to Swift and making an audio app using AVAudioPlayer. I am using a remote URL mp3 file for the audio, and this works when it's static.

对于我的用例,我想从JSON数组中提取mp3文件的URL,然后将其传递到AVAudioPlayer来运行.

For my use case, I want to pull a URL for an mp3 file from a JSON array and then pass it into the AVAudioPlayer to run.

  1. 如果我将AVAudioPlayer块移到ViewDidLoad并将mp3文件设置为静态URL,它将运行良好.

  1. If I move the AVAudioPlayer block into the ViewDidLoad and make the mp3 file a static URL, it will run fine.

然后,当我将此代码移到从JSON中提取mp3网址的代码块中时,我可以成功地print网址.但是,当我将其传递给音频播放器时,就会出现问题.这是代码.

Then, when I move this code into my block that extracts an mp3 url from JSON, I can print the URL successfully. But when I pass it into my audio player, problems arise. Here's the code.

override func viewDidLoad() {
super.viewDidLoad()

    let url = URL(string: "http://www.example.com/example.json")
        URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
            guard let data = data, error == nil else { return }

            let json: Any?
            do{
                json = try JSONSerialization.jsonObject(with: data, options: [])
            }
            catch{
                return
            }

            guard let data_list = json as? [[String:Any]] else {
                return
            }
            if let foo = data_list.first(where: {$0["episode"] as? String == "Example Preview"}) {

                self.audiotest = (foo["audio"] as? String)!
                print(self.audiotest) // this prints 

                // where i'm passing it into the audio player
                if let audioUrl = URL(string: self.audiotest) {

                    // 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)

                    //let url = Bundle.main.url(forResource: destinationUrl, withExtension: "mp3")!

                    do {
                        audioPlayer = try AVAudioPlayer(contentsOf: destinationUrl)

                    } catch let error {
                        print(error.localizedDescription)
                    }
                } // end player

// ....

具体地说,单击连接到音频播放器的播放按钮IBAction时出现错误Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value.最后,该动作函数如下所示:

Specifically, I get an error Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value when clicking a play button IBAction that is connected to the audio player. Finally, that action function looks like this:

  @IBAction func playPod(_ sender: Any) {
    audioPlayer.play() 
}

您知道我要去哪里了吗?我对于为什么我不能打印URL并在同一块中得到URL为零的响应感到困惑,但这也许是异步的.

Do you know where I'm going wrong? I'm confused as to why I can't print the URL and also get a response that the URL is nil in the same block, but maybe that's an asynchronous thing.

推荐答案

问题是您没有将mp3文件保存到文档中并尝试播放

The problem is that you didn't save the mp3 file to documents and trying to play it

此行

    audioPlayer = try AVAudioPlayer(contentsOf: destinationUrl)

假设该路径中存在一个已保存的mp3文件,但实际上没有任何文件是您在运行中即时添加音频扩展名的

assumes that there is a saved mp3 file in that path , but acutally there is no files you appended the audio extension on the fly

除了用于从远程服务器传输音频外,请使用 AVPlayer 代替AVAudioPLayer. AVPlayer文档

besides for steaming audio from a remote server, use AVPlayer instead of AVAudioPLayer. AVPlayer Documentation

还可以尝试使用从json解析的网址

Also try this with urls parsed from json

  var urlStr = (foo["audio"] as? String)!

  self.audiotest = urlStr.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

这篇关于在Swift 3中将AVAudioPlayer与动态URL结合使用会导致线程错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆