How to play audio from an http data stream in swift
Asked Answered
M

2

7

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?

Magus answered 20/2, 2018 at 6:6 Comment(2)
Have you considered using AVPlayer for that?Hygrophilous
I've looked at one or two examples using AVAssetResouceLoader, but not deeply. I'm open to solutions with AVPlayer, what would that look like?Magus
H
5

The easiest way is to use AVPlayer of AVFoundation framework. Instantiate the playerItem with your URL and pass it the player. Following code will do for you.

    let urlString = "your url string"
    guard let url = URL.init(string: urlString)
        else {
            return
    }
    let playerItem = AVPlayerItem.init(url: url)
    player = AVPlayer.init(playerItem: playerItem)
    player.play()
Hygrophilous answered 20/2, 2018 at 6:34 Comment(0)
M
4

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

Malamut answered 20/2, 2018 at 6:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.