Play audio with Javascript

Sound effects with Javascript

Embed sound events in HTML

The task often arises, the solution is simple: How can sound effects (e.g. signal tones) be linked to certain elements in HTML pages and reproduced automatically?

We'll show you how easy it is!

Example 1: playing notes

This little sheet of music shows the beginning of the melody of the nursery rhyme
"Little Hans". You can listen to the tones individually:

  • Hover your mouse over the note on the sheet music that you want to hear.

Example 2: A small computer game with sound events

Sinking ships

 

Who doesn't know the classic from school?
Your computer is a patient and fair opponent.

The Javascript function

We just need a simple Javascript function that contains two core elements:

  • an HTML string that loads and executes the sound file
  • a Javascript instruction that dynamically integrates the HTML string into the HTML page at the desired location.
 
function show_SoundMessage () {
var soundfile = "path / soundfile.mp3";
var sound_id = "soundbox";
var sound_message = "<";
sound_message + = 'embed src = "' + soundfile + '" autostart = "true"
loop = "false" hidden = "true" height = "0" width = "0" ';
sound_message + = ">";
document.getElementById (sound_id) .innerHTML = sound_message;
}
 

 

Explanation:

  • First we assign the correct file name to the variable soundfile. The id value of the HTML element that is to receive the dynamic content is stored in the sound_id variable.
  • The HTML string in sound_message embeds the file, starts it automatically (autostart), plays it only once (loop), does not display any player controls (hidden) and does not reserve any display space in the output (height, width ).

    Note: The value assignment for sound_message can of course be done in a single statement. In this example code, it only had to be carried out in three steps because otherwise Windows Explorer 8 actually interprets the text as embeded code during execution, which would lead to an error.
  • Finally, the HTML string is written with document.getElementById (sound_id) .innerHTML in the content area of ​​the tag that is labeled with sound_id.
    Caution: The function completely overwrites the content area of ​​the tag!

Embed the function in HTML

The Javascript function can be used in the head area
saved on the HTML page:

 
<script type="text/javascript" ><!--// Hier die Funktion einkopieren!--></script>  

You can also save the function in a separate file with the extension .js and integrate it using the file name in the head area of ​​your HTML page:

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

The HTML code for the function call

Now we have to call the function in the HTML code.
For this we need

  • an HTML element with the attribute id = "..."
  • and a triggering event, in this case a mouse event

This is how it works, for example:

 
<!-- Beispiel 1 --> <img src="pic.png" alt="" width="32" height="32"onmouseover="show_SoundMessage()"><divid="soundbox"></div><!-- Beispiel 2 --> <a href="javascript:show_SoundMessage()">Klick mich!</a><td id="soundbox"></td>
 

We're done with that!

The triggering event

The triggering event is a mouse event. Of course, it can also be the result of a calculation, a counter reading or a file content, etc. However, this has to be programmed for each specific application.

Our sheet music example is only slightly more complex: it basically only contains this function, but it is slightly expanded and works with two separate editions.

One output area (assigned via id) records the sound as described above, a second receives a text message at the same time. If a note image (png) is hovered over with the mouse (onmouseover), a certain sound file is loaded depending on the image and a message is generated. If the mouse leaves the picture, a second function is called which clears the text output area. To do this, an empty string is sent to the document function for the text area - but not for the sound area! - to hand over.

Summary

Sound files can be dynamically integrated into HTML files very easily. The way there is easy. Only a few requirements are necessary for this:

  • a defined, triggering event
  • a small javascript function that is called when the event occurs and writes the HTML to the HTML page
  • an HTML element that is uniquely identified with the id parameter and whose content can be completely replaced by the dynamic content

We have only included a few specialties as individual extensions in our example:

  • several different sound files are loaded and integrated
  • there is a second output area that outputs the text message, but works according to the same pattern
  • the text area is deleted as soon as a second event (here: onmouseout) occurs.

Own ideas

This creates the basis for many applications. For example, you can get rid of the alert boxes, which were very popular for alerting the user. Now it is very easy not only to write a message in a suitable place in the browser window; the user can be made aware of this with an acoustic signal at the same time.

However: you shouldn't expect too much! More complex applications - and our sheet music example is one of them! - one shouldn't solve with HTML this way. The browser is taking too much time to generate, load and execute the information (you will have noticed that the output of the sounds seems quite sluggish). The browsers also differ in how they handle sound files. Just test our site in different browsers.

Adobe® Flash is recommended for developing complex applications. The SWF files can be loaded much more easily during runtime and the Flash player takes care of playback. This ensures reliable playback in high quality (which can be important with sounds) in all browsers that support SWF files.

Good luck implementing your own ideas!

Sabrina

Text | Graphic | Web design | Layout:

© by Reiner Makohl | Stilkunst.de
© by Sabrina | SABRINA CREATIVE DESIGN ™

SK version 01/29/2021 ●