Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stream audio from URL without downloading mp3 file on device

How would I stream audio from a URL in Swift without downloading the mp3 file on the device? What do I need to import? Do I need certain libraries? Add anything to the info.plist? Please comment your code.

like image 454
user8802333 Avatar asked Feb 01 '18 03:02

user8802333


2 Answers

You can use iOS AVPLayer for Streaming audio from url.

var player: AVPlayer!
let url  = URL.init(string:   "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3")

let playerItem: AVPlayerItem = AVPlayerItem(url: url!)
player = AVPlayer(playerItem: playerItem)

let playerLayer = AVPlayerLayer(player: player!)

playerLayer?.frame = CGRect(x: 0, y: 0, width: 10, height: 50)
        self.view.layer.addSublayer(playerLayer!)
player.play()
like image 100
Taimoor Suleman Avatar answered Nov 17 '22 00:11

Taimoor Suleman


class MusicPlayer {
    public static var instance = MusicPlayer()
    var player = AVPlayer()

    func initPlayer(url: String) {
        guard let url = URL(string: url) else { return }
        let playerItem = AVPlayerItem(url: url)
        player = AVPlayer(playerItem: playerItem)
        playAudioBackground()
    }
    
    func playAudioBackground() {
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: AVAudioSession.Mode.default, options: [.mixWithOthers, .allowAirPlay])
            print("Playback OK")
            try AVAudioSession.sharedInstance().setActive(true)
            print("Session is Active")
        } catch {
            print(error)
        }
    }
    
    func pause(){
        player.pause()
    }
    
    func play() {
        player.play()
    }
}

This class will play music in the background and play any audio/video URL.

like image 12
Anil Kumar Avatar answered Nov 16 '22 23:11

Anil Kumar