SilentK SilentK - 2 months ago 21
Swift Question

Audio duration returns 0.0

Im trying to get the duration of the audio i've recorded using AVAudioRecorder (.m4a format) but the following code prints out "0.0" :

let asset = AVURLAsset(URL: myAudioFileURL)
let audioDuration = asset.duration
print(Float(CMTimeGetSeconds(audioDuration)))


What am i doing wrong?
Thanks

Answer
do
    {
        let avAudioPlayer = try AVAudioPlayer (contentsOfURL:recordedAudioURL)
        duration = avAudioPlayer.duration
        let ms  = Int((duration%1)*1000)
        let sec = Int(duration%60)
        let minutes = Int(duration / 60) % 60
        let hours = Int(duration / 3600)
        recordedAudioDuration.text = (NSString(format: "Dur: %0.2d:%0.2d:%0.2d.%0.3d",hours,minutes,sec,ms)) as String
    }
    catch{
        print(error)
    }