Swift – AVAudioFoundation

Playing sounds with Swift and AVAudioFoundation

A few notes about using AVAudioFoundation with Swift.

Be sure to add your audio files to your project. Make sure they have been “added to target”. Without this the audio files will not be bundled with your app.

Import AVAudioFoundation.

Use AVAudioPlayer() to create a new audio player instance.

Call audioPlayer.play() to play a sound and audioPlayer.stop() to stop a sound.

Sounds play from beginning to end. Calling stop() pauses the sound at the current time. Calling play() again starts the sound from the current time. To start from the beginning of the set the currentTime property to 0!

Here is a sample code block.

import AVAudioFoundation

// Get a path to your audio resource
let path = NSBundle.mainBundle().pathForResource(self.audioFileName(), ofType: nil)!

// Make a URL from the path
let url = NSURL(fileURLWithPath: path)
// Try to make an audio player with the URL
do {
    let sound = try AVAudioPlayer(contentsOfURL: url)
    sound.play() // If all is good play your sound
} catch {
    // Handle an error here
    print("unable to load sound...")
}

Leave a Reply

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