I'm process to build my first IOS app in swift and i get stuck in the question: How to get length (duration) of a music file when streaming ?
I did research a lot and also write some line of codes for solve this problem but seem my code is not good enough.
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
Anyone here who ever stuck with this problem, could you give me some suggests for fix it ? I'm very new in Swift and still learn to improve my skill.
Thanks,
For swift:
let asset = AVURLAsset(URL: NSURL(fileURLWithPath: pathString), options: nil)
let audioDuration = asset.duration
let audioDurationSeconds = CMTimeGetSeconds(audioDuration)
The following function works with Swift 3.0 and will return a Double value containing the duration of the target file.
func duration(for resource: String) -> Double {
let asset = AVURLAsset(url: URL(fileURLWithPath: resource))
return Double(CMTimeGetSeconds(asset.duration))
}
This will take the resource
parameter, consisting of a String
for the filepath of the audio file, and then convert the value from a Float64
to a Double
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With