Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Audio - Sound only plays once

I am using Chrome and this is my code:

<audio id="letter_audio" src="audio/bomb.mp3" type="audio/mp3" preload="auto"></audio>

    $('.sound').live('click', function () {

        var sound = $("#letter_audio")[0];  

        sound.pause();
        sound.currentTime = 0;
        sound.play();

        return false;
    });

How come the sound plays the first time I click on play. then when I click again, it pauses, like the code goes. but the it justs stays on pause? i want it to play, then when i click on it again, go back to 0 and play again as in the code?

like image 941
Harry Avatar asked Feb 17 '12 21:02

Harry


People also ask

What is the correct HTML5 element for playing audio files?

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

Can I play audio in HTML5?

HTML5 features include native audio and video support without the need for Flash. The HTML5 <audio> and <video> tags make it simple to add media to a website. You need to set src attribute to identify the media source and include a controls attribute so the user can play and pause the media.

Does HTML5 support MP3?

The most supported codecs for playing audio in HTML5 are Ogg Vorbis, MP3, and Wav. There is currently no single codec that plays across all browsers. To get around the potential for codec incompatibility, HTML5 allows you to specify multiple source files.

How do I embed a sound in HTML?

To embed audio in HTML, we use the <audio> tag. Before HTML5, audio cannot be added to web pages in the Internet Explorer era. To play audio, we used web plugins like Flash. After the release of HTML5, it is possible.


2 Answers

I've had similar problems replaying audio, but managed to solve it by calling the load() method before the play() call. Try this:

$('.sound').live('click', function () {
    var sound = $("#letter_audio")[0];

    sound.load();
    sound.play();

    return false;
});

I think this is better than resetting the src attribute for two reasons:

  1. Keeps the src value in the page content, rather than in the JavaScript
  2. Works when you embed multiple <source> elements of different audio formats:

    <audio id="letter_audio">
       <source src="audio/bomb.mp3" type="audio/mp3" preload="auto"/>
       <source src="audio/bomb.ogg" type="audio/ogg" preload="auto"/>
    </audio>
    
like image 92
Tom Avatar answered Oct 23 '22 07:10

Tom


try this.. basically, resetting the src attribute should reset the audio as desired.

$('.sound').live('click', function () {

    var sound = $("#letter_audio")[0];  

    sound.src = "audio/bomb.mp3";
    sound.play();

    return false;
});
like image 32
Lloyd Avatar answered Oct 23 '22 09:10

Lloyd