根据音频播放器当前时间

时间:2017-05-29 23:41:20

标签: swift swift3 avaudioplayer avaudiosession audio-player

我正在尝试根据AudioPlayer当前时间的持续时间进行UILabel更新。我不想使用计时器,因为在我的应用程序中,人们将以较短的持续时间记录自己。半秒很重要,所以我不想使用timer()。相反,我试图做的只是根据当前时间自动进行标签更新。但我似乎无法弄清楚......

以下是我的意思,但显然我没有正确地做到这一点

var audioPlayer : AVAudioPlayer!

    var audioTime = UILabel() {
        didSet {
            do {
                try audioPlayer = AVAudioPlayer(contentsOf: audioURL!)
                let currentTime = Int(audioPlayer.currentTime)
                let minutes = currentTime/60
                let seconds = currentTime - minutes * 60
                audioTime.text = (NSString(format: "%02d:%02d", minutes,seconds) as String)

            } catch {

            }
        }
    }

1 个答案:

答案 0 :(得分:0)

这可能对你有所帮助!将Outlet连接到showTimeLbl并尝试。

class ViewController: UIViewController {

@IBOutlet weak var showTimeLbl: UILabel!
var timeCount:Int = 0
var timer:Timer!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    if(timer != nil)
    {
        timer.invalidate()
    }
    timer = Timer(timeInterval: 1.0, target: self, selector: #selector(ViewController.timerDidFire), userInfo: nil, repeats: true)
    RunLoop.current.add(timer, forMode: RunLoopMode.commonModes)

}

func timerDidFire()
{
    timeCount += 1

    showTimeLbl.text = NSString(format: "%02d:%02d:%02d", timeCount/3600,(timeCount/60)%60,timeCount%60) as String

}
override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(true)
    timer?.invalidate()
    timer = nil
}