AVAudioPlayerDelegate swift 没有调用该方法

AVAudioPlayerDelegate swift doesn't call the method

Swift 和 Xcode 上的新功能 - 尝试实现一个简单的 AVAudioPlayerDelegate - 但它不会触发 AudioPlayerDidFinishPlaying 方法 - 我查看了所有其他打开的线程,但我没有找到答案适合我的问题,因为一切似乎都很好。有人吗?

import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    var player = AVAudioPlayer()

    override func viewDidLoad() {
         super.viewDidLoad()
         player.delegate = self
     }
    
    @IBAction func keyPressed(_ sender: UIButton) {
        
        sender.alpha = 0.5
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            sender.alpha = 1
        }
        
        let buttonPressed:String = sender.currentTitle!
        playSound(buttonPressed:  buttonPressed)
    }
    
    func playSound(buttonPressed: String) {
        let url = Bundle.main.url(forResource: buttonPressed, withExtension: "wav")
        player = try! AVAudioPlayer(contentsOf: url!)
        player.play()
                
    }
    
  
}

//MARK: - AVAudioPlayerDelegate

extension ViewController: AVAudioPlayerDelegate {
    
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        
        print("completed")
        
    }
    
    func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
        print(error!)
    }
    
}

 

因为你在view didload中设置delegate后新建了一个AVAudioPlayer实例,应该是这样的

func playSound(buttonPressed: String) {
        let url = Bundle.main.url(forResource: buttonPressed, withExtension: "wav")
        player = try! AVAudioPlayer(contentsOf: URL!)
        player.delegate = self
        player.play()
                
    }