How to play audio from an http data stream in swift

Peza picture Peza · Feb 20, 2018 · Viewed 10.7k times · Source

I have an audio data stream coming in from a http response. I receive packets of bytes using the URLSessionDataDelegate method:

urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)

I have successfully played the audio after appending all the data packets into a single Data object, using an AVAudioPlayer object and it's initWithData: initializer method.

What I really want to do is start audio playback while data is still coming in - streaming audio effectively. I haven't seen any answers that seem elegant for this use-case.

Options I've seen are:

  1. Using the AudioToolbox: Audio File Stream Services & Audio Queues
  2. Using the NSStream API, writing to a file and playing audio from that file concurrently

How would I achieve audio streaming playback from the Data packets coming in?

Answer

Sharad Chauhan picture Sharad Chauhan · Feb 20, 2018

Consider AVPlayer for your requirement, something like this :

import AVKit
var player: AVPlayer?
func audioPlayer() {
    do {
         try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
         player = AVPlayer(url: URL.init(string: "your url")!)

          //This is for a player screen, if you don't want to show a player screen you comment this part

          let controller = AVPlayerViewController()
          controller.player = player
          controller.showsPlaybackControls = false
          self.addChildViewController(controller)
          let screenSize = UIScreen.main.bounds.size
          let videoFrame = CGRect(x: 0, y: 130, width: screenSize.width, height: (screenSize.height - 130) / 2)
          controller.view.frame = videoFrame
          self.view.addSubview(controller.view)
          // till here

          player?.play()
        } catch {
        }
}

For more please read this : https://developer.apple.com/documentation/avfoundation/avplayer