In PART I, I explained in super details on how to make an independent watch app. A reader posted in the comments a request on how to make the dinos do sounds. I wasn’t taking on the ask until I found that the reader is a little young girl learning how to program Apple Watch.
I am a sucker for such combos so I figured let me show the way.
The project still the same we used last time. Here’s what changed:
- Added a button on screen two
- Attached a function to the button to play the dino’s sound
- Added some sounds
Open the storyboard file and on the second screen at the bottom, add button. By default, the buttons are ugly and uninteresting. Use the inspector to change its appearance. Here what mine looks like.
Enable the assistant like we did in the previous post so that you can see code and UI at the same time. Holding CTRL (or dragging with right-click) draw an outlet from the button to the source code DetailsInterfaceController.swift.
Pay attention that the dialog that will appear once you release the button will propose an outlet (a connection) we don’t want that, we want action. Give it the name soundButton and then connect.
Source code changes
We are still in DetailsInterfaceController.swift
Add to the imported libraries
That tells the system we need api for making video and sound stuff. Right after the last declared outlet add
var player = AVAudioPlayer()
let audioSession = AVAudioSession.sharedInstance()
after dinoImage.setImage(UIImage(named:name)) add. Don’t worry if you get an error for now as that function doesn’t exist yet. Just like before you invented fire there was not axe to cut the wood… remember cavewoman?!
The code for the function setFileAudioToPlay looks like this. Put it anywhere in the same file you are currently working on.
The code for the actual button, to execute once tapped looks like this
If you don’t see the dot filled you haven’t connected the action correctly. There are multiple ways of doing that as I have shown you thus far.
We are done with the code YAY! Here’s a summary of the changes:
Add the sounds
I created a folder (right click, create group), make sure that is added to Watchkit extension and not the watchkit app otherwise the bundle will not contain the sounds in the right place.
Happy roaring girl!