Swift 3 sound play

shane picture shane · Nov 15, 2016 · Viewed 28.5k times · Source

Ok I have looked into this and have tried many different ways to play a sound when a button is clicked.

How would I play a sound when a button is clicked in swift 3? I have my sound in a folder named Sounds and the name is ClickSound.mp3

Answer

Amit Rawat picture Amit Rawat · Nov 15, 2016

User below this function

 //MARK:- PLAY SOUND
func playSound() {
    let url = Bundle.main.url(forResource: "ClickSound", withExtension: "mp3")!

    do {
        player = try AVAudioPlayer(contentsOf: url)
        guard let player = player else { return }

        player.prepareToPlay()
        player.play()
    } catch let error as NSError {
        print(error.description)
    }
}

first import AudioToolbox import AVFoundation

Hope it works :)