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

后端 未结 5 574
挽巷
挽巷 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:11

    here you can go

     import AVFoundation
    
    var progressTimer:Timer?
    {
        willSet {
            progressTimer?.invalidate()
        }
    }
    var playerStream: AVPlayer?
    var playerItem: AVPlayerItem?
    
    func playerStream(urlStream : String) {
        if let playerStream = playerStream {
            if playerStream.isPlaying {
                stopProgressTimer()
                playerStream.pause() 
            } else {  
                startProgressTimer()
                playerStream.play()
            }  
        } else {
            if let urlStr = urlStream.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
                if let TempURL = URL.init(string: urlStr) {
                    playerItem = AVPlayerItem(url: TempURL)
                    playerStream = AVPlayer(playerItem: playerItem)
                    NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidPlayToEndTime), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
                } 
            } 
        } 
    }
    
    func playerItemDidPlayToEndTime() {
         stopProgressTimer()
         self.playProgressView.progress = 0.0
         if let playerStream = self.playerStream {
            playerStream.replaceCurrentItem(with: playerItem)
            playerStream.seek(to: kCMTimeZero)
           // playerStream.seek(to: .zero) swift 4.0
        } 
    }
    
    func stopProgressTimer() {
        progressTimer?.invalidate()
        progressTimer = nil
    }
    
    func startProgressTimer() {
        if #available(iOS 10.0, *) {
            progressTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true){ [weak self] in
                self?.updateProgressTimer()
            }
        } else {
            progressTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.updateProgressTimer), userInfo: nil, repeats: true)
        }
    }
    
    @objc func updateProgressTimer() {
        if let playerItem = playerItem {
            if let pa = playerStream {
                let floatTime = Float(CMTimeGetSeconds(pa.currentTime()))
                let floatTimeDu = Float(CMTimeGetSeconds(playerItem.duration))
    
                playProgressView.progress = Double(floatTime / floatTimeDu)
            }
        }
    }
    

提交回复
热议问题