Entries:
Comments:
Posts:

Loading User Information from Channel 9

Something went wrong getting user information from Channel 9

Latest Achievement:

Loading User Information from MSDN

Something went wrong getting user information from MSDN

Visual Studio Achievements

Latest Achievement:

Loading Visual Studio Achievements

Something went wrong getting the Visual Studio Achievements

Creating Loud Websites

  In this post, Stephen Walther explains how to make your websites have more noise. You learn how to use Javascript to add sound effects to your ASP.NET pages.
Steve's Blog

Difficulty: Easy
Time Required: Less than 1 hour
Cost: Free
Software: Visual Web Developer 2005 Express

I want to create noisy websites. All of our desktop applications make sounds. It seems completely unfair that our websites are so quiet.

For example, when you empty your computer's recycle bin your computer makes the satisfying sound of trash being dumped from a trash can. When you leave the desktop and enter the web, however, the world goes silent (almost like you are under water).

When you browse a catalog of products displayed on a website, each product should demand to be bought. When you hover your mouse over a picture of a music box, it should play a quiet tune. When you hover your mouse over a picture of a vacuum cleaner, it should make a mighty rrrrrrrrrrrrr sound.

Whenever I reveal my secret ambition to make noisy websites, people always groan. Everyone always thinks of all of those MySpace pages with the endlessly looping background music. But I don't mean background music, I mean noise.

We interact with websites through metaphors. We work with “files” and “folders” on a “desktop”. We grab files and “drag” them to new folders. Under the covers, of course, we are really just flipping massive numbers of bits. But, we understand our complex interactions with our computers by projecting metaphors that we've stolen from the physical world onto our machines.

The more closely our software interactions match our metaphors, the more satisfying the experience becomes. Dropping a file in a recycle bin to delete it makes perfect sense. If the recycle bin looks like a prototypical recycle bin, the experience seems more real. If the trash makes a satisfying trash-being-emptied sound, the experience is even more real.

In this month's post, I'm going to tackle the problem of adding sounds to your ASP.NET websites. The goal is to produce sounds dynamically using Javascript.

Methods of Making Sounds

Let's start with a quick review of the methods of generating sounds in a web page. There are three tags that you can add to a page to generate a sound: the <bgsound> tag, the <embed> tag, and the <object> tag.

Here's how you add sound with the <bgsound> tag:

<bgsound src="test.wav" />

The <bgsound> tag is the tag that gave sound a bad name. This is the tag that everyone adds to their websites to create the endlessly looping background music.

The <bgsound> tag was introduced into the world (in the same month) with the release of Microsoft Internet Explorer 2.0 and Mosaic 2.1. Opera supports the <bgsound> tag, but Firefox does not.

Since the <bgsound> was never incorporated into any web standards (you won't find any mention of the tag in either the HTML or XHTML standards), most web authors avoid this tag as outdated and dead. Typically, you are encouraged not to use the <bgsound> tag in favor of either the <embed> or <object> tag.

However, I use the <bgsound> sound tag in the Javascript that I develop at the end of this post. There is one very important advantage of the <bgsound> tag. The <bgsound> tag does not cause the information bar to popup in Internet Explorer when you use this tag in a page.

The Internet Explorer version of this tag has four important properties:

  • Balance -- Enables you to specify the balance between the left and right speaker
  • Loop -- Enables you to specify the number of times that the sound will repeat. The value -1 means loop infinitely
  • Src -- Enables you to specify the URL to the sound file
  • Volume -- Enables you to specify the volume of the sound (valid values range from -10,000 to 0)

As an alternative to the <bgsound> tag, you can use the <embed> tag. The <embed> tag was introduced to the world with the release of Netscape 1.1. The tag is now supported by all modern browsers.

Here's how you use the <embed> tag:

<embed src="test.wav" type=”audio/x-wav” />

The src attribute points to the sound file and the type attribute specifies the MIME type of the file. Notice that the MIME type of a .wav sound file is indicated with the MIME type audio/x-wav. The x means that .wav is a custom type. Using the x is necessary because the .wav sound file format does not have a registered MIME type at IANA.

The <embed> tag is not limited to sounds. You can use the <embed> tag to embed a variety of different types of objects in a page including videos and pictures.

There's no master list of valid attributes for the <embed> tag. Different types of objects that you embed in a document will support different attributes. For example, on my computer, Windows Media Player is mapped to the .wav extension. Therefore, I can use Windows Media Player attributes with the <embed> tag.

One problem with using the <embed> tag is that you must have an application mapped to the type of file being downloaded. Unfortunately, on my computer, there was no application mapped to the .wav extension by default. When I initially requested a page that contained an embedded .wav file, I got the Internet Explorer information bar.

Since I don't want to inflict the Internet Explorer information bar on users when playing sounds, I don't use the <embed> tag in the Javascript at the end of this article. The <bgsound> element enables us to play .wav files without displaying the information bar.

The final -- and generally recommended -- method of adding sound to a web page is to use the <object> tag. The <object> tag is very similar to the <embed> tag. It allows you to embed objects in a page like this:

<object data="test.wav" type="audio/x-wav" />

Notice that the <object> tag uses the data attribute and not the src attribute to point to a file.

The difference between the <embed> tag and the <object> tag is that the latter tag is supported by W3C web standards. If creating standards compliant websites is important to you, then you should use this tag.

Just like in the case of the <embed> tag, there is no master list of attributes for the <object> tag. The list of valid attributes all depends on the application or plug-in being used to display the embedded object.

Unfortunately, when used with Internet Explorer, the <object> tag causes the Internet Explorer information bar to popup just like the <embed> tag. In the Javascript at the end of this article, I use the <bgsound> tag for Internet Explorer and the <object> tag for every other browser.

Generating Sounds with Javascript

So now that we've finished reviewing the possible methods of generating sound in a page, we are ready to create our Javascript that we'll use in our ASP.NET pages to generate sound. Our script will works with recent versions of all major browsers including Internet Explorer, Firefox, and Opera.

Since the script is small, the entire content of the PlaySound.js Javascript file is included right here:

PlaySound.js

if (window.attachEvent)
    window.attachEvent("onload", setupPlaySound);
else
    window.addEventListener("load", setupPlaySound, false); 


function setupPlaySound()
{
    if (navigator.appName == "Microsoft Internet Explorer")
    {
        var snd = document.createElement("bgsound");
        document.getElementsByTagName("body")[0].appendChild(snd);
        
        playSound = function(url)
        {
        
            snd.src = url;
        }
    }
    else
    {
        playSound = function(url)
        {
            var obj = document.createElement("object");
            obj.width="0px";
            obj.height="0px";
            obj.type = "audio/x-wav";
            obj.data = url;
            
            var body = document.getElementsByTagName("body")[0];
            body.appendChild(obj);
        }
    }
}

 

The first lines of the Javascript create an event handler for the browser window load event. Internet Explorer uses the attachEvent() method to create an event handler and other browsers use the addEventListener() method.

The setupPlaySounds() method is called after the window is loaded. This method creates the playSound() method. Javascript enables you to conditionally create different versions of a function. There is one version of the playSound() method that is created in the case of Internet Explorer and another version that is created in the case of every other browser.

The Internet Explorer version of the playSound() method takes advantage of the <bgsound> tag to play a sound. The alternative playSound() method takes advantage of the <object> tag.

If you link the Javascript file above into an ASP.NET page, then you can play a sound by calling the playSound() method and passing the URL of a sound file. You can link the PlaySound.js file to an ASP.NET page by adding the following tag to the page:

<script type="text/javascript" src="PlaySound.js"></script>

And, adding the following link to a page will cause the sound file ClickHere.wav to play whenever you hover your mouse over the link.

<a href="SomePage.htm" onmouseover="playSound('ClickHere.wav')">Click Here!</a>

The playSound() method works with recent versions of Internet Explorer, Firefox, and Opera.

I did run into one issue when testing this method with Firefox. Firefox uses the Apple QuickTime plug-in to play sound files. However, on my computer, QuickTime was not mapped to .wav files. I fixed this problem by launching the QuickTime Player, and selecting the menu option Edit, Preferences, QuickTime Preferences and selecting the File Types tab. Under this tab, I was able to associate .wav files with the QuickTime Player.

Conclusion

I think the web would be a much more enjoyable place if it were only a little louder. In this post, I've provided you with a cross-browser compatible Javascript playSound() method that you can use in your ASP.NET pages to add sound. Please make some noise.

Tags:

Follow the Discussion

  • Pure LPure L

    I'm confused as to where the actual sound file should be called from?

    Let's say the sound file is located at sounds/tada.wav , do I type that url wherever "(url)" is listed in the code?

    Thanks.

  • TutiTuti

    This sounds like an April Fools Day contribution!

    Who wants all that noise - aren't pop-ups more than enough already?

  • kirankiran

    Cool way of reinventing the lost glory Wink

    Will experiment with SOunds now ,thank you!

  • Steve SavageSteve Savage

    Do non-Microsoft browsers support any of this?  (Firefox, netscape, safari, etc...)

  • jrthor2jrthor2

    This script does not work in Safari.  Is there any way to get this working in Safari?

    Thanks.

  • jrthor2jrthor2

    This method does not work in Safari.  Anyone know how to get ths script working in Safari?

  • DawgDawg

    BGSOUND is still the best way to play background music on a web page. The W3C will have a fit and so will Microsoft based HTML IDE's about the tag, but it is still supported by IE7 and Netscape.

  • CharanCharan

    simple, excellent & useful article buddie ... gr8 work !!!!!!!!

  • KemalKemal

    Steve,

    Technically, your article is one of the best short tutorials I have seen anywhere.

    People may or may not like sound on web pages. That is their opinition, and frankly, they are irrelevant.

  • AmitAmit

    I want to pass the sound file url from code behind

    during page load and then want to play that sound file

    on page load.

    I think code behind page load executes prior to client side page load so this is possible but don't know the exact way to do so.

    Please tell me

  • dannzemandannzeman

    On line 13 (lines of code, not spaces) the code "snd.src = url;" is where it defines the location. You replace 'url' with the directory where your soud file is located.

  • zaghy2zy_at_yahoo_dot_comzaghy2zy_at​_yahoo_dot_​com

    great! now making those surprisingly great effects can grab some attention

    ---does this work on mp3?

    ------yeah, if you use the <object> or <embed> tag

    but if you dont like that info bar, try finding an audio converter for to change mp3 to wave

  • brodybrody

    i am looking for a free web site brodcast music any body has one email me i have rap/rock/metal all i need is a url

  • TomTom

    Surely network latency is an issue here?  If I click the "empty trash" button the trash-emptying sound needs to play straight away, not after the delay caused by the browser requesting and receiving the audio file from the server (and then figuring out how to play it).

  • Dylan JDylan J

    I can't say that i'm the best web developer in the world, but didn't sounds on web pages go out of fashion a while ago?

    Just my two cents.

  •   Coding4Fun : Creating Loud Websites |  Music Coding4Fun : Creating Loud Websites | Music

    PingBack from http://music.247blogging.info/?p=328

  • TJATJA

    Can you turn the sound off using a onmouse out?  If true, how do you code it -- in relation to the above PlaySound.js and JavaScript?

    Thanks in advance.

  • Clint RutkasClint I'm a "developer"

    @TJA:  Try removing the sound from the DOM tree on mouse out.  That may work.  I haven't tried but seems logical.

  • Clint RutkasClint I'm a "developer"

    @TJA:  Email me via the contact link at the top.

  • TJATJA

    playSound="('')" works fine in IE onmouseout for turning sound off.  In Firefox, however, sound plays until end of wav.  Any way around this?

  • shreyashreya

    bgsound works fine until the window is maximized

    but if you minimize the window we can't hear any sound in IE6

  • Clint RutkasClint I'm a "developer"

    @Deren, it isn't that simple.  a ASPX page is actually compiled once by the server and requires a few extra bits in it.

    Check out Visual Web Developer Express to make some ASP.Net web pages at http://www.microsoft.com/express/

  • Deren Deren

    It is an excellent article and sincere thanks for posting the JS script.  One simple question:

    in ASP.NET the page extension is SomePage.aspx,  I tried to change

    SomePage.htm  to SomePage.aspx

    but it did not work.

    Could you help, Steve?  Thanks again.

  • derenderen

    Steve,

    This is a very useful article:

    Using JavaScript Along with ASP.NET

    http://msdn.microsoft.com/en-us/library/aa479011(loband).aspx

Remove this comment

Remove this thread

close

Comments Closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.