未触发 audioPlayerDidFinishPlaying

audioPlayerDidFinishPlaying is not triggered

每个谷歌都退出了类似的 OP,但我没有通过关注他们来解决我的问题。看来我已经关闭了,但仍然无法找出错误的地方,感谢这里的任何提示。

我的 AudioPlayer 作为 Singleton 模式放在一个单独的文件中

class AudioPlayer {
    // Singleton to keep audio continue to play when switching viewControllers
    static let shared = AudioPlayer()
    var player: AVAudioPlayer?
    
    private init() {}
    
    func play(url: URL) {
        do {
            player = try AVAudioPlayer(contentsOf: url)
            guard let player = player else { return }
            player.prepareToPlay()
            player.play()
        } catch {
            print(error)
        }
    }
}

然后在PlayerViewController中作为播放场景。我放了player.delegate = self。 并将委托方法放在下面。我调试并发现 audioPlayerDidFinishPlaying 没有被调用。

class PlayerViewController: UIViewController, AVAudioPlayerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        AudioPlayer.shared.player?.delegate = self
    }

    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        if flag {
            print("EAT")
            goNextTrack()
        } else {
            fatalError("the audio doesn't finished playing successfully.")
        }
    }
}

在你调用 play 之前可能是这个

AudioPlayer.shared.player?.delegate = self // here player is nil and delegate won't work 
AudioPlayer.shared.play(url:////)  

不同
AudioPlayer.shared.play(url:////)  
AudioPlayer.shared.player?.delegate = self  // here player has a value  and delegate will work