Activating sound in video background html page

Asked

Viewed 492 times

1

I have a question, it seems simple, and I believe it is: I have a video that I use as background, and it has the attribute "mute" to run in the browsers, but I want to provide a button for the user to activate the sound. But I’ve tried several ways to enable sound through javascript, but.... so far.... Who’s been through this, and can help...

Follow the code below:

<script type="text/javascript" >
var vid=document.getElementById("audio");
function aumentasom() {
    vid.volume+=0.2;
    }
</script>  

X S

1 answer

1


Man, I got it done here in parts. I do not know if there is any 100% safe way to solve this, because for reasons of user preference, UX and even security, in videos with sound Autoplay does not usually work.

What I did was put autoplay and muted in the video, and then in a function setTimeout() I remove the attribute muted, but eventually you might make that mistake

inserir a descrição da imagem aqui

See more: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

This error occurs only in Chrome. In Firefox and Edge audio appears even without user interaction. (in Safari I can’t say, even in mobile browsers, I don’t have a test environment for this)

But however here is an example that can work there and is worth testing.

Attention in Chrome:
Note that when you click on run below, if you DO NOT interact on the page, either by clicking somewhere, giving scroll or else the video will give the error described above and will pause. But if there is qq interaction on page o muted will be removed and the video starts to have audio after 2000ms. So this code only works if the user clicks on something, drags something, writes something scroll on the page within that 2 second interval, or else the video will pause.

OBS: Scroll with the mouse wheel will not be a "enough" interaction to avoid video landing, you will need scrollar with the scroll of the window by clicking...

const vid = document.getElementById('vv');

setTimeout(
    function () {
        vid.muted = false;
    }
, 2000);
<br>
<br><input type="text" name="" id="">
<br><input type="checkbox" name="" id="">
<br>
<video id="vv" muted width="320" height="240" autoplay>
    <source src="https://www.w3schools.com/html/movie.mp4" type="video/mp4">
</video>
<br>
<br>
<br>
<br>
<br>
<br>

  • Thanks, it worked out....

  • @Josildooliveira has done well consider marking the Reply as accepted by clicking on this icon below the Little Arrows next to my reply. Worth the strength, success!

Browser other questions tagged

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