Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play audio from an http data stream in swift

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?

like image 291
Peza Avatar asked Feb 20 '18 06:02

Peza


2 Answers

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()
like image 182
Adeel Miraj Avatar answered Oct 16 '22 16:10

Adeel Miraj


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

like image 40
Sharad Chauhan Avatar answered Oct 16 '22 15:10

Sharad Chauhan