How to play mp3 audio from URL in ios swift

后端 未结 9 688
鱼传尺愫
鱼传尺愫 2020-11-30 04:50

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 =          


        
9条回答
  •  囚心锁ツ
    2020-11-30 05:28

    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.

    NSAppTransportSecurity
        
            NSAllowsArbitraryLoads
            
        
    

提交回复
热议问题