If I wish to change the opacity
of a <div>
irregularly over time, I can use CSS animation
and @keyframes
:
.myDiv {
animation: myAnimation 10s linear;
}
@keyframes myAnimation {
0% {opacity: 1;}
80% {opacity: 1;}
81% {opacity: 0.99;}
100% {opacity: 0;}
}
}
But what if I want to change the volume
of an <audio class="my-audio">
element irregularly over time in an identical manner?
I know I can begin with:
var myAudio = document.getElementsByClassName('my-audio')[0];
myAudio.volume = 1.0;
But how can I change the volume
to 0.99
, when 81%
of the sound clip has played and fade uniformly down to a volume
to 0.0
, when 100%
of the sound clip has played?
Is there a javascript syntax for this kind of aural transition or am I looking for something which doesn't exist (yet)?
HTML 5 audio tags can be styled. By using the audio tag with “controls” attribute, the default browsers player is used. You can customize by not using the browsers controls. You can also add CSS classes to each one of the elements and style them accordingly.
Hello everyone, In this post, we will examine how to solve the How You Can Use Javascript To Play The Sound For The Button Color Selected problem using the computer language. var audio = new Audio("play. mp3"); audio. play();
There are three supported audio formats in HTML: MP3, WAV, and OGG.
The <audio> HTML element is used to embed sound content in documents. It may contain one or more audio sources, represented using the src attribute or the <source> element: the browser will choose the most suitable one. It can also be the destination for streamed media, using a MediaStream .
I guarantee there is a better way of doing this, both performance wise and simplicity. However, here is my attempt of solving this case if I understood your question correct:
var myAudio = document.getElementsByClassName('my-audio')[0];
myAudio.onloadedmetadata = function() {
myAudio.ontimeupdate = function() {
fadeVolume(kFrame)
};
};
var kFrame = {
0: 0,
10: .10,
20: .20,
30: .30,
40: .40,
50: .50,
60: 0
}
function fadeVolume(settings) {
if (settings) {
var keys = Object.keys(settings);
var duration = myAudio.duration;
var currentTime = myAudio.currentTime;
var percentage = (currentTime / duration) * 100;
keys.forEach(key => {
if (key <= percentage) {
myAudio.volume = settings[key];
}
})
}
}
<audio class="my-audio" controls>
<source src="https://www.w3schools.com/tags/mov_bbb.mp4" type="audio/ogg">
</audio>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With