Reputation: 43
I have this code, but I do not know how to make the song start from 0:19 seconds. Could you help me out?
<div class="fin-subheading">
· ROLEPLAY ·
<audio id='music' volume='0.5' autoplay controls>
<source src="anonymous.mp3" type="audio/mpeg">
</audio>
</div>
<script>
var audio = document.getElementById("music");
audio.volume = 0.3;
</script>
Upvotes: 2
Views: 307
Reputation: 5237
You can specify a playback range in the src
attribute itself. See the docs here:
When specifying the URI of media for an or element, you can optionally include additional information to specify the portion of the media to play. To do this, append a hash mark ("#") followed by the media fragment description.
A time range is specified using the syntax:
#t=[starttime][,endtime]
So instead of:
<source src="anonymous.mp3" type="audio/mpeg">
simply put:
<source src="anonymous.mp3#t=n,m" type="audio/mpeg">
where n
and m
are the start and end times, respectively.
The range can also be unbounded as well. So you could, for instance do this:
<source src="anonymous.mp3#t=19" type="audio/mpeg">
which will start at 19 seconds and play through till the end; or even this:
<source src="anonymous.mp3#t=,19" type="audio/mpeg">
which will start from the beginning through 19 seconds.
Upvotes: 1
Reputation: 282
You can use currentTime
property
window.onload = function() {
const audio = document.getElementById("music");
audio.volume = 0.3;
audio.currentTime = 19;
audio.play();
}
Upvotes: 1
Reputation: 8098
You need to use canplaythrough
event and within that currentTime
and then play
when that time is reached.
Make sure you do not autoplay
in the audio tag in HTML.
<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 = 19;
this.play();
});
</script>
Upvotes: 0