Play audio file using AVFoundation

Play Audio File in Swift

This tutorial will show you how to play sound in Swift using the native AVFoundation framework.

    var player: AVAudioPlayer?
    
    func playSound(audioName: String) {

        let url = NSBundle.mainBundle().URLForResource(audioName, withExtension: "mp3")!
        
        do{
            player = try AVAudioPlayer(contentsOfURL: url)
            guard let player = player else { return }
            player.prepareToPlay()
            player.play()
        } catch let error as NSError {
            print(error.description)
        }
    }

Don’t forget to import AVFoundation in your class.

Leave a Reply

Your email address will not be published. Required fields are marked *