2017-05-29 116 views
0

我试图根据AudioPlayer当前时间的持续时间进行我的UILabel更新。我不想使用计时器,因为在我的应用程序中,人们会以很短的时间录制自己,半秒钟很重要,所以我不想使用计时器()。相反,我试图做的只是基于当前时间自动进行标签更新。我不能然而似乎看着办吧......根据音频播放器当前时间进行UILabel更新

这里是我会如何吧,但显然我没有做正确

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 { 

      } 
     } 
    } 

回答

0

这可以帮助你!连接插座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 
}