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

标签 ios swift avplayer

我正在快速构建我的第一个 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 的新手,仍在学习以提高我的技能。

谢谢,

最佳答案

对于 swift :

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

关于ios - Swift: AVPlayer - 如何从 URL 获取 mp3 文件的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31155003/

相关文章:

ios - Firebase 身份验证链接不起作用 - 缺少尾部斜杠?

ios - 为现有对象添加扩展名的 Swift 文件命名的最佳实践是什么?

ios - 正在显示 View 但打印宽度显示为 0

ios - 通过蓝牙或在 iOS 中的本地 WiFi 网络之间进行点对点语音聊天

ios - 使用 Swift 将数据写入自定义文件夹

ios - 当应用程序快速进入后台时,如何使用 AVLayer 继续将视频作为 VideoView 层播放

swift - 是否可以在 Swift 中进行元编程

ios - 根据 API 的结果选择 Tableview 单元格

iOS : detect the movie aspect ratio

objective-c - 使用 AVPlayer 循环一段视频