我正在使用一个名为 AudioManager
的类,您可以找到它作为这个问题的答案 here .
它有委托(delegate)方法 AVAudioPlayerDelegate
作为 AudioManager
类的扩展。
有没有办法在我的 View Controller 中使用它或覆盖这些委托(delegate)方法,以便能够更改我的 UI 中的属性。 这是扩展名:
extension AudioManager: AVAudioPlayerDelegate {
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer,
successfully flag: Bool) {
player.stop()
print("Finish Playing")
}
func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer,
error: Error?) {
print(/error?.localizedDescription)
}
}
这是我的 View Controller 播放按钮代码:
@IBAction func playButtonTapped(_ sender: UIButton) {
if AudioManager.shared.player == nil {
if recordFilePath != nil {
AudioManager.shared.setupPlayer(URL(string:recordFilePath)!)
}
}
if playButtonIsChecked {
playButtonIsChecked = false
AudioManager.shared.player?.play()
playRecordButton.setBackgroundImage(#imageLiteral(resourceName: "pauseProfileButton"), for: .normal)
} else {
playRecordButton.setBackgroundImage(#imageLiteral(resourceName: "editProfilePlay"), for: .normal)
playButtonIsChecked = true
AudioManager.shared.player?.stop()
}
上面的代码很好,当我调用 player?.stop()
时,AVAudioPlayerDelegate
方法是从 AudioManager
类调用的,但是当音频文件结束并在我没有调用 player?.stop
的情况下停止时,按钮背景图像当然不会改变。
我如何在我的 View Controller 中使用这个委托(delegate)方法并知道我的音频文件何时结束和停止。
最佳答案
在您的 AudioManager 类中,您可以实现回调(闭包),例如:
var isAudioStopped: ((Bool) -> Void)?
您可以在您的扩展中调用它,在委托(delegate)方法中:
func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer,
成功标记:Bool) {
player.stop()
isAudioStopped?(true)
print("Finish Playing")
然后在您的 ViewController 方法中:
AudioManager.shared.isAudioStopped = {
[weak self] completion in
// if completion the audio is stopped
}
关于swift - 我如何在另一个类中使用此扩展委托(delegate)更新我的 ViewController UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46856881/