Search code examples
iosswiftuibuttonavfoundation

Unrecognized selector error when tapping on a button to play a sound


When I am trying to play a sound, it gives me an error.

This is the code:

import UIKit
import AVFoundation

class ViewController: UIViewController {
    var player: AVAudioPlayer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    @IBAction func buttonC(_sender: UIButton) {
        playSound()
    }
    
    
    
    func playSound() {
        guard let path = Bundle.main.path(forResource: "C", ofType:"wav") else {
            return }
        let url = URL(fileURLWithPath: path)

        do {
            player = try AVAudioPlayer(contentsOf: url)
            player?.play()
            
        } catch let error {
            print(error.localizedDescription)
        }
    }
    
}

And this is the error:

enter image description here


Solution

  • Probably you have renamed your IBAction method name, now it's different and it's connected to the previous name inside your storyboard. Disconnect your action method and reconnect it appropriately.

    Go to your storyboard, select button and then in connectionInspector (cmd + option + 6) delete your previous connection.

    Then link your button to the @IBAction function correctly.