Start a Project

How to Play Sounds in Swift

How to Play Sounds in Swift

In today’s blog, we will learn how to play sounds in Swift.

The most prevalent way to play a sound on iOS is using AVAudioPlayer.

It’s popular for a reason: it’s facile to use, you can stop it whenever you want, and you can adjust its volume as often as you require.

The only authentic catch is that you must store your player as property or another variable that won’t get eradicated straight away – if you don’t, the sound will stop immediately.

Let’s check the code below for how to play sounds in Swift.

Step 1: Create an Xcode project, in our demo let’s name it “PlayAudio”.

Step 2: Now, open Main.storyboard, and create a button to play-pause the audio.

Step 3: Create the IBOutlet for the button, the action on the button will play and pause the audio.

Step 4: Add the audio of your choice to the project directory.

You can check here for the supported audio formats  in AVAudioPlayer

Step 4: As AVAudioPlayer is the functionality in the AVFoundation framework, so import AVFoudation in your ViewController class.

Step 5: We need to store our audio player as a property somewhere so it is retained while the sound is playing, so let’s create an object of AVAudioPlayer.

Step 6: Create a function to play the audio.

Step 7: Then, in the play-pause, action button, write the below code.

Step 8: Now run your code, after clicking on the play button the sounds start, and if you wish to stop it, again click on the same button.

Thanks for reading 🙂

Hope this blog helped you with a better understanding of how to use AVAudioPlayer.

For more blogs please visit here.

Exit mobile version