Sometimes, we want to playback HTML audio with fade in and fade out with JavaScript.
In this article, we’ll look at how to playback HTML audio with fade in and fade out with JavaScript.
How to playback HTML audio with fade in and fade out with JavaScript?
To playback HTML audio with fade in and fade out with JavaScript, we can adjust the volume of the audio as it’s being played.
For instance, we write:
<audio id='audio' controls>
<source src="https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3" type="audio/mpeg">
</audio>
to add the audio element.
Then we write:
const sound = document.getElementById('audio');
const fadeAudio = setInterval(() => {
const fadePoint = sound.duration - 5;
if ((sound.currentTime >= fadePoint) && (sound.volume !== 0)) {
sound.volume -= 0.1
}
if (sound.volume < 0.003) {
clearInterval(fadeAudio);
}
}, 200);
We get the audio element with document.getElementById
.
Then we call setInterval
with a callback that gets the fadePoint
of the sound, which is the time near the end of the clip.
Then we check if sound.currentTime
is bigger than or equal to fadePoint
and sound.volume
isn’t 0.
sound.currentTime
is the current time of the sound clip.
If both are true
, then we reduce the volume by 0.1
And if sound.volume
is less than 0.003, then we call clearInterval
to stop reducing sound volume.
We run the callback every 200 seconds reduce the sound volume slowly to create the fading effect.
Conclusion
To playback HTML audio with fade in and fade out with JavaScript, we can adjust the volume of the audio as it’s being played.