Play sounds using AVAudioPlayer iOS

Tathagat Thapliyal
Coding Blocks
Published in
2 min readDec 1, 2019

One of the most common ways to play a sound on iOS is using AVAudioPlayer. it's easy to use, you can stop it whenever you want, and you can adjust its volume as often as you need. The only real catch is that you must store your player as property or other variables that won't get destroyed straight away – if you don't, the sound will stop immediately.

AVAudioPlayer comes from AVFoundation framework, so you'll need to import that:

import AVFoundation

Previously said, you need to store your audio player as a property somewhere so it is retained while the sound is playing. In our example, we’re going to play a Xylophone keypress sound, so I created a property for it like demonstrated below:

var player: AVAudioPlayer!

Now, all you need to do is play your audio file. This is done first making a function playSound()inside which you first need to find where the sound’s source file is located in your project, which is done using Bundle & path(forResource:), and then creating a file URL out of it. That can then be passed to AVAudioPlayer to create an audio player object, at which point – finally – you can play the sound.

func playSound() {        
let url = Bundle.main.url(forResource: xyz, withExtension: "mp3")
player = try! AVAudioPlayer(contentsOf: url!)
player.play()
}

Now finally you need to call this function from within your IBAction.

@IBAction func keyPressed(_ sender: UIButton) {
playsound()
}

If you want to stop the sound, you should use its stop() method.

If you found this article useful, then do appreciate it by clapping no less than 50 times.

For more projects and updates lookup at github.com/tathagat2006

--

--

Tathagat Thapliyal
Coding Blocks

Javascript | Typescript | ReactJS | EmberJS | NodeJS | GraphQL | React-Native | Blogger | Making Things Possible.