Play (short) sound 📣 in iOS using AudioToolbox
Normally we need different variety of notification sounds to be played in our app to give feedback to user. The best and optimised way to play sound (of max 30 seconds) I found for myself is below 👇-
- According to documentation only
.caf
,.aif
, or.wav
files are allowed. So add your sound files in one of these formats to your bundle, don’t forget to check “Copy if needed” and also adding to target. - Add an lookup array to store all the sounds.
3. Add an enum for these types.
4. Then add the main part of code
In above code we try to find the soundID we want to play and play it and if not found we are creating a system sound and adding it’s ID to an lookup table and playing it. This helps us to remove the need of creating same sound again and again. You can use AudioServicesPlayAlertSound
to make phone vibrate along with making sound.
5. Add a method to dispose all soundIDs and call it appropriately in deinit
and didReceiveMemoryWarning
.
6. Now you can call the play method as (the dot preceding “wav” looks 😍)-
And now you can make your app more better by playing short sounds on appropriate places.
Happy coding
The sooner you start coding, the longer it takes.
Link-