Reputation: 2676
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 gone through other answers but I couldn't see any which make use of the duration property.
If the duration property is readonly, what other method does it leave me with?
Upvotes: 4
Views: 13045
Reputation: 21
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><a onclick="play_audio('audio_el',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();
};
});
function play_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();
}
Upvotes: 2
Reputation: 1
sound = new Howl({
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 sound
this.sound.play();
setTimeout(()=> {
this.sound.stop();
}, 1000);
Upvotes: 0
Reputation:
You cannot change the duration as it is locked to the original data (which cannot be changed via the audio element).
You can achieve the illusion of a different duration though by making restrictions on play by monitoring the time and pause the audio when a threshold kicks in:
timeupdate
event and check currentTime
against your thresholdrequestAnimationFrame
to poll the same value and do the same checkOn the loading side the browser will possibly load the entire file. If you want to control this part you would have to use Media Source Extension which allow you to control the buffering process.
Upvotes: 7