Autoplay Video with Sound

Viewed 16851

I am a beginner in HTML and just want to write a page with a little video and a text. I want to autoplay the video but with sound. Since it's only possible to autoplay without sound I assume that I need javascript.

This is my code so far

index.html

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="generic.css">
    </head>
    <body>
        <video autoplay="autoplay" loop="" class="myVideo" id="myVideo">
            <source src="vid.mp4" type="video/mp4">
            Your browser does not support HTML5 video.
          </video> 
    </body>
</html>

css file:

video {
    position: fixed;
    text-align: center;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}

Is it somehow possible or am I forced to use a button to autoplay?

2 Answers

Your code is correct, But here are google's poilcy Chrome's autoplay policies are simple:

Muted autoplay is always allowed.

  • Autoplay with sound is allowed if:
  • User has interacted with the domain (click, tap, etc.).
  • On desktop, the user's Media Engagement Index threshold has been crossed, meaning the user has previously played video with sound. The user has added the site to their home screen on mobile or installed the PWA on desktop.

TRY INTREACT WITH SNIPPET BEFORE VIDEO LOADS

video {
    position: fixed;
    text-align: center;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
}
<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="generic.css">
    </head>
    <body>
        <video autoplay="autoplay" loop="" class="myVideo" id="myVideo">
            <source src="https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4" type="video/mp4">
            Your browser does not support HTML5 video.
          </video> 
    </body>
</html>

A hacky trick I've seen people use is add an iframe containing an autoplay material before the element itself thus forcing subsequent elements to have audio. You can check something like it done here.

<iframe src="SOME_EMPTY_VIDEO_WITH_SILENCE_URL" type="video/mp4" allow="autoplay" id="video" style="display:none"></iframe>
<video autoplay>
     <source src="ACTUAL_VIDEO_URL" type="video/mp4">
</video>

Still, like I said, this is a nasty hack.

Related