How to stream audio from URL without downloading m

2020-07-14 05:35发布

问题:

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.

回答1:

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()


回答2:

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

    func initPlayer(url : String) {
        guard let url = URL.init(string: url) else { return }
        let playerItem = AVPlayerItem.init(url: url)
        player = AVPlayer.init(playerItem: playerItem)
        playAudioBackground()
    }
    
    func playAudioBackground() {
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, mode: AVAudioSessionModeDefault, 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 background and play any audio video url.



回答3:

I test it with your url and it work

    var player: AVPlayer?
    let url = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3"
    let playerItem = AVPlayerItem( url:NSURL( string:url )! as URL )
    player = AVPlayer(playerItem:playerItem)
    player!.rate = 1.0;

        player!.play()


回答4:

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)
        }
    }
}


回答5:

For online streaming you have to use AVFoundation framework.

var player: AVPlayer!

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

To play:

    player.play()

To pause:

    player.pause()