Playing a Sound in JavaScript

The code included below will play the sound “ding.wav” from JavaScript when the “Play Sound” link is clicked.

To see it in action, copy it into a .html file, put that file in the same folder as a copy of “ding.wav”, and open the .html file in a web browser that has JavaScript enabled.

<script type='text/javascript'>

function Sound(filePath)
	this.filePath = filePath;
{ = function()
		var htmlElementForSound = document.createElement("audio");
		htmlElementForSound.autoplay = true;

		var htmlElementForSoundSource = document.createElement("source");
		htmlElementForSoundSource.src = this.filePath;


<a href='#' onclick="new Sound('ding.wav').play();">Play Sound</a>
This entry was posted in Uncategorized. Bookmark the permalink.

One Response to Playing a Sound in JavaScript

  1. serdarsanri says:

    This will only run if browsers supports HTML5. You should include a fallback function for ol browsers.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s