Ihoss Extension: Sound tutorial

Adding Sound Tutorial

How do I add sound effects to my extension? - 6/3-2005

Sound effects can be very important in an extension as it livens it up. With sound effects you can notify the user of certain events or simply add more depth to your extension. In this tutorial I will explain how you can add simple sound to your extension and how to use the nsISound interface.

nsISound

nsISound is an XPCOM Interface which means that you can only use it in javascript handled by mozilla. It will let you use special functions especially for mozilla software and there are lots of useful interfaces that you can use in extensions. nsISound will let you play sounds. nsISound has four functions, but I will focus on only 2 of them, beep and play. You can read about nsISound and the other functions here.

Using nsISound

//netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
gSound = Components.classes["@mozilla.org/sound;1"].createInstance(Components.interfaces.nsISound);

This will create a sound object which you can use to play sounds. As you can see I have commmented out a function. If you put this in your code you will be allowed to call components and use their special functions outside of mozilla. That is, if your javascript is not part of an extension or the mozilla (firefox, thunderbird or suite) source code, you will have to include it. Don't include it for extensions.

gSound is now an instance that we can use to play sounds. I will show you how to play a beep sound and how to play sounds from files.

beep()

gSound = Components.classes["@mozilla.org/sound;1"].createInstance(Components.interfaces.nsISound);
gSound.beep();
		

All this will do is play a simple beep sound. Yep, that was easy, wasn't it?

play()

//netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
soundURL = "sound.wav";
gSound = Components.classes["@mozilla.org/sound;1"].createInstance(Components.interfaces.nsISound);
var ioService = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
var url = ioService.newURI(soundURL, null, null);
gSound.play(url);

Playing a sound file is a bit more difficult. The sound object does not take the url as a string, so we have to convert it to a URI. To do this you can use io-service and call the function newURI. Pass the string as a parameter and save it in a variable and we are ready to play the sound. Play it with the play(url) function where the url parameter is the url of the sound.

Not working?

Ok, so you have added everything and it still does not work?

Finaly

That's it. Add the code where it is needed and test your extension. You can download this tutorial and a javascript file here. If you have any questions or ideas send me a mail and I will gladly help you.
Ihoss - March/2005