maxo77
maxo77

Reputation: 15

AVAudioPlayerDelegate swift doesn't call the method

New on Swift and Xcode - trying to implement a simple AVAudioPlayerDelegate - but it doesn't trigger the method AudioPlayerDidFinishPlaying - i looked into all the others open thread but i found no answer that fits my issue because everything seems fine. Anyone?

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

 

Upvotes: 1

Views: 174

Answers (1)

aiwiguna
aiwiguna

Reputation: 2922

it because you create a new AVAudioPlayer instance after you set delegate in view didload, it should be like this

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

Upvotes: 2

Related Questions