Playing a sound with AVAudioPlayer Playing a sound with AVAudioPlayer ios ios

Playing a sound with AVAudioPlayer


Made modification to your code:

import UIKitimport AVFoundationclass ViewController: UIViewController {    var audioPlayer = AVAudioPlayer()    override func viewDidLoad() {        super.viewDidLoad()        var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("button-09", ofType: "wav"))        println(alertSound)        // Removed deprecated use of AVAudioSessionDelegate protocol        AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)        AVAudioSession.sharedInstance().setActive(true, error: nil)        var error:NSError?        audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)        audioPlayer.prepareToPlay()        audioPlayer.play()    }}

Swift 3 and Swift 4.1:

import UIKitimport AVFoundationclass ViewController: UIViewController {    private var audioPlayer: AVAudioPlayer?    override func viewDidLoad() {        super.viewDidLoad()        let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: "button-09", ofType: "wav")!)        print(alertSound)        try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)        try! AVAudioSession.sharedInstance().setActive(true)        try! audioPlayer = AVAudioPlayer(contentsOf: alertSound)        audioPlayer!.prepareToPlay()        audioPlayer!.play()    }}


As per Swift 2 the code should be

var audioPlayer : AVAudioPlayer!func playSound(soundName: String){    let coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(soundName, ofType: "m4a")!)    do{        audioPlayer = try AVAudioPlayer(contentsOfURL:coinSound)        audioPlayer.prepareToPlay()//there is also an async version        audioPlayer.play()    }catch {        print("Error getting the audio file")    }}


Your audio play will be deallocated right after viewDidLoad finishes since you assign it to a local variable. You need to create a property for it to keep it around.