Swift:AVPlayer - 如何从URL获取mp3文件的长度?

Dai*_*Bui 16 ios avplayer swift

我正在使用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
Run Code Online (Sandbox Code Playgroud)

在这里遇到过这个问题的人,你能不能给我一些建议来解决它?我是斯威夫特的新手,仍然学会提高我的技能.

谢谢,

Jay*_*Jay 21

对于swift:

let asset = AVURLAsset(URL: NSURL(fileURLWithPath: pathString), options: nil)
let audioDuration = asset.duration
let audioDurationSeconds = CMTimeGetSeconds(audioDuration)
Run Code Online (Sandbox Code Playgroud)


Che*_*ati 5

我在iOS上做了这个stuf并且工作得很好.

AVURLAsset* audioAsset = [AVURLAsset URLAssetWithURL:audioUrl options:nil];
CMTime audioDuration = audioAsset.duration;
float audioDurationSeconds = CMTimeGetSeconds(audioDuration);
Run Code Online (Sandbox Code Playgroud)


Cod*_*der 5

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

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

这将采用resourceString音频文件的文件路径的a组成的参数,然后将值从a转换Float64为a Double