我有来自http响应的音频数据流。我使用 URLSessionDataDelegate 方法接收字节数据包:
urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)
我使用AVAudioPlayer
对象及其initWithData:
初始化方法将所有数据包附加到单个Data对象后成功播放了音频。
我真正想做的是在数据仍然进入时启动音频播放 - 流式传输音频。我还没有看到任何对这个用例看起来优雅的答案。
我见过的选项是:
如何从进入的数据包中实现音频流播放?
答案 0 :(得分:1)
根据您的要求考虑AVPlayer,如下所示:
import AVKit
var player: AVPlayer?
func audioPlayer(){
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
player = AVPlayer(url: URL.init(string: "your url")!)
//This is for a player screen, if you don't want to show a player screen you comment this part
let controller = AVPlayerViewController()
controller.player = player
controller.showsPlaybackControls = false
self.addChildViewController(controller)
let screenSize = UIScreen.main.bounds.size
let videoFrame = CGRect(x: 0, y: 130, width: screenSize.width, height: (screenSize.height - 130) / 2)
controller.view.frame = videoFrame
self.view.addSubview(controller.view)
// till here
player?.play()
} catch {
}
}
有关详情,请参阅:https://developer.apple.com/documentation/avfoundation/avplayer
答案 1 :(得分:0)
最简单的方法是使用AVPlayer
AVFoundation
框架。使用您的URL实例化playerItem并将其传递给播放器。以下代码将为您完成。
let urlString = "your url string"
guard let url = URL.init(string: urlString)
else {
return
}
let playerItem = AVPlayerItem.init(url: url)
player = AVPlayer.init(playerItem: playerItem)
player.play()