Swift: 如何设置音频播放完毕后执行代码?

Swift: How to set code excecution when audio finished playing?

我想创建一个功能,如果来自 UIbutton 的音频播放完毕,按钮就会消失。

有没有设置音频播放完后执行代码的功能?

我尝试设置队列以使 UIbutton 消失

DispatchQueue.main.asyncAfter(deadline: .now() + (audio duration)) {sender.alpha = 0} 

但我发现当我使用暂停按钮(我为停止音频制作的按钮)时无法取消它。 中途暂停音频时,DispatchQueue 仍然使 UIbutton 消失。

所以我正在寻找新的解决方案。

Picture

这是我的代码

import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    var player: AVAudioPlayer!
    
    @IBOutlet var buttons: [UIButton]!
    
    @IBOutlet weak var button: UIButton!
    @IBOutlet weak var pause: UIButton!
    
    @IBOutlet weak var mainStackView: UIStackView!
    
    @IBOutlet weak var pirateBoy: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        pause.alpha = 0
        
    }
    
    //multiplication table action button
    @IBAction func buttonPressed(_ sender: UIButton) {
        
        playSound(soundName: sender.currentTitle!)
        
        pause.alpha = 1 
        
    }
    
    //pause action button
    @IBAction func pausePressed(_ sender: UIButton) {
        
        player.stop()
        
        pause.alpha = 0
        
    }
    
    func playSound(soundName: String) {
        let url = Bundle.main.url(forResource: soundName, withExtension: "m4a")
        player = try! AVAudioPlayer(contentsOf: url!)
        player.play()
        
    }
    
    
}

你可以使用AVAudioPlayerDelegate's方法audioPlayerDidFinishPlaying(_:successfully:),

Called when a sound has finished playing.

class ViewController: UIViewController, AVAudioPlayerDelegate {
    //rest of the code...
    
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        //write your code to hide the button here...
    }
}