How to play mp3 audio from URL in ios swift

后端 未结 9 682
鱼传尺愫
鱼传尺愫 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:27

    Since AVPlayer is very limited (for example you cannot change url there without regenerate whole AVPlayer I think you should use AVQueuePlayer:

    From the docs:

    AVQueuePlayer is a subclass of AVPlayer used to play a number of items in sequence. Using this class you can create and manage a queue of player items comprised of local or progressively downloaded file-based media, such as QuickTime movies or MP3 audio files, as well as media served using HTTP Live Streaming.

    So in Swift 3 it will work like this:

    lazy var playerQueue : AVQueuePlayer = {
        return AVQueuePlayer()
    }()
    

    ...

    func playTrackOrPlaylist{
        if let url = track.streamURL() { //this is an URL fetch from somewhere. In this if you make sure that URL is valid
            let playerItem = AVPlayerItem.init(url: url)
            self.playerQueue.insert(playerItem, after: nil)
            self.playerQueue.play()
        }
    }
    

提交回复
热议问题