Play sounds in Swift

Moussa Hellal
2 min readSep 6, 2023

Incorporating audio cues can drastically improve the overall User-Experience in your application, whether it’s verifying a successful payment, celebrating a win in a game, or responding to any other user interaction. It gives the users instant audible feedback on their activities.

Luckily in Swift it’s a straightforward process to integrate such a thing.

Step One

Drag and drop your audio file to your project folder.

In our example here we are going to use Success.mp3

Make sure to check these options.

Step Two

import AVFoundation


func playSound() {
guard let path = Bundle.main.path(forResource: "Success", ofType:"mp3") else {
return }
let url = URL(fileURLWithPath: path)

do {
player = try AVAudioPlayer(contentsOf: url)
player?.play()

} catch let error {
print(error.localizedDescription)
}
}

Copy this function in your code.

Change file name and the type accordingly.

In our case it’s Success: file name, mp3: file type

Now simply call this function playSound() from whatever case you see it is useful , and That’s it.

Easy right? Try it and Happy coding!

I appreciate you choosing to spend some of your day with me. I hope that my piece was informative and helpful to you.

Farewell, keep growing and learning. See you in the next one. ✌️

Make sure to follow me on Twitter to keep receiving the newest articles:

https://twitter.com/codeWithMoses

--

--