chintan9 / plyr-react

A simple, accessible and customisable react media player for Video, Audio, YouTube and Vimeo

Home Page:https://github.com/chintan9/plyr-react

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Cant detect when video has ended in nextjs

willzfrank opened this issue · comments

I am attempting to detect when a video ends and trigger a specific behavior using a prop. However, the code I have doesn't seem to be working. Even the console log I added inside the function is not appearing. Can someone help me understand why?

Here's the code I am using:

useEffect(() => {
if (videoRef.current) {
console.log('Starting');

videoRef.current.restart();
videoRef.current.on('ended', function (event: any) {
  props.onVideoEnded && props.onVideoEnded();
  console.log('Ending');
});

}
}, []);


and here is the full code import React, { useRef, useEffect, useState } from 'react';
import styles from './videoplayer.module.css';
import { motion } from 'framer-motion';
import Plyr from 'plyr-react';
import 'plyr-react/plyr.css';

interface VideoPlayerProps {
  src: string | SourceInfo[];
  title?: string;
  description?: string;
  posterUrl?: string;
  subtitleUrl?: string;
  className?: string;
  onVideoEnded?: () => void;
}

interface SourceInfo {
  src: string;
  type: string;
}

function VideoCoursePlayer(props: VideoPlayerProps): JSX.Element {
  const [videoSrc, setVideoSrc] = useState<SourceInfo[]>([]);
  const videoRef = useRef<any>(null);

  useEffect(() => {
    if (props.src) {
      setVideoSrc(
        Array.isArray(props.src) ? props.src : [{ src: props.src, type: '' }]
      );
    }
  }, [props.src]);

  useEffect(() => {
    if (videoRef.current) {
      console.log('starting');

      videoRef.current.restart();
      videoRef.current.on('ended', function (event: any) {
        props.onVideoEnded && props.onVideoEnded();
        console.log('ending');
      });
    }
  }, []);

  return (
    <div className="w-full">
      <motion.div>
        <h6 className="capitalize inter">{props.title}</h6>
        <div>
          <div>
            <Plyr
              options={{
                ratio: '16:9',
              }}
              source={{
                type: 'video',
                sources: videoSrc,
              }}
              ref={videoRef}
              onEnded={() => {
                props.onVideoEnded && props.onVideoEnded();
                console.log('ending');
              }}
            />
          </div>
        </div>
      </motion.div>
    </div>
  );
}

export default VideoCoursePlayer;


I would appreciate any assistance in figuring out why the video ending detection is not functioning as expected."