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.
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With