Using HTML to play Audio Clip

I would like to add a small audio clip to my client’s home page that users can play if they so choose.

Is there a way to do this using just HTML without diving into Flash and JavaScript and all that?

I was thinking of having a small image that users could click on to start the audio clip. (Having some sort of player with Start, Stop, Rewind would be even better!)

Add controls attribute to HTML5 <audio> tag and browser will show small player for your sounds:

<audio controls>
    <source src="sound.ogg" type="audio/ogg">
    <source src="sound.mp3" type="audio/mpeg">
</audio>

If you want it to be playable with image click then you have to use javascript:

<audio id="my_sound">
    <source src="sound.ogg" type="audio/ogg">
    <source src="sound.mp3" type="audio/mpeg">
</audio>

<img src="play.png" onclick="play()">

<script>
    function play(){
        var sound = document.getElementById("my_sound");
        sound.play();
    }
</script>
3 Likes

@megazoid,

Here is what I tried last night…

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <!-- HTML Metadata -->
    <title>Some Page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="description" content="Listen to a wolf howling!" />
</head>
<body>
    <audio controls>
        <source src="/audio/wolf-01.ogg" type="audio/ogg" />
        <source src="/audio/wolf-01.mp3" type="audio/mpeg" />
        Your browser does not support the audio element.
    </audio>
</body>

Here is what happens…
FireFox: I see an audio control flash on my screen and then disappear. (Adding the .ogg option was supposed to fix this!)

Chrome: I see see an audio control which looks good…

But when I click on “Play”, it turns grey and nothing happens.

Opera: The audio control is greyed out by default.

Safari: I get a control that appears to work, but I can’t hear anything.


I’m sure there are lots of fancy ways to do this using JavaScript and Flash, but since this is a “last minute” client request, I’m not to motivated to have to learn technologies on-the-fly that I don’t know.

I thought playing a simple audio clip was around since the 1990s on the WWW? :confused:

Looks like it can’t find suitable file to play. Check your paths

I hereby nominate myself for “Idiot of the Week” award.

It turns out that my “audio” directory was in another work area and that I didn’t actually have an “audio” directory or files in my “public_html” directory.

:blush:

Fixed that tiny issue, and now my audio clip plays in all four browsers mentioned above! Doh!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.