Audio playback progress as UISlider in Swift

前端 未结 4 1050
心在旅途
心在旅途 2021-01-31 10:28

I\'ve seen some posts about accomplishing this in Objective-C but I\'ve been unable to do the same via Swift.

Specifically, I can\'t figure out how to implement a

4条回答
  •  执念已碎
    2021-01-31 11:33

    Thanks to the suggestion of Dare above, here's how I accomplished this:

    var updater : CADisplayLink! = nil
    
    @IBAction func playAudio(sender: AnyObject) {
        playButton.selected = !(playButton.selected)
        if playButton.selected {
            updater = CADisplayLink(target: self, selector: Selector("trackAudio"))
            updater.frameInterval = 1
            updater.addToRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
            let fileURL = NSURL(string: toPass)
            player = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
            player.numberOfLoops = -1 // play indefinitely
            player.prepareToPlay()
            player.delegate = self
            player.play()
            startTime.text = "\(player.currentTime)"
            theProgressBar.minimumValue = 0
            theProgressBar.maximumValue = 100 // Percentage
        } else {
            player.stop()
        }
    }
    
    func trackAudio() {
        var normalizedTime = Float(player.currentTime * 100.0 / player.duration)
        theProgressBar.value = normalizedTime
    }
    
    @IBAction func cancelClicked(sender: AnyObject) {
        player.stop()
        updater.invalidate()
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    

提交回复
热议问题