Home > Back-end >  How to play a sound in Swift 5
How to play a sound in Swift 5

Time:10-25

I am new at swift and Xcode, and When I am trying to play a sound, it gives me an error that I have no idea what is wrong.

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

I will appreciate the help; thanks!

CodePudding user response:

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. I hope it helps you

  • Related