Build an independent watch app - Part II

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.




image

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

UI changes

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.




image

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.




image

Source code changes

We are still in DetailsInterfaceController.swift
Add to the imported libraries
import AVFoundation
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?!
setFileAudioToPlay(soundToPlay: name)
The code for the function setFileAudioToPlay looks like this. Put it anywhere in the same file you are currently working on.




image

The code for the actual button, to execute once tapped looks like this




image

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:




image

Asset changes

Download some dino sounds from this web site for free. If you want to use the ones I picked with the names are already to just drag and work, use this link to download them.
Add the sounds




image

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!

Comments

Popular posts from this blog

Build an independent watch app - PART IV

It's all matter of angles, in life