xcode 如何在不下载设备上的 mp3 文件的情况下从 URL 流式传输音频

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48555049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 10:32:03  来源:igfitidea点击:

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

iosswiftxcodeurlaudio

提问by user8802333

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.

如何在 Swift 中从 URL 流式传输音频而不在设备上下载 mp3 文件?我需要导入什么?我需要某些图书馆吗?在 info.plist 中添加任何内容?请评论您的代码。

回答by Taimoor Suleman

You can use iOS AVPLayer for Streaming audio from url.

您可以使用 iOS AVPlayer 从 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()

回答by Anil Kumar

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.

这个类将在后台播放音乐并播放任何音频视频 url。

回答by masoud

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

回答by Inder Jagdeo

For online streaming you have to use AVFoundation framework.

对于在线流媒体,您必须使用 AVFoundation 框架。

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

回答by m.alqadi

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