0

In my app where I use AVFoundation I call function showCurrentAudioProgress() using NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "showCurrentAudioProgress", userInfo: nil, repeats: true) in viewDidLoad. I would like to return this kind of time format 00:00:00 but I have a big problem with it. Whole function looks like this:

var musicPlayer = AVAudioPLayer()

func showCurrentAudioProgress() {
    self.totalTimeOfAudio = self.musicPlayer.duration
    self.currentTimeOfAudio = self.musicPlayer.currentTime

    let progressToShow = Float(self.currentTimeOfAudio) / Float(self.totalTimeOfAudio)
    self.audioProgress.progress = progressToShow

    var totalTime = self.musicPlayer.duration
    totalTime -= self.currentTimeOfAudio

    self.currentTimeTimer.text = "\(currentTimeOfAudio)"
    self.AudioDurationTime.text = "\(totalTime)"  
}

how can I convert time which I recive using AVAudioPlayer to 00:00:00?

PiterPan
  • 1,760
  • 2
  • 22
  • 43

2 Answers2

5

You can use NSDateComponentsFormatter .Positional style and zeroFormattingBehavior .Pad to display your time interval as follow:

extension NSTimeInterval {
    struct DateComponents {
        static let formatterPositional: NSDateComponentsFormatter = {
            let formatter = NSDateComponentsFormatter()
            formatter.allowedUnits = [.Hour,.Minute,.Second]
            formatter.unitsStyle = .Positional
            formatter.zeroFormattingBehavior = .Pad
            return formatter
        }()
    }
    var positionalTime: String {
        return DateComponents.formatterPositional.stringFromTimeInterval(self) ?? ""
    }
}

print(120.positionalTime)  // 0:02:00

If you would like to use string format initialiser you can take a look at this answer.

Community
  • 1
  • 1
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
1

The simplest solution will be to get hours, minutes and seconds separately and the combine into one string. To improve you can put it into String category or extension.

let totalTimeOfAudio = 26343 // number of seconds just for an example

let secondsInMinute = 60
let minuteInHour = 60
let secondsInHour = secondsInMinute * minuteInHour

let hours = Float(totalTimeOfAudio / (secondsInHour))
let minutes = Float(totalTimeOfAudio / minuteInHour % minuteInHour)
let seconds = Float(totalTimeOfAudio % secondsInMinute)

let string: NSString = NSString(format: "%02.f:%02.f:%02.f", hours, minutes, seconds)
Dima Cheverda
  • 402
  • 1
  • 4
  • 10