如何使用AVFundation以格式00:00:00打印音频时间

时间:2016-02-28 12:22:21

标签: ios iphone swift time avfoundation

在我使用AVFoundation的应用中,我使用showCurrentAudioProgress()中的NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "showCurrentAudioProgress", userInfo: nil, repeats: true)来调用函数viewDidLoad。我想返回这种时间格式00:00:00,但我有一个很大的问题。整个功能看起来像这样:

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)"  
}

如何将使用AVAudioPlayer转发的时间转换为00:00:00?

2 个答案:

答案 0 :(得分:4)

您可以使用NSDateComponentsFormatter .Positional样式和zeroFormattingBehavior .Pad来显示您的时间间隔,如下所示:

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

如果您想使用字符串格式初始化程序,可以查看此answer

答案 1 :(得分:1)

最简单的解决方案是分别将hoursminutesseconds以及合并为一个字符串。要改进,可以将其放入字符串类别或扩展名。

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)