Embedding Audio in an HTML5 Document

2 posts Page 1 of 1
Contributors
User avatar
comathi
Coding God
Coding God
Posts: 1242
Joined: Fri Mar 26, 2010 1:59 pm

Embedding Audio in an HTML5 Document
comathi
Hello guys,

Once again, I'll be making a quick HTML5 tutorial, this time about how to embed audio to an HTML5 document.

As I've said in previous tutorials, HTML5 brings simpler tags, and more meaning to the code. That said, embedding audio to a webpage is no more complicated than using the <audio> and </audio> tags.

Now, there is one unfortunate drawback: not all browsers support the same audio formats, as you can see below:

AAC (mp3): supported by IE, Safari and Chrome
OGG: supported by Firefox, Opera and Chrome


This means you can either choose the browser you want to support best, or include both to insure cross-browser compatibility.

Let's get to the code!

Start by making a simple HTML5 document. You can find out by reading my previous tutorial here.

In the body section of the document, you'll want to add an <audio> tag. Then, give it a 'controls' attribute, like so:
Code: Select all
<audio controls>  </audio>
Now, between the <audio> and </audio> tags, we'll want to put the source of our audio. This will be done inside a <source> tag.
Code: Select all
<audio> <source src="filename.mp3" type="audio/mpeg" />
Notice the first attribute is set to "filename.mp3". This defines the path to the resource. Secondly, you'll see that the 'type' attribute is set to "audio/mpeg". This is because our file is of the mp3 type. If you were to link to an ogg file, you would put "audio/ogg" instead.

That's it! You'll now be able to play audio in your HTML5 document.

Enjoy!
User avatar
smashapps
Coding Guru
Coding Guru
Posts: 961
Joined: Tue Apr 05, 2011 8:41 am

You would think that mp3 would be supported by more web browsers considering that most people use it, how many people will use a .ogg music file? I thought ogg was for games etc well than again HTML5 can be used for games and that (even seen a Nes/Snes rom emulator all programmed with the HTML5 canvas)

well once again Comathi another great tutorial, I haven't really done much in HTML5 but maybe when I get my new laptop I will post some tutorials planning on learning how to create games and that will be interesting.

(Would +rep but I've just given -rep to a member)
My name is Tom | Visit my blog where I post new content every day! Tom's Daily Blog | MineCraft is awesome!
2 posts Page 1 of 1
Return to “Tutorials”