如何在 React 中显示 YouTube 视频或任何带有 url Stream 的视频的选定部分?

问题描述 投票:0回答:1

我正在开发一个 React 应用程序,在其中使用自定义视频播放器组件流式传输 YouTube 视频。但是,我想通过仅显示视频流的选定部分来增强用户体验。本质上,我想隐藏视频播放器控件并将视频的可见部分限制为特定片段。我怎样才能实现这一目标?预先感谢!

这是我当前对视频流组件的实现:

     import React from 'react';
   import styled from 'styled-components';

 const VideoWrapper = styled.div`
 width: 100%;
  height: 100%;
 `;

const VideoPlayer = styled.iframe`
   width: 100%;
 height: 100%;
 border: 2px solid #76b900;
 border-radius: 8px;
   `;

  const VideoStream = () => {
 const videoLink = process.env.REACT_APP_VIDEO_LINK;
 const videoId = getYouTubeVideoId(videoLink);
 const embedUrl = `https://www.youtube.com/embed/${videoId}`;

  return (
  <VideoWrapper>
  <VideoPlayer src={embedUrl} allowFullScreen />
</VideoWrapper>
  );
 };

   function getYouTubeVideoId(url) {
  // Regular expression to extract the video ID from YouTube URL
  const regex = /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^/]+\/.+\/| 
 (?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
 const match = url.match(regex);
  if (match && match[1]) {
  return match[1];
 } else {
  throw new Error('Invalid YouTube URL');
 }
 }

 export default VideoStream;
reactjs iframe video-streaming
1个回答
0
投票

我之前做过类似的事情,你可以使用Youtube播放器api。

您应该能够为此交换代码:

 import React, { useEffect, useRef } from 'react';
    const VideoStream = () => {
    const videoRef = useRef(null);
    const videoLink = process.env.REACT_APP_VIDEO_LINK;
    const videoId = getYouTubeVideoId(videoLink);
    useEffect(() => {
    const tag = document.createElement('script');
    tag.src = 'https://www.youtube.com/iframe_api';
    const firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    window.onYouTubeIframeAPIReady = initializePlayer;

    return () => {
      window.onYouTubeIframeAPIReady = null;
    };
     }, []);
     const initializePlayer = () => {
    new window.YT.Player(videoRef.current, {
      videoId: videoId,
      playerVars: {
        autoplay: 1,
        controls: 0, 
        start: 30, 
        end: 90, 
      },
    });
    };
     return <div ref={videoRef}></div>;
    };
    function getYouTubeVideoId(url) {
    const regex = /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^/]+\/.+\/| 
     (?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
     const match = url.match(regex);
     if (match && match[1]) {
      return match[1];
      } else {
      throw new Error('Invalid YouTube URL');
     }
     }
    export default VideoStream;

然后您会在 constinitializePlayer 部分中看到,您有一个开始和结束,这明确了您希望视频开始和结束的秒数。

© www.soinside.com 2019 - 2024. All rights reserved.