Read More
Read now

How to Play Sounds in Swift

Save

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.

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

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

Step3: Create the IBOutlet for the button, action on the button will play pause the audio.

Step4: Add the audio of your choice to the project directory.

You can check here for the supported audio formats  in AVAudioPlayer

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

Step5: 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.

Step6: Create a function to play the audio.

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

Step8: Now run your code, after clicking on the play button the sounds starts, 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.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

css.php

Big thanks to Webkul and his team for helping get Opencart 3.0.3.7 release ready!

Deniel Kerr

Owner and Founder. Opencart

Talk to Sales
Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home