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.
1 |
import AVFoundation |
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.
1 |
var player: AVAudioPlayer! |
Step 6: Create a function to play the audio.
1 2 3 4 5 |
func playSound() { let url = Bundle.main.url(forResource: "file_example_MP3", withExtension: "mp3") player = try! AVAudioPlayer(contentsOf: url!) player.play() } |
Step 7: Then, in the play-pause, action button, write the below code.
1 2 3 4 5 6 7 8 9 10 |
@IBAction func pause(_ sender: Any) { if player != nil { player.stop() player = nil button.setImage(UIImage(named: "play"), for: .normal) } else { button.setImage(UIImage(named: "pause"), for: .normal) playSound() } } |
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.