Search code examples
iosswift3avaudioplayeraudio-streaming

Which Native iOS API can be used to stream and play audio data in my application?


I'm interested in building a iOS application similar to wynk.The app will be having a list of songs. On clicking any option, it will start streaming that music file from the server. I don't want to use any third Party API. Any help/ suggestion will be of great help. I'm using xCode 8.0 with swift 3.


Solution

  • Apple provides HTTP Live Streaming (HLS) for audio/video streaming: https://developer.apple.com/streaming/,

    At the start of the streaming session, the client downloads a master .m3u8 playlist file containing the metadata for the various sub-streams which are available. Then decides what to download from the media files available, based on predefined factors such as device type, resolution, data rate, size, etc.

    Apple provides sample code on how to play and persist HTTP Live Streams hosted on remote servers: https://developer.apple.com/library/content/samplecode/HLSCatalog/Listings/HLSCatalog_AssetListTableViewCell_swift.html#//apple_ref/doc/uid/TP40017320-HLSCatalog_AssetListTableViewCell_swift-DontLinkElementID_4

    also check this answer on HLS here, you'll get the whole picture: HTTP LIve Streaming

    AVFoundation for playback https://developer.apple.com/av-foundation/

    import AVFoundation
    import UIKit
    
    class ViewController: UIViewController {
    
        override func viewDidAppear(animated: Bool) {
            let videoURL = NSURL(string: "your_video_url")
            guard let player = AVPlayer(URL: videoURL) else { return }
            let playerLayer = AVPlayerLayer(player: player)
            playerLayer.frame = self.view.bounds
            self.view.layer.addSublayer(playerLayer)
            player.play()
        }
    }