我需要创建音频播放器。我从 url 获取音频,然后从 url 下载音频,然后播放。但是我需要在音频下载时播放音频我该怎么做?
这是我的代码如何从 url 播放它:
func URLSession(session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didFinishDownloadingToURL location: NSURL){
do {
loadingView.hidden=true
actInd.stopAnimating()
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
player=try AVAudioPlayer(contentsOfURL: location)
player?.delegate=self
selectedAudio.status=true
selectedAudio.isDownload=true
player?.enableRate=true
switch speedType_Index {
case 0:
appDelegate.player?.rate=Float(1)
break
case 1:
appDelegate.player?.rate=Float(1.5)
break
case 2:
appDelegate.player?.rate=Float(2)
break
case 3:
appDelegate.player?.rate=Float(0.5)
break
default:
break
}
switch playingType_Index {
case 0:
appDelegate.player?.numberOfLoops = 0
break
case 1:
appDelegate.player?.numberOfLoops = -1
break
default:
break
}
player?.volume=Float(volume)
player?.play()
self.tableView.reloadData()
}catch let error as NSError{
print(error.localizedDescription)
}
}
func URLSession(session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64){
let progress=Float(totalBytesWritten) / Float(totalBytesExpectedToWrite);
bite.text=String(format: "%.1f%%",progress * 100)
}
Run Code Online (Sandbox Code Playgroud)
AVAudioPlayer 不能 - 立即 - 从远程 URL 流式传输内容。
正如它在AVAudioPlayer的文档中所说
Apple 建议您使用此类进行音频播放,除非您正在播放从网络流捕获的音频或需要非常低的 I/O 延迟。
你可以做什么,如果你想从远程URL到流,是使用AVPlayer代替AVAudioPlayer。文档可以在这里找到
要创建能够进行流式传输的播放器,您需要按照这些方式做一些事情。
var player = AVPlayer() //declared as a property on your class
if let url = NSURL(string: "https://archive.org/download/testmp3testfile/mpthreetest.mp3") {
player = AVPlayer(URL: url)
player.volume = 1.0
player.play()
}
Run Code Online (Sandbox Code Playgroud)
希望能帮到你。
| 归档时间: |
|
| 查看次数: |
4089 次 |
| 最近记录: |