Tutorial – Playing a Sound Effect
Playing a sound in XCode is easy with not much code. This tutorial will take you through the steps to play a sound.
The demo sound we will be using for this project is a Mario power up sound!, it can be downloaded from here.
Once you have downloaded the sound create a new XCode project of the type single view application. Drag the sound file into the supporting files folder in XCode and ensure the option is ticked to copy the files.
Now lets head over to the storyboard and add a button to play the sound. Drag a button onto the storyboard. Lets name it play sound. Once on select the assistant editor to split the view up.
Hold control and drag the button to connect it up to the storyboard, create an Action and name it PlaySound with the type as UIButton.
Now under import UIKit add import AVFoundation, this is needed to play the sound.
Also under class ViewController add var audioPlayer = AVAudioPlayer() , this will be used to play sound later.
Now that this is setup time to add the code to our button to play the sound!. Add the following code to play sound.
// Set the sound file name & extension let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: "Mario", ofType: "mp3")!) do { // Preperation try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) } catch _ { } do { try AVAudioSession.sharedInstance().setActive(true) } catch _ { } // Play the sound do { audioPlayer = try AVAudioPlayer(contentsOf: alertSound) } catch _{ } audioPlayer.prepareToPlay() audioPlayer.play()
Now run the app & click the button to hear your sound be made!