DEV Community

yipcodes
yipcodes

Posted on

Play sound in SWIFT 5

import AVKit

class ViewController: UIViewController {
    var player: AVAudioPlayer?

    @IBAction func buttonPressed(_ sender: UIButton) {
        playSound(soundTitle:sender.currentTitle!)
    }

    func playSound(soundTitle:String) {
        let path = Bundle.main.path(forResource: "soundName",ofType:"mp3")

        let url = URL(fileURLWithPath: path!)

        do {
            player = try AVAudioPlayer(contentsOf: url)
            player?.play()

        } catch let error {
            print(error.localizedDescription)
        }
    }
}


Enter fullscreen mode Exit fullscreen mode

Top comments (0)