Playing a Sound from a Dashcode Widget

I’ve just begun to play around with Dashcode for the first time. I wanted to develop a widget that, when clicked, plays a sound. Figured it would be pretty simple. It nearly was.

The general steps are as follows:

  • Launch Dashcode and select ‘Custom’ from the Dashboard section.
  • Click on Library (top right) and click Parts
  • Drag a button onto the widget
  • Drag and drop a sound file (.m4a or any other file supported by QuickTime) from Finder onto the widget
  • For the sake of following these instructions, rename the sound file element from ‘video’ to ‘sfx’

Okay. Now we just have to write some code that will play the sound when you click the button. Fortunately or unfortunately, Apple provide some example code. If you go to the Library again and select Code instead of Parts and type ‘play quicktime’ in the search box you get some sample code. This is what you will see:

// Values you provide
var qtElement = document.getElementById("elementID");	// replace with the ID of a QuickTime element

// QuickTime code
qtElement.Play();

Now, at this point it should simply be a case of opening up the inspector, navigating to the events tab (far right), creating an onclick handler, pasting in the code and renaming ‘elementID’ to ‘sfx’.

Well it would be…If the sample code wasn’t completely wrong! The code that actually works is below:

function onButtonClick(event)
{
    var qtElement = document.getElementById("sfx");
    qtElement.firstChild.play();
}

There are two problems with the original sample code.

  1. The actual element is just a div container. To get to the media player element you have to access the first child of this container.
  2. The Play() method has the wrong casing and should be lower case, not upper case.

It kinda makes you wonder what the point of providing sample code is if it doesn’t actually work? Anyhow. Hope someone finds this useful.

I woud be interested to know if anyone knows of a better way of playing a sound effect? If you do, please post your suggestion in the comments.