Skip to content Skip to sidebar Skip to footer

How To Set The Duration Of Audio

I am trying to set the duration of an audio tag using HTML DOM duration property of audio. I have tried the following but it doesn't seem to work: $('audio')[0].duration = 1; I've

Solution 1:

I wanted to share how I solved. Hope this helps you. Assume you have an audio element in your HTML (which you can hide):

<audio src="source_to_audio_file.mp3" controls="controls"id="audio_el"type="audio/mpeg"></audio>

You have another element used to start the play of the audio:

<div><aonclick="play_audio('audio_el',audio_element,2.01,3.2);"></a></div>

The function play_audio is below and it takes three parameters: audio_element,time_start,duration

When the element starts to play, the property value of the audio element is set to the duration given. You will then use this in the timeupdate event to pause the audio.

In the script:

var player = document.getElementById("audio_el");  
player.addEventListener("timeupdate", function() {
if (player.currentTime - player._startTime >= player.value){    
      player.pause(); 
 };

});

functionplay_audio(audio_element,time_start,duration){
var player = document.getElementById(audio_element);
player.value=duration;
player._startTime=time_start;
player.currentTime = time_start;  
player.play();
}

Solution 2:

sound = newHowl({

    src: ['./assets/audio/classic_bell.mp3'], //you can set the custom path 
                                       **OR** 
    src : ['http://...../your url/mp3file.mp3'], //you can also set the url path to set 
                                                 the audio                                                        loop: true,
  });

//in method where you want to play the soundthis.sound.play();

 setTimeout(()=> {

      this.sound.stop();

  }, 1000);

Post a Comment for "How To Set The Duration Of Audio"