Issue
I have the following HTML:
<audio autoplay id="background_audio">
<source src="https://sporedev.ro/pleiade/hol.mp3" type="audio/mpeg">
</audio>
The code above plays some music in the background.
<audio autoplay>
<source src="https://sporedev.ro/pleiade/sounds/swoosh-enter.mp3" type="audio/mpeg">
</audio>
This code plays a swoosh sound when the user enters the page.
And I have the following JS:
<script>
var audio = document.getElementById('background_audio');
document.getElementById('mute').addEventListener('click', function (e)
{
e = e || window.event;
audio.muted = !audio.muted;
e.preventDefault();
}, false);
</script>
This code is used to mute the background music when the user clicks on a certain div.
Here's a JSFiddle.
The link to the project I'm working at is here.
I'm trying to create a script that won't play the audio
located in the background_audio
id until a certain ammount of seconds (for example's sake, 5s) have passed so that the swoosh sound can finish playing before starting the music.
I did some research on SO and Google and camed to the conclusion that some use of preventDefault()
would be the solution however I fail to implement the solution.
How can I make the music in the background_audio
id after the swoosh sound have finished playing?
Solution
You can use onended
events, play your second audio after first one ended.
var audio1 = document.getElementById("another_audio");
audio1.onended = function() {
console.log('Playing background audio')
var audio2 = document.getElementById("background_audio");
audio2.play();
};
<audio id="background_audio">
<source src="https://sporedev.ro/pleiade/hol.mp3" type="audio/mpeg">
</audio>
<audio autoplay id="another_audio">
<source src="https://sporedev.ro/pleiade/sounds/swoosh-enter.mp3" type="audio/mpeg">
</audio>
Answered By - Durga
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.