一尘不染

如何在iOS Swift中从URL播放MP3音频

swift

我收到mp3网址作为api调用的响应。我想播放该音频,那么我该怎么做?(iOS迅速)

这是我的回应

 {
    content = "En este primer programa se tratar\U00e1n asuntos tan importante como este y aquel sin descuidar un poco de todo lo dem\U00e1s";
    file = "http://radio.spainmedia.es/wp-content/uploads/2015/12/ogilvy.mp3";
    image = "http://radio.spainmedia.es/wp-content/uploads/2015/12/tapas.jpg";
    number = 0001;
    subtitle = Titulareando;
    title = "Tapa 1";
}

这是我的代码::

 @IBAction func btnplayaudio(sender: AnyObject) {
    let urlstring = "http://radio.spainmedia.es/wp-content/uploads/2015/12/tailtoddle_lo4.mp3"
    let url = NSURL(string: urlstring)
    print("the url = \(url!)")

    play(url!)

}

func play(url:NSURL) {
    print("playing \(url)")

    do {
        self.player = try AVAudioPlayer(contentsOfURL: url)
        player.prepareToPlay()
        player.volume = 1.0
        player.play()
    } catch let error as NSError {
        self.player = nil
        print(error.localizedDescription)
    } catch {
        print("AVAudioPlayer init failed")
    }

}

我要去哪里错了?


阅读 637

收藏
2020-07-07

共1个答案

一尘不染

我尝试了以下方法

    let urlstring = "http://radio.spainmedia.es/wp-content/uploads/2015/12/tailtoddle_lo4.mp3"
    let url = NSURL(string: urlstring)
    print("the url = \(url!)")
    downloadFileFromURL(url!)

添加以下方法,

func downloadFileFromURL(url:NSURL){

    var downloadTask:NSURLSessionDownloadTask
    downloadTask = NSURLSession.sharedSession().downloadTaskWithURL(url, completionHandler: { [weak self](URL, response, error) -> Void in
        self?.play(URL)
    })

    downloadTask.resume()

}

和您的播放方法一样,

func play(url:NSURL) {
    print("playing \(url)")

    do {
        self.player = try AVAudioPlayer(contentsOfURL: url)
        player.prepareToPlay()
        player.volume = 1.0
        player.play()
    } catch let error as NSError {
        //self.player = nil
        print(error.localizedDescription)
    } catch {
        print("AVAudioPlayer init failed")
    }

}

下载mp3文件,然后尝试播放,但AVAudioPlayer无法以某种方式为您下载mp3文件。我可以下载音频文件,然后播放器播放它。

请记住,将其添加到info.plist中,因为您是从 http* 源加载的,并且需要为 iOS 9+ 设置以下内容 *

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
</plist>
2020-07-07