How to play a sound in your Swift iOS app using Chirp

I wrote Chirp because, frankly, although using AVFoundation is incredibly easy, it’s not easy enough — especially for new developers.

Chirp turns the following code:

if let soundURL = NSBundle.mainBundle().URLForResource("boop", withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL, &mySound)
AudioServicesPlaySystemSound(mySound);
}

Into:

Chirp.sharedManager.playSound("boop")

With Chirp, you do not need to keep track of SystemSoundIDs yourself. This is a huge bonus!

Chirp has 3 main functions

  • prepareSound(…)
  • playSound(…)
  • removeSound(…)

And these are the only functions you should need to prepare (load into memory), play, and remove (cleanup from memory) sounds in your app!

Example

prepareSound(…)

/* MyViewController.swift */

override func viewDidLoad() {
super.viewDidLoad()

// Load sounds into memory
Chirp.sharedManager.prepareSound("boop") // default extension is .wav
Chirp.sharedManager.prepareSound("ding.mp3") // so other extensions you must name explicitly
}

playSound(…)

func submitButtonTouched(button: UIButton) {
// Since the sound is already loaded into memory, this will play immediately
Chirp.sharedManager.playSound("boop")

// example function that might get called when you touch a button
submitForm()
}

playSound(…)

func submissionDidFinish(success: Bool) {
if success {
// This will also play immediately because you loaded the sound into memory in ViewDidLoad()
Chirp.sharedManager.playSound("ding.mp3")
} else {
// This sound was not preloaded into memory, and therefore will not play. Remember to prepare sounds first!
Chirp.sharedManager.playSound("oops.mp3")
}
}

removeSound(…)

deinit {
// Cleanup is really simple!
Chirp.sharedManager.removeSound("boop")
Chirp.sharedManager.removeSound("ding.mp3")
Chirp.sharedManager.removeSound("oops.mp3")

// If you never loaded the sounds, e.g. viewDidLoad wasn't called, or submission never failed or succeeded,
// that's ok, because these will function as no-ops
}

I hope you find this library helpful. Please feel free to leave me feedback here, and report any issues you may find on the Github repo

Enjoy!