Audio playback progress as UISlider in Swift

前端 未结 4 1044
心在旅途
心在旅途 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:19

    Specifically for Swift I was able to handle it like this:

    1. I set the maximum value of the scrubSlider to the duration of the music file(.mp3) that was loaded in this method

      override func viewDidLoad() {
          super.viewDidLoad()
      
          do {
      
              try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("bach", ofType: "mp3")!))
      
              scrubSlider.maximumValue = Float(player.duration)
      
          } catch {
              //Error
          } 
      
          _ = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(ViewController.updateScrubSlider), userInfo: nil, repeats: true)
      
      }
      
    2. I player was set to play the music at the time set by the value of the scrubber.

      @IBAction func scrub(sender: AnyObject) {
      
          player.currentTime = NSTimeInterval(scrubSlider.value)
      
      }
      

提交回复
热议问题