Harry M
Harry M

Reputation: 42

Autoplay for multiple video elements on one page

I'm trying to add a featured video to my archive product page in woocommerce.

The only issue I'm having is that only one video autoplays and the others are just paused. When I have one video on the page, it just plays perfectly, as soon as I add a second one it just pauses.

I'm unsure if this has to do with browser autoplay policies or just a mistake in my code / video parameters.

Console throws the error: Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause().

Is there a workaround for this?

I've seen multiple examples where this is the case, for example: https://marcopanconesi.com/collections/all

 <?php

                        // Display either the featured video or the post thumbnail
                        if ($featured_video_mp4) {
                            // If featured video exists, display the video using video shortcode
                            $attr = array(
                                'src'      => $featured_video_mp4,
                                'preload'  => true,
                                'loop'     => true,
                                'controls' => '',
                                'muted'    => true,
                                'autoplay' => true,
                            );

                            echo '<div class="relative w-full h-full bg-black">';

                            // Display the featured video shortcode
                            echo wp_video_shortcode($attr);
                            echo '</div>';
                        } else {
                            // Otherwise, display the post thumbnail
                            the_post_thumbnail('medium', ['class' => 'w-full']);
                        }
                        ?>

I tried to force play the videos with jQuery, without any result, the videos still stay paused on the page.

    jQuery(document).ready(function() {
      // Select all video elements
      jQuery('.wp-video-shortcode').each(function(index, video) {
        var videoElement = jQuery(video)[0]; 
        
        jQuery(videoElement).on('canplaythrough', function() {
          jQuery(this).get(0).play();
        });
    
        videoElement.load();
        
      });
    });

Upvotes: 0

Views: 154

Answers (1)

Harry M
Harry M

Reputation: 42

I've found the answer to my own question. For anyone struggling with the same issue, it's better to drop the built-in wordpress oembed shortcode and use the video tag directly, as seen in this example:

echo '<video class="autoplay-loop-video" muted loop autoplay>';
echo '<source src="' . esc_url($featured_video_mp4) . '" type="video/mp4">';
echo 'Your browser does not support the video tag.';
echo '</video>';

Upvotes: 1

Related Questions