Apple ships a ton of great APIs for playing audio in our apps.

They offer a wealth of great functionality, but also a fair amount of complexity.

Often we don't need all that power. Perhaps we're adding sound effects or audio feedback to one of our user interfaces, or maybe we just need to loop some background music in the menu of our video game.

Today we'll check out a new library from Adam Cichy called SwiftySound that can help us simplify our audio playback code. Let's take a look.

First up, simple playback:

Sound.play(file: "unscheduled-offworld-activation.wav")

or

Sound.play(url: someURL)

That's it. Yes, really.

This kind of UIImage-esque simplicity has always been sort of missing from UIKit. Neat to see.

SwiftySound doesn't stop there though, We can easily loop sounds:

Sound.play(file: "main-menu", fileExtension: "wav", numberOfLoops: -1)

We could pass in any Int here to loop the music, but we've passed -1 to indicate we want to loop forever.

One of the most useful features of SwiftySound is the inclusion of a UserDefaults-persisted flag for persisting the user's preference of sound playback being enabled or disabled.

We can use this on our app's Settings screen to allow users to easily enable/disable sound effects globally.

Sound.enabled = soundsSwitch.on

The value is then automatically persisted and respected across app launches. A nice touch by SwiftySound's author, Adam Cichy.

We're not required to use this singleton Sound instance by the way, we can always create a Sound instance and pass it around:

let sound = Sound(url: soundEffectURL)

Then later:

sound.play()

Last but not least, SwiftySound stands out for being a single Swift file.

It's great to see this kind of power and flexibility in such a tiny little dependency.

😍 More like this please!

Full documentation for SwiftySound is at git.io/swiftysound