Ios 如何从URL获取mp3文件的长度?

Ios 如何从URL获取mp3文件的长度?,ios,swift,avplayer,Ios,Swift,Avplayer,我正在用swift构建我的第一个IOS应用程序,我陷入了一个问题:流媒体播放时如何获取音乐文件的长度(持续时间) 我做了很多研究,也写了一些代码来解决这个问题,但我的代码似乎不够好 func prepareAudio() { audioLength = CMTimeGetSeconds(self.player.currentItem.asset.duration) playerProgressSlider.maximumValue = CFloat(CMTimeGetSeco

我正在用swift构建我的第一个IOS应用程序,我陷入了一个问题:流媒体播放时如何获取音乐文件的长度(持续时间)

我做了很多研究,也写了一些代码来解决这个问题,但我的代码似乎不够好

 func prepareAudio() {
    audioLength = CMTimeGetSeconds(self.player.currentItem.asset.duration) 
    playerProgressSlider.maximumValue = CFloat(CMTimeGetSeconds(player.currentItem.duration))
    playerProgressSlider.minimumValue = 0.0
    playerProgressSlider.value = 0.0
    showTotalSurahLength()
} // i prepare for get the duration and apply to UISlider here

func showTotalSurahLength(){
    calculateSurahLength()
    totalLengthOfAudioLabel.text = totalLengthOfAudio
} // get the right total length of audio file


func calculateSurahLength(){
    var hour_ = abs(Int(audioLength/3600))
    var minute_ = abs(Int((audioLength/60) % 60))
    var second_ = abs(Int(audioLength % 60))

    var hour = hour_ > 9 ? "\(hour_)" : "0\(hour_)"
    var minute = minute_ > 9 ? "\(minute_)" : "0\(minute_)"
    var second = second_ > 9 ? "\(second_)" : "0\(second_)"
    totalLengthOfAudio = "\(hour):\(minute):\(second)"
} // I calculate the time and cover it
这里有谁遇到过这个问题,你能给我一些建议来解决它吗?我对Swift非常陌生,仍然在学习提高我的技能


谢谢,

我已经在iOS中制作了这个stuf,并且工作得非常好

AVURLAsset* audioAsset = [AVURLAsset URLAssetWithURL:audioUrl options:nil];
CMTime audioDuration = audioAsset.duration;
float audioDurationSeconds = CMTimeGetSeconds(audioDuration);
对于swift:

let asset = AVURLAsset(URL: NSURL(fileURLWithPath: pathString), options: nil)
let audioDuration = asset.duration
let audioDurationSeconds = CMTimeGetSeconds(audioDuration)

以下函数适用于Swift 3.0,并将返回一个包含目标文件持续时间的双精度值

func duration(for resource: String) -> Double {
    let asset = AVURLAsset(url: URL(fileURLWithPath: resource))
    return Double(CMTimeGetSeconds(asset.duration))
}

这将采用
资源
参数,该参数由音频文件的文件路径的
字符串组成,然后将值从
浮点64
转换为
双精度
有几种解决方法。这是我的

    let item = AVPlayerItem(url: url)
    let duration = Double(item.asset.duration.value) / Double(item.asset.duration.timescale)

这将以秒为单位返回资产的持续时间

Hi,如果互联网连接缓慢,则停止整个应用程序,如果没有互联网连接,则返回0.0。那么,有什么方法可以在街区内完成吗?当资源可用时,它是否会触发任何通知?