【问题标题】:AVAudioPlayer pause() not behaving as expectedAVAudioPlayer pause() 未按预期运行
【发布时间】:2023-04-07 05:05:01
【问题描述】:

我在 AVAudioPlayer 的 pause() 函数中看到了这种意外行为。当我单击“暂停”按钮时,音频实际上应该在当前时间暂停,并在调用 play() 时从它恢复。但是在这里,当我点击 pause() 时,音频暂停,当我点击 play() 时,音频从头开始播放。 pause() 的行为类似于 stop()。

var player: AVAudioPlayer = AVAudioPlayer()

@IBAction func PlayPauseAudioButton(_ sender: UIButton) {
    if sender.currentImage == #imageLiteral(resourceName: "play-btn") {
        sender.setImage(#imageLiteral(resourceName: "pause-btn"), for: .normal)

        do {
            let audioPath = Bundle.main.path(forResource: "aug-ps-raj", ofType: "mp3")
            try player = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath: audioPath!) as URL)
        } catch {
            // Catch the error
        }
        player.play()

    } else {
        sender.setImage(#imageLiteral(resourceName: "play-btn"), for: .normal)
        player.pause()

    }
}

【问题讨论】:

    标签: ios swift avfoundation


    【解决方案1】:

    问题是每次点击播放按钮时都会创建一个新的播放器实例。相反,您可以提前创建 AVAudioPlayer 实例,并且只在您的按钮单击处理程序中调用 play() 和 pause()。

    【讨论】:

      猜你喜欢
      • 2014-11-12
      • 1970-01-01
      • 2020-06-28
      • 2012-02-18
      • 2018-01-18
      • 2012-06-14
      • 2019-03-03
      • 2012-09-21
      • 2014-07-19
      相关资源
      最近更新 更多