-- --- .-. ... . -.-. --- -.. . - .-- .. - .... .- .. .-. .- -. -.. .--- .- ...- .- ... -.-. .-. .. .--. -

Filed under: AIR, JavaScript, jQuery

comments (6) Views: 6,866

Also known as Morse Code Generator with AIR and JavaScript

Back in October Ray Camden posted a quick tutorial on how to play sound effects in AIR using JavaScript. One of the commentors mentioned that he teaches a class on morse code and thought it would be cool to have an app that can play morse code on command. I thought it was a good challenge, so I accepted it. Most of it is plain vanilla JavaScript, with the exception of the Sound object. Let's take a look at what's involved. You can download a zip file with the entire project, or you can download the AIR app by itself.

The first thing I needed to do was get the Morse alphabet, and serialize it. Morse code is simple, consisting of a series of long and short sounds, represented visually by a dot ( . ), and a dash ( - ). I created an object and used the letters and numbers of the alphabet as keys. The values of those keys were the dots and dashes that made up each character.

Then I created a simple input field for the text users wanted converted. Next I found 2 sound clips over at SoundJay.com that I felt best represented a dot and a dash. To keep things organized I created another object to store references to the sound clips. I used a dot and dash as the keys in this object, you'll see why in a minute. Using AIR we then load them into memory as a Sound object, like so:

The next part is pretty straightforward. I grab the contents of the input field, allowing only letters and numbers. I then loop over the length of the string, matching the character with a key in the morse code object. Because I'm only working with two sound files, each character needs to be broken down to it's dots/dashes, so I store each individual dot/dash of the matching string into an array index for efficient looping later on.

When I'm done matching all the characters from the input field I loop over the resulting array and match each dot and dash with the corresponding audio file. The final piece of the app was to add a slight pause during each loop of the array. Because the SquirrelFish JavaScript engine in AIR is so fast, all the sounds would play at the same time. The pause occurs while the sound is playing and prevents overlap.

As an extra touch, I decided to add a handy little output window so that users could see the resulting morse code tied to each individual letter. This app was a lot of fun to build and I hope you learn something from it.

Amazon logo

If this article was interesting, or helpful, or even wrong, please consider leaving a comment, or buying something from my wishlist. It's appreciated!

comments powered by Disqus