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

后端 未结 5 579
挽巷
挽巷 2021-02-09 21:18

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.plis

5条回答
  •  心在旅途
    2021-02-09 22:12

    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.

提交回复
热议问题