2

I am working on an SPA with Vue 3, TypeScript and The Movie Database (TMDB). I use also use Bootstrap 5 for the UI.

With the intention of displaying movie trailers on the movie details page, I have made the TrailerCarousel.vue component:

<template>
  <div
    id="trailersCarousel"
    class="carousel slide"
    data-bs-interval="false"
  >
    <ol v-if="movieTrailers.length > 1" class="carousel-indicators">
      <li
        v-for="(video, index) in movieTrailers.slice(0, maxCarouselItems)"
        :key="video.id"
        data-bs-target="#trailersCarousel"
        :data-bs-slide-to="`${index}`"
        :class="{ active: index === 0 }"
      >
        {{ index + 1 }}
      </li>
    </ol>

    <div class="carousel-inner">
      <div
        v-for="(video, index) in movieTrailers.slice(0, maxCarouselItems)"
        :key="video.id"
        class="carousel-item"
        :class="{ active: index === 0 }"
      >
        <iframe
          class="embed-responsive-item"
          :src="`https://www.youtube.com/embed/${video.key}`"
        ></iframe>
      </div>
    </div>

    <button
      v-if="movieTrailers.length > 1"
      class="carousel-control-prev"
      type="button"
      data-bs-target="#trailersCarousel"
      data-bs-slide="prev"
    >
      <span class="carousel-control-prev-icon"></span>
    </button>

    <button
      v-if="movieTrailers.length > 1"
      class="carousel-control-next"
      type="button"
      data-bs-target="#trailersCarousel"
      data-bs-slide="next"
    >
      <span class="carousel-control-next-icon"></span>
    </button>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
  name: "TrailerCarousel",

  props: {
    movieTrailers: Array,
  },

  data() {
    return {
      maxCarouselItems: 5
    } 
  },
});
</script>

<style scoped lang="scss">
.carousel-indicators {
  li {
    text-indent: 0;
    margin: 0 2px;
    font-size: 12px;
    width: 26px;
    height: 26px;
    line-height: 26px;
    text-align: center;
    border: none;
    border-radius: 50%;
    color: #333;
    background-color: #fff;
    transition: all 0.25s ease;
    &.active,
    &:hover {
      margin: 0 2px;
      background-color: #0b8a52;
      color: #fff;
    }
  }
}

.carousel-control-next,
.carousel-control-prev {
  width: 7.5%;
}

.carousel-item {
  padding-top: 56.25%;
  height: 0px;
  position: relative;
}

iframe {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}
</style>

I use the the above component in src\components\MovieDetails.vue:

<div v-if="movieTrailers.length" class="mb-3">
    <h2 class="section-title">Trailers</h2>
    <TrailerCarousel :movieTrailers = "movieTrailers" />
</div>

Stackblitz

I have put together a Stackblitz with the code.

Note that the "www.youtube.com refused to connect" error is only present on Stackblitz (for a reason I was unable to figure out).

The problem

When navigating from a trailer to another and playing them, the one previously playing does not stop and they overlap by that I mean that the sound overlaps.

I have been unable to find a way to prevent that.

What would be a reliable way to achieve the desired result?

Razvan Zamfir
  • 4,209
  • 6
  • 38
  • 252

3 Answers3

1

There are many ways to solve that I guess. One way would be to pause the video iframe. Didn't try but I believe something like the following would work:

const previousActiveIframe = document.querySelectorAll('.carousel-item.active iframe') as HTMLIFrameElement

previousActiveIframe?.contentWindow?.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*')

But another easy solution is to just re-render the iframe when the slide changes:

  data() {
    return {
      maxCarouselItems: 5,
      iframeRendererCount: 0, // 
    }
  },

  methods: {
    onSlideChange() {
      this.iframeRendererCount++
    }
}
<iframe
  :key="iframeRendererCount"
  :src="`https://www.youtube.com/embed/${video.key}`"
  frameborder="0"
  allowfullscreen
></iframe>
Roland
  • 24,554
  • 4
  • 99
  • 97
1

The most reliable way to resolve this issue is to use Youtube IFrame Player API. You can control Youtube videos in a standard way.

To do this, first install the package youtube-player package in your project:

npm install youtube-player

Then, replace your component content TrailerCarousel.vue with the following code:

<template>
  <div id="trailersCarousel" class="carousel slide" data-bs-interval="false">
    <ol v-if="movieTrailers.length > 1" class="carousel-indicators">
      <li v-for="(video, index) in movieTrailers.slice(0, maxCarouselItems)" :key="video.id"
        data-bs-target="#trailersCarousel" :data-bs-slide-to="`${index}`" :class="{ active: index === 0 }">
        {{ index + 1 }}
      </li>
    </ol>

    <div class="carousel-inner">
      <!-- Add `ref` to div element to get reference to it in script -->
      <div v-for="(video, index) in movieTrailers.slice(0, maxCarouselItems)" :key="video.id" class="carousel-item"
        :class="{ active: index === 0 }" :ref="el => itemRefs.push(el)" :data-id="video.key">
        <!-- <iframe class="embed-responsive-item" :src="`https://www.youtube.com/embed/${video.key}`"></iframe> -->
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import YT from "youtube-player";

export default defineComponent({
  name: "TrailerCarousel",

  props: {
    movieTrailers: {
      type: Array,
      required: true,
    },
  },

  data() {
    return {
      maxCarouselItems: 5,

      // Create an array to store references to each carousel item
      itemRefs: [] as HTMLElement[],
    };
  },

  mounted() {

    /**
     * @see https://developers.google.com/youtube/iframe_api_reference#Events
     */
    const stateNames = {
      unstarted: -1,
      ended: 0,
      playing: 1,
      paused: 2,
      buffering: 3,
      video_cued: 5,
    };

    // Create an array to store references to each youtube player
    const players = [] as any;

    this.itemRefs.forEach((itemRef) => {
      // get data-id attribute and pass it to youtube-player
      const videoId = itemRef.getAttribute("data-id");

      // create youtube player
      const youtubePlayer = YT(itemRef, {
        videoId: videoId || "",
        height: '500'
      });

      // Add player to players array
      players.push(youtubePlayer);

      youtubePlayer.on("ready", () => {
        // Handle ready state
      });

      youtubePlayer.on("stateChange", (event) => {
        // Nothing is playing, so don't do anything
        if (event.data == stateNames.playing) {
          return;
        }

        // Pause all other videos
        players.forEach(async (player: any) => {
          const state = await player.getPlayerState();
          if (state === stateNames.playing && player !== youtubePlayer) {
            player.pauseVideo();
          }
        });
      });

      youtubePlayer.on("error", (event) => {
        console.log("error", event);
      });
    });
  },
});



</script>

<style scoped lang="scss">
.carousel-indicators {
  margin-bottom: 10px;

  li {
    text-indent: 0;
    margin: 0 2px;
    font-size: 12px;
    width: 26px;
    height: 26px;
    line-height: 26px;
    text-align: center;
    border: none;
    border-radius: 50%;
    color: #333;
    background-color: #fff;
    transition: all 0.25s ease;

    &.active,
    &:hover {
      margin: 0 2px;
      background-color: #0b8a52;
      color: #fff;
    }
  }
}

.carousel-control-next,
.carousel-control-prev {
  width: 7.5%;
}

.carousel-item {
  padding-top: 56.25%;
  height: 0px;
  position: relative;
}

iframe {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}
</style>

I have commented the code to explain what I have added/modified. In short, I created an array of player references and once the status of any of them changes (start playing) then it will pause all other videos.

The code I provided is not production (although it is working). It needs stronger typing (I used any), error handling, event handling .. etc.

Sidenotes:

  • Since you are using vue3, the recommended build tool is vite.
  • Use setup in <script lang='ts'> and composition API for have less boilerplate code.
Kalimah
  • 11,217
  • 11
  • 43
  • 80
  • Can you add a Stackblitz (fork mine) so that we can all see hoe it works? Thanks! – Razvan Zamfir May 08 '23 at 06:18
  • Sure. But Stackblitz does not run youtube videos so you will need to download it – Kalimah May 08 '23 at 10:44
  • This is the fork on Stackblitz with the changes applied. https://stackblitz.com/edit/vue3-typescript-vue-cli-starter-6sqvnp?file=src%2Fcomponents%2FTrailerCarousel.vue – Kalimah May 10 '23 at 07:40
0

This is how it is implemented.

https://mdbootstrap.com/docs/standard/extended/video-carousel/

  • This solution doesn't stop or pause the videos. It only hides and silences them (with `display: none` and `.muted`). – tao May 04 '23 at 16:52