javascriptjqueryhtmlaudio

HTML 5 <audio> - Play file at certain time point


I have a simple auto playing snippet that plays the audio file however I was wondering either in JavaScript or as an attribute play that file at a certain time (ex. 3:26).

<script type="text/javascript">
    var myAudio=document.getElementById('audio2')
    myAudio.oncanplaythrough=function(){this.play();}
</script>

<audio id="audio2" 
       preload="auto" 
       src="file.mp3" 
       oncanplaythrough="this.play();">
</audio>

Any help would be great. Thanks in advance :)


Solution

  • A few things... your script will first need to be after the audio tag.

    Also you don't need the oncanplaythough attribute on the audio tag since you're using JavaScript to handle this.

    Moreover, oncanplaythrough is an event, not a method. Let's add a listener for it, which will instead use canplaythough. Take a look at this:

    <audio id="audio2" 
       preload="auto" 
       src="http://upload.wikimedia.org/wikipedia/commons/a/a9/Tromboon-sample.ogg" >
    
       <p>Your browser does not support the audio element</p>
    </audio>
    
    <script>
      myAudio=document.getElementById('audio2');
      myAudio.addEventListener('canplaythrough', function() {
        this.currentTime = 12;
        this.play();
      });
    </script>
    

    And finally, to start the song at a specific point, simply set currentTime before you actually play the file. Here I have it set to 12 seconds so it will be audible in this example, for 3:26 you would use 206 (seconds).

    Check out the live demo: http://jsfiddle.net/mNPCP/4/


    EDIT: It appears that currentTime may improperly be implemented in browsers other than Firefox. According to resolution of this filed W3C bug, when currentTime is set it should then fire the canplay and canplaythrough events. This means in our example, Firefox would play the first second or so of the audio track indefinitely, never continuing playback. I came up with this quick workaround, let's change

    this.currentTime = 12;
    

    to test to see if it has already been set, and hence preventing the canplaythrough to get called repeatedly:

    if(this.currentTime < 12){this.currentTime = 12;}
    

    This interpretation of the spec is still currently being disputed, but for now this implementation should work on most modern browsers with support for HTML5 audio.

    The updated jsFiddle: http://jsfiddle.net/mNPCP/5/