Search code examples
swiftavfoundationavkit

How to implement a HLS for Radio Live Streaming service in Swift


I am trying to make a radio life streaming service using an AVPlayer.

The url I have is

http://player.absoluteradio.co.uk/tunein.php?i=a664.aac

However AVPlayer does not play it... I am aware that the url does not provide the audio streaming but it returns a playable URL within the first header response. I thought that AVPlayer would either handle the request or would let me intercept the headers but it doesn't.

Does anyone knows how to achieve it?


Solution

  • I have tried to play the url with different approaches but I found out something that made AVPlayer work but still don't know what happens behind the scenes...

    My first approach was to initialise the AVPlayer and set the AVURLAsset resource loader delegate but, since a Reserved/Standard url scheme doesn't trigger the delegate, I was into a dead end...

    Secondly and after implementing the AVPlayer like that:

    class ViewController: UIViewController, AVAssetResourceLoaderDelegate {
    
        let urlFile = URL(string:"http://player.absoluteradio.co.uk/tunein.php?i=a664.aac")!
    
        private var avPlayer:AVPlayer!
        private var avAudioSession:AVAudioSession = AVAudioSession.sharedInstance()
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            try! avAudioSession.setCategory(.playback, mode: .default, options: [])
            try! avAudioSession.setActive(true)
    
            let audioURLAsset = AVURLAsset(url: urlFile)
            //audioURLAsset.resourceLoader.setDelegate(self, queue:DispatchQueue.init(label: "MY QUEUE"))
            avPlayer = AVPlayer(playerItem: AVPlayerItem(asset: audioURLAsset))
    
            avPlayer.play()
    
        }
    
    }
    

    I have allowed Arbitrary loads in my info.plist

    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>
    

    And It worked!