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

20

我正在使用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方面很新,还在学习提高我的技能。

谢谢!

4个回答

29

针对Swift:

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

1
嗨,如果网络连接缓慢,整个应用程序就会停止运行,如果没有网络连接,则返回0.0。那么有没有办法以块的形式执行此操作?并且当资源可用时是否会触发任何通知? - souvickcse

11
以下函数适用于Swift 3.0,将返回一个包含目标文件持续时间的Double值。
func duration(for resource: String) -> Double {
    let asset = AVURLAsset(url: URL(fileURLWithPath: resource))
    return Double(CMTimeGetSeconds(asset.duration))
}

这将使用resource参数,其由音频文件的文件路径String组成,然后将该值从Float64转换为Double


6

我已经在iOS上完成了这个东西,并且它完美地运行。

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

3
这个问题有几种解决方法,这是我的一种解决方案。
    let item = AVPlayerItem(url: url)
    let duration = Double(item.asset.duration.value) / Double(item.asset.duration.timescale)

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接