How to put the duration of a song in a css variable (html javascript css)

Asked

Viewed 107 times

0

Hello, I want to create a bar that shows the duration and current time of audio playback, for this I need to take the time of these audios and put in a variable to be used in a CSS property but I don’t know how to do this.

I was able to get the audio duration with javascript, but now I don’t know how to turn it into a variable to play on the CSS property:

html (in the javascript log appears "The sound has 143.096 seconds")

    <audio id="player" controls autoplay> <source src="musicas/CUAT.mp3" type="audio/mpeg"> Your browser does not support the audio element. </audio>
    <script>
        const som1 = document.getElementById("player");
        som1.onloadeddata = function() {
        console.log("O som tem " + som1.duration + " segundos");};
    </script>

css

div.progress::after {
 animation: loading "Duração do Áudio Aqui"s ease-in-out;
 background:#2A0A29;
 content: '';
 position: absolute;
 left: 0; top: 0; bottom: 0;
 border: 0.1px solid grey;
}

How can I put this audio duration that javascript gave me in a variable that I can put in the middle of css?

Edit: I got it Solved

  • OK, I’ve changed a little

  • Have you tried without using the event onloadeddata ? Try straight through console.log("O som tem " + som1.duration + " segundos");

  • You are right, is that my code was full of stuff there <javascript> was before the <audio> tag then he says that nothing loadou, but I put javascript after the <audio> tag and it worked, said so "The sound has 143.096 seconds". Now I just need to find a way to use this variable that contains the amount of seconds out of <javascript> to create my progress bar. Thank you for your attention ツ

  • @Yound this problem occurs because the element had not been rendered yet, so it would have to add the event load to the document or add the script always at the end of the document after all the elements. We focused so much on the part of recovering the duration that we did not pay attention to this fact rsrsrs.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.