How to play mp3 audio from URL in ios swift

Govind picture Govind · Jan 2, 2016 · Viewed 64.7k times · Source

I am getting mp3 url as a response of api calling. I want to play that audio, so how can i do that? (ios swift)

here is my response

 {
    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";
}

here is my code::

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

}

where am i going wrong?

Answer

technerd picture technerd · Jan 2, 2016

Use AVPlayer instead of AVAudioPlayer to play remote content. As per documentation AVAudioPlayer needs mp3 file to play Audio. AVAudioPlayer not provide support for streaming.

Try this code , its working fine for me

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

    do {

        let playerItem = AVPlayerItem(URL: url)

        self.player = try AVPlayer(playerItem:playerItem)
        player!.volume = 1.0
        player!.play()
    } catch let error as NSError {
        self.player = nil
        print(error.localizedDescription)
    } catch {
        print("AVAudioPlayer init failed")
    }
}

Please keep in mind to set App Transport Security(ATS) in info.plist file.

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>