Skip to content

Instantly share code, notes, and snippets.

@genedelisa
Created August 5, 2014 22:00
Show Gist options
  • Save genedelisa/d4aa45840af9e22245b9 to your computer and use it in GitHub Desktop.
Save genedelisa/d4aa45840af9e22245b9 to your computer and use it in GitHub Desktop.
Play a sound with AVAudioPlayer
func playSoundWithAVAudioPlayer() {
var alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("alert", ofType: "mp3"))
var error:NSError?
if !AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: &error) {
if let err = error {
println("could not set session category: \(err.localizedDescription)")
}
}
if !AVAudioSession.sharedInstance().setActive(true, error: &error) {
if let err = error {
println("could not make session active: \(err.localizedDescription)")
}
}
var audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, error: &error)
if let err = error {
println("could not create player: \(err.localizedDescription)")
}
audioPlayer.prepareToPlay()
audioPlayer.play()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment