How to use Canvas to show video buffer and current duration

Viewed 30

I am following Mozilla documentation for video and audio buffering using Canvas.

Instead of pure javascript I am using a react with typescript. In the documentation, they use windows.onload() event. So I am using its react alternate useEffect

useEffect(() => {
    const video = videoRef.current;
    const canvas = canvasRef.current;
    if (canvas && video) {
      var context = canvas.getContext("2d");
      if (context && video.duration) {
        context.fillStyle = "lightgray";
        context.fillRect(0, 0, canvas.width, canvas.height);
        context.fillStyle = "red";
        context.strokeStyle = "white";
        setInc(canvas.width / video.duration);
      }
    }
  }, []);

and for seeked event listener I am using the function onSeekedEvent

const onSeekedEvent = () => {
    const video = videoRef.current;
    const canvas = canvasRef.current;
    if (canvas && video) {
      var context = canvas.getContext("2d");
      if (context) {
        for (var i = 0; i < video.buffered.length; i++) {
          var startX = video.buffered.start(i) * inc;
          var endX = video.buffered.end(i) * inc;
          let width = endX - startX;
          context.fillRect(startX, 0, width, canvas.height);
          context.rect(startX, 0, width, canvas.height);
          context.stroke();
        }
      }
    }
  };
<div className="App">
      <video
        width="320"
        height="240"
        muted
        ref={videoRef}
        onSeeked={onSeekedEvent}
      >
        <source
          src="https://www.w3schools.com/html/movie.mp4"
          type="video/mp4"
        />
      </video>
      <div className={"canvasDiv"} ref={bufferDivRef}>
        <canvas className={"bufferCanvas"} ref={canvasRef}></canvas>
      </div>
      <button className={"btn"} onClick={playVideo}>
        Play
      </button>
      <button className={"btn"} onClick={stopVideo}>
        Pause
      </button>
    </div>

The problem is buffering and the current position is not working.

Here is my complete sandbox link

0 Answers
Related