AVAudioPlayer UISlider和播放元素

时间:2019-06-04 12:22:43

标签: ios swift

我想创建一个简单的AVAudioPlayer元素,但不确定要解决的问题。我正在制作一个UISlider和2个标签,它们全部对应于AVAudioPlayer

示例:enter image description here

我在尝试正确实现滑块和标签updateTimeFunction时遇到了很多麻烦?我已经尽力了...我该怎么做? :)

@IBOutlet weak var playbackSlider: UISlider!
@IBOutlet weak var playbackTimeLabelFront: UILabel!
@IBOutlet weak var playbackTimeLabelBack: UILabel!

var timer: Timer!
var isPlaying = false

var audioRecorder: AVAudioRecorder!
var audioPlayer : AVAudioPlayer!
var recordingSession: AVAudioSession!

func loadRecordingUI() {
    do {
        audioPlayer = try AVAudioPlayer(contentsOf: getFileUrl())
        audioPlayer!.delegate = self
        audioPlayer!.prepareToPlay()
    } catch {
        print("audioPlayer error: \(error.localizedDescription)")
    }
}
print("Audio Success")
}

@IBAction func playTapped(_ sender: Any) {
    if isPlaying {
        audioPlayer!.pause()
        isPlaying = false
    } else {
        audioPlayer!.play()
        isPlaying = true
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
    }

}

@objc func updateTime() {
    let currentTime = Int(audioPlayer.currentTime)
    let minutes = currentTime/60
    let seconds = currentTime - minutes * 60
    playbackTimeLabelFront.text = ??
}

1 个答案:

答案 0 :(得分:0)

这是工作代码

@IBOutlet weak var slider: UISlider!
@IBOutlet weak var lblTotalDuration: UILabel!
@IBOutlet weak var lblCurrentDuration: UILabel!

var timer:Timer!
var audioPlayer: AVAudioPlayer!

  // Pass your Audiofile path here
  func prepareAudio(path:String) {

        let mp3URL = NSURL(string: path)
        do {

            do {
                try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            } catch _ { }
            do {
                try AVAudioSession.sharedInstance().setActive(true)
            } catch _ { }

            audioPlayer = try AVAudioPlayer(contentsOf: mp3URL as! URL)
            audioPlayer.delegate = self
            slider.maximumValue = CFloat(audioPlayer.duration)
            slider.minimumValue = CFloat(0.0)
            slider.value = CFloat(0.0)
            audioPlayer.prepareToPlay()

            // Total Audio Duration
            let time = calculateTimeFromNSTimeInterval(audioPlayer.duration)
            totalLengthOfAudio = "\(time.minute):\(time.second)"
            lblTotalDuration.text = totalLengthOfAudio

            lblCurrentDuration.text = "00:00"

            audioPlayer.play()
            startTimer()

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

计时器和更新标签

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

func stopTimer(){
    timer.invalidate()
}

func update(_ timer: Timer){
    if !audioPlayer.isPlaying{
        return
    }
    let time = calculateTimeFromNSTimeInterval(audioPlayer.currentTime)
    DispatchQueue.main.async{

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

计算歌曲长度

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)
}