Home > other >  Use play() video method with audio muted
Use play() video method with audio muted

Time:11-24

I added a play button to an HTML background video on my site so users can choose to play video or not. Video was added with code below:

<video id="mobilevideo" class="video-full" loop muted playsinline>
  <source src="<?php echo esc_url( $videofile ); ?>" type="video/mp4">Your browser does not support the video tag.
</video>

I added the control buttons and styled them so the icons can change from play to pause as the user toggles the button. I did same for mute and unmute.

<a class="playcontrol" href="#">
    <img src="<?php echo $pause; ?>" width="18" height="" alt="overlay" class="play">
    <img src="<?php echo $play; ?>" width="18" height="" alt="overlay" class="pause">
</a>
<a class="soundcontrol" href="#">
    <img src="<?php echo $pause; ?>" width="18" height="" alt="overlay" class="unmute">
    <img src="<?php echo $play; ?>" width="18" height="" alt="overlay" class="mute">
</a>

I however do not want the audio to play by itself. I want users to be able to click another button to enable audio or not.

var mobileVideo = document.getElementById("mobilevideo"); 
$(".video-mobile video").prop('muted', true);

$(".video-mobile .playcontrol").click(function () { 
    if (mobileVideo.paused) {
        mobileVideo.muted = true;
        mobileVideo.play(); 
        $(this).addClass('playsound'); // changing icon for button
    } else {
        mobileVideo.pause(); 
        $(this).removeClass('playsound'); // changing icon for button
    }
});

$(".video-mobile .sound-control").click(function () {
    if ($(".video-mobile video").prop('muted')) {
        $(".video-mobile video").prop('muted', false);
        $(this).addClass('playsound'); // changing icon for button
    } else {
        $(".video-mobile video").prop('muted', true);
        $(this).removeClass('playsound'); // changing icon for button
    }
}); 

The problem I have is that although both buttons work well. The play button causes the video to be unmuted when clicked. I do not want that but I am not sure how to make the play button only control play and pause without the audio while the other button would control the audio.

Any suggestion is appreciated.

CodePudding user response:

Eventually sorted this out by using Video Event. Removed the line - mobileVideo.muted = true; and added below to the script to mute the video once it starts playing:

mobileVideo.addEventListener('play', (event) => {
    mobileVideo.muted = true;
}); 

Still play a few milliseconds before the function kicks in but it works overall. It's barely noticeable. Suggestion to fine-tune this is welcome though.

CodePudding user response:

You could try using the volume property and set it to 0. It’s an interval between 0-1. In this case it would be: mobileVideo.volume = 0;.

  • Related