Adding Sound

The premise of our app is for the user to guess the sounds which are played. The app was at point where the structure was completely stable and can run through a set of question which had has multiple answers to choose from. So our next task was to add a way which the user can press a button and play a sound and from that sound have a clues on what the answer is.

We didn’t have much knowledge in the area of sounds and how we would implement this button which would play sounds, but after some research we a functional method to achieve whet we wanted. The first stage was to import the pre-built class (code shown below), which allowed us to access the code needed to implement.

import AVFoundation

Next we had to set-up and initialize an audioPlayer, which gave us a space/ storage space where the sound that we loaded would be put prepare to play before the button is pressed so once the user wants to hear the sound there is no delay.

 


override func didMoveToView(view:SKView){
audioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: nil)
audioPlayer.prepareToPlay()

Then we added a piece of code which grabbed the sound file from the folder and also dictated the type of sound file we had to create, as you can see below the file name and file type are separate, so the sound files, type e.g .wav had to coincide with what was put in the code.


var coinSound = NSURL(fileURLWithPath:NSBundle.mainBundle().pathForResource("coin", ofType: "wav"))

Finally I had to set-up a button, positioning and using constraints to keep it contained with-in the structure we previously had with the other buttons,  and then put the below code in an action linked to the button so when the button is pressed it calls the function which then plays the sound.


audioPlayer.play()

After successfully making a single sound to work, we came across a problem, which was because, we needed multiple sounds to played from the same view controller, we would have to adopt this code to be dynamic and be able to input multiple sound files.

The way we resolved this was by adding a sound file name object to our question class and then stored all of the file names of the sound files, but without the type of file because of how the code works, then instead a static single file name we called the class (like below). So each sound now essentially had a number assigned to it which allocated it to a certain question, so when the question is displayed the linked sound would be prepared to play.


pathForResource(questions.soundFile, ofType:"wav"))

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s