Reusable extension to play sound without memory leak in iOS and Swift?

Viewed 876

Playing a sound is so verbose in code and would like to create an extension of AVAudioSession if possible. The way I'm doing it is assigning an object to a variable, but need help/advise on how to set up this function so it's reusable and optimized.

Here's what I have:

func playSound(name: String, extension: String = "mp3") {
    let sound = NSBundle.mainBundle().URLForResource(name, withExtension: extension)

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)

        UIApplication.sharedApplication().beginReceivingRemoteControlEvents()

        audioPlayer = try AVAudioPlayer(contentsOfURL: sound!)
        audioPlayer?.prepareToPlay()
        audioPlayer?.play()
    } catch { }
}

I think I have to create the audioPlayer variable outside of this function, otherwise I had a hard time playing anything. Maybe it can be self contained? I'm hoping to use it something like this:

AVAudioSession.sharedInstance().play("bebop")
2 Answers
Related