AudioPlayer UISlider标签滞后

时间:2019-06-06 10:39:13

标签: ios swift avaudioplayer

我正在创建一个简单的AVAudioPlayer。我在添加UISlider作为查找工具时遇到了麻烦。由于我不知道原因,持续时间滑块下的左侧标签正在“跳过”。它是锯齿状的,无法平滑更新当前的持续时间文本。它链接到滑块/播放音频上的当前内容。我怎样才能解决这个问题?这是设备上发生的事情的屏幕录像:https://imgur.com/a/frpZKV7

func loadRecordingUI() {
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: getFileUrl())
            audioPlayer.delegate = self
            playbackSlider.maximumValue = CFloat(audioPlayer.duration)
            playbackSlider.minimumValue = CFloat(0.0)
            playbackSlider.value = CFloat(0.0)
            audioPlayer.prepareToPlay()

            let time = calculateTimeFromNSTimeInterval(audioPlayer.duration)
            let totalLengthOfAudio = "\(time.minute):\(time.second)"
            playbackTimeLabelEnd.text = totalLengthOfAudio

            playbackTimeLabelFront.text = "00:00"

        } catch let error as NSError {
            print(error.localizedDescription)
        }

    }}

func startTimer(){
    let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.update(_:)), userInfo: nil,repeats: true)
    timer.fire()
}

func stopTimer(){
    timer.invalidate()
}

@objc func update(_ timer: Timer){
    let time = calculateTimeFromNSTimeInterval(audioPlayer.currentTime)
    DispatchQueue.main.async{

        self.playbackTimeLabelFront.text  = "\(time.minute):\(time.second)"
        self.playbackSlider.value = CFloat(self.audioPlayer.currentTime)
    }
}

@IBAction func slide(_ slider: UISlider) {
    audioPlayer.currentTime = TimeInterval(slider.value)
}

func calculateTimeFromNSTimeInterval(_ duration:TimeInterval) ->(minute:String, second:String){
    let minute_ = abs(Int((duration/60).truncatingRemainder(dividingBy: 60)))
    let second_ = abs(Int(duration.truncatingRemainder(dividingBy: 60)))

    // var hour = hour_ > 9 ? "\(hour_)" : "0\(hour_)"
    let minute = minute_ > 9 ? "\(minute_)" : "0\(minute_)"
    let second = second_ > 9 ? "\(second_)" : "0\(second_)"
    return (minute,second)
}

0 个答案:

没有答案