Learn English with Martin

Learn all you need to know about English!

Example of audio embed, the HTML5 way.

 

1. The audio player

The code to do this is:


<audio controls>
  <source src="PATH TO FILE.mp3" type="audio/mpeg">
  Your browser does not support the audio tag.
</audio> 

Note: If you made the audio file yourself, then the file must be uploaded to your github area, and the link to it pasted into the 'PATH TO FILE' entry shown in the code above. For example, in my example, the path is: https://martinbarge.github.io/demo-site-2021/audio/uk.mp3 .

Also, try to keep the names of your audio files short, descriptive, single-word and lowercase. You'll notice that my audio file is simply named **uk.mp3**. It makes it so much easier!


 

2. H5P audio player

H5P provides an audio player application, named 'Audio', to which you upload your audio file and then embed on your site, like so:

Note: You won't find the Audio player item on the H5P website. However, you can click the 'reuse' link in my example above, download the H5P file and then upload it to your own H5P account and edit it there.


 

3. Using JavaScript to play audio

JavaScript includes the 'play()' method, enabling you call a function to play audio when a page element is clicked.

The following are examples of page elements that play a sound when clicked.

i) Text that plays sound when clicked

Some text such as psychology.


ii) Buttons that play sounds when clicked


iii) An image that plays a sound when clicked


Javascript Code

The following code extracts illustrate how to attach sounds to page elements, using JavaScript.

First, we need to include this simple JavaScript function to play sounds:

  
<script>
function playSound(soundObj) {
var audio = new Audio(soundObj);
audio.play();
}
</script>

Now we can call the JavaScript function from any page element. The following entries show how to do this.

1. This first entry shows the function attached to a button object.

  
<input id="submit" type="button" value="psychology" onClick="playSound('https://martinbarge.github.io/sml5202-sts/assets/audio/psych.mp3')"> 

2. This next entry shows the function attached to a link text.

  
<p><a href="#" onClick="playSound('https://martinbarge.github.io/sml5202-sts/assets/audio/psych.mp3');event.preventDefault();">LINK TEXT</a>.</p>

3. This final extract shows the function attached to an image.


<a id="image" onClick="playSound('https://martinbarge.github.io/sml5202-sts/assets/audio/rhino.mp3')">
<img src="https://upload.wikimedia.org/wikipedia/commons/b/b3/Ostafrikanisches_Spitzmaulnashorn.JPG" style="width:256px; cursor: pointer;" />
</a>

Try copying the javascript code into one of your pages, and then add the button code and see how it works.