Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playing Audio in HTML

I want to play a mp3 audio file in HTML. I don't want to display the whole player with controls like Volume etc. I just need a play/pause button, Designed by me, not the core design of some player, like yahoo player, or google one.

For example the audio will be autoplay. When a button (probably an image) is clicked it will pause, and when that image is clicked again, the audio will play again.

There are quite few examples here : http://www.w3schools.com/html/html_sounds.asp

Can I control any of them to play/stop from JS code ?

like image 202
Sohail Avatar asked Dec 27 '11 05:12

Sohail


People also ask

Can I play audio in HTML?

The HTML <audio> element is used to play an audio file on a web page.

How do I connect audio in HTML?

Linking to a sound file using a href allows a browser to open and play an audio file if the viewer of your web page has properly configured their Internet browser. You can also use the <embed> tag or the newer <audio> tag to insert a sound file directly into a web page.

What is the correct HTML for playing audio?

The <audio> HTML element is used to embed sound content in documents. It may contain one or more audio sources, represented using the src attribute or the <source> element: the browser will choose the most suitable one. It can also be the destination for streamed media, using a MediaStream .

How do I get HTML audio to play on my website?

Complete HTML/CSS Course 2022 To play sound file in the background on a web page, use the <embed>… </embed> element. Also, use the autoplay attribute. This will run music in the background whenever the page loads.


2 Answers

You can use the html5 audio tag. You can specify your own controls for playback.

<audio preload="auto" autobuffer> 
  <source src="elvis.mp3" />
  <source src="elvis.wav" /> <!-- fallback if no mp3 support in browser -->
</audio>

This is a jQuery solution.

http://jsfiddle.net/QPW27/109/

This is what your non-jQuery solution would look like.

var foo = document.getElementById('player');
foo.pause();  //just bind play/pause to some onclick events on your page
foo.play();

Different browsers support different audio formats. You can specify fallback audio versions though. This website has a nice chart of browser support as of July 2011.

like image 68
mrtsherman Avatar answered Oct 21 '22 14:10

mrtsherman


Hopefully, in a few years, the HTML5 audio API will be supported accross more browsers, but currently, playing sounds requires either a lot of browser-specific hacks to get things working, or reliance on a browser plugin like flash.

In the meantime, I reccomend using SoundManager2. It's fairly easy to work with and will involve much less headache than doing it yourself.

like image 22
Peter Olson Avatar answered Oct 21 '22 16:10

Peter Olson