我正在使用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中非常新,并且仍然学会提高我的技能。
谢谢,
答案 0 :(得分:20)
对于swift:
let asset = AVURLAsset(URL: NSURL(fileURLWithPath: pathString), options: nil)
let audioDuration = asset.duration
let audioDurationSeconds = CMTimeGetSeconds(audioDuration)
答案 1 :(得分:5)
我已经在iOS中制作了这个stuf并且工作得很好。
AVURLAsset* audioAsset = [AVURLAsset URLAssetWithURL:audioUrl options:nil];
CMTime audioDuration = audioAsset.duration;
float audioDurationSeconds = CMTimeGetSeconds(audioDuration);
答案 2 :(得分:5)
以下函数适用于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
。
答案 3 :(得分:3)
有几种解决方法。这是我的。
let item = AVPlayerItem(url: url)
let duration = Double(item.asset.duration.value) / Double(item.asset.duration.timescale)
这将以秒为单位返回资产的持续时间
答案 4 :(得分:1)
您还可以从AVPlayerItem
let item = AVPlayerItem(url: URL(string: "myURL.com")!)
let player = AVPlayer(playerItem: item)
let duration = player.currentItem?.duration.seconds
我通常使用以下方法进行检查:
guard let duration = player.currentItem?.duration.seconds else { return }