Search code examples
swiftavaudioplayeribactioncancellation

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


I want to create function that if the audio from UIbutton finished playing, the button will disappear.

Is there a function that can set code execution when audio finished playing?

I tried setting queue to make UIbutton disappear with

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

but I found that I can't cancel it when I use a pause button (the button I made for stop audio). when pause the audio midway, DispatchQueue still make UIbutton disappear.

So I am finding a new solution.

Picture

this is my code

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()
        
    }
    
    
}

Solution

  • You can use AVAudioPlayerDelegate's method 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...
        }
    }