Dai Bui
Dai Bui

Reputation: 313

Swift: AVPlayer - How to get length of mp3 file from URL?

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,

Upvotes: 20

Views: 17885

Answers (4)

Waylan Sands
Waylan Sands

Reputation: 375

There are a few ways of solving this. This was mine.

    let item = AVPlayerItem(url: url)
    let duration = Double(item.asset.duration.value) / Double(item.asset.duration.timescale)

This will return your asset's duration in seconds

Upvotes: 2

CodeBender
CodeBender

Reputation: 36610

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.

Upvotes: 11

Jay
Jay

Reputation: 2661

For swift:

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

Upvotes: 29

Chetan Prajapati
Chetan Prajapati

Reputation: 2297

I have made this stuf in iOS and working perfectly.

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

Upvotes: 6

Related Questions