gpt4 book ai didi

ios - `audioPlayerDidFinishPlaying` 未被调用

转载 作者:行者123 更新时间:2023-11-29 05:22:09 25 4
gpt4 key购买 nike

遇到问题 audioPlayerDidFinishPlaying没有被调用...

我查看了其他一些 SO 线程:

Swift: AudioPlayerDidFinished will not be called

AVAudioPlayerDelegate doesn't call the method

...但仍然遇到同样的问题。

我已经设置了我的ViewController符合AVAudioPlayerDelegate :

class ViewController: UIViewController, AVAudioPlayerDelegate {
var audioEngine = AVAudioEngine()
...
}

并在此处创建播放器;创建播放器本身后立即设置委托(delegate):

func startAudioEngine(audioFileURL: URL) {

var player: AVAudioPlayer?

do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)

player = try AVAudioPlayer(contentsOf: audioFileURL, fileTypeHint: AVFileType.mp3.rawValue)

guard let player = player else { return }
player.delegate = self

player.prepareToPlay()
player.play()

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

最佳答案

你的问题是双重的:

  1. var player: AVAudioPlayer? 被声明为 func startAudioEngine() 的本地函数,因此一旦该函数存在,您就会失去对 player 的引用>.
  2. 您正在选择性绑定(bind)的播放器上设置委托(delegate)

更改为此(或类似的内容):

class ViewController: UIViewController, AVAudioPlayerDelegate {
var audioEngine = AVAudioEngine()
var player: AVAudioPlayer?
}

然后在分配 player 后,声明您的委托(delegate) self.player?.delegate = self。确保包含 self.,以便在类属性上设置委托(delegate),而不是在可选绑定(bind)上设置委托(delegate);

关于ios - `audioPlayerDidFinishPlaying` 未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58582280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com