首页 > 其他分享 >react-player学习

react-player学习

时间:2023-08-23 16:12:22浏览次数:50  
标签:学习 use ReactPlayer media when react player

一个适用于 react 的视频插件—react-player

说明文档 转载说明:来源于npm库中的readme.md 侵权删
调试工具地址: https://cookpete.com/react-player
1. 可以自动播放
2. 可以实现画中画、倍速、可控播放等功能

ReactPlayer

Latest npm version Build Status Test Coverage Become a sponsor on Patreon

A React component for playing a variety of URLs, including file paths, YouTube, Facebook, Twitch, SoundCloud, Streamable, Vimeo, Wistia, Mixcloud, DailyMotion and Kaltura. Not using React? No problem.

Migrating to ReactPlayer v2.0

ReactPlayer v2.0 changes single player imports and adds lazy loading players. Support for preload has also been removed, plus some other changes. See MIGRATING.md for information.

Usage

npm install react-player # or yarn add react-player
import React from "react";
import ReactPlayer from "react-player";

// Render a YouTube video player
<ReactPlayer url="https://www.youtube.com/watch?v=ysz5S6PUM-U" />;

By default, ReactPlayer supports many different types of url. If you only ever use one type, use imports such as react-player/youtube to reduce your bundle size. See config keys for all player keys.

import React from "react";
import ReactPlayer from "react-player/youtube";

// Only loads the YouTube player
<ReactPlayer url="https://www.youtube.com/watch?v=ysz5S6PUM-U" />;

If your build system supports import() statements, use react-player/lazy to lazy load the appropriate player for the url you pass in. This adds several reactPlayer chunks to your output, but reduces your main bundle size.

import React from "react";
import ReactPlayer from "react-player/lazy";

// Lazy load the YouTube player
<ReactPlayer url="https://www.youtube.com/watch?v=ysz5S6PUM-U" />;

Demo page: https://cookpete.com/react-player

The component parses a URL and loads in the appropriate markup and external SDKs to play media from various sources. Props can be passed in to control playback and react to events such as buffering or media ending. See the demo source for a full example.

For platforms without direct use of npm modules, a minified version of ReactPlayer is located in dist after installing. To generate this file yourself, checkout the repo and run npm run build:dist.

Polyfills

Autoplay

As of Chrome 66, videos must be muted in order to play automatically. Some players, like Facebook, cannot be unmuted until the user interacts with the video, so you may want to enable controls to allow users to unmute videos themselves. Please set muted={true}.

Props

Prop Description Default
url The url of a video or song to play
  ◦  Can be an array or MediaStream object
playing Set to true or false to pause or play the media false
loop Set to true or false to loop the media false
controls Set to true or false to display native player controls.
  ◦  For Vimeo videos, hiding controls must be enabled by the video owner.
false
light Set to true to show just the video thumbnail, which loads the full player on click
  ◦  Pass in an image URL to override the preview image
false
volume Set the volume of the player, between 0 and 1
  ◦  null uses default volume on all players #357
null
muted Mutes the player
  ◦  Only works if volume is set
false
playbackRate Set the playback rate of the player
  ◦  Only supported by YouTube, Wistia, and file paths
1
width Set the width of the player 640px
height Set the height of the player 360px
style Add inline styles to the root element {}
progressInterval The time between onProgress callbacks, in milliseconds 1000
playsinline Applies the playsinline attribute where supported false
pip Set to true or false to enable or disable picture-in-picture mode
  ◦  Only available when playing file URLs in certain browsers
false
stopOnUnmount If you are using pip you may want to use stopOnUnmount={false} to continue playing in picture-in-picture mode even after ReactPlayer unmounts true
fallback Element or component to use as a fallback if you are using lazy loading null
wrapper Element or component to use as the container element div
playIcon Element or component to use as the play icon in light mode
previewTabIndex Set the tab index to be used on light mode 0
config Override options for the various players, see config prop

Callback props

Callback props take a function that gets fired on various player events:

Prop Description
onReady Called when media is loaded and ready to play. If playing is set to true, media will play immediately
onStart Called when media starts playing
onPlay Called when media starts or resumes playing after pausing or buffering
onProgress Callback containing played and loaded progress as a fraction, and playedSeconds and loadedSeconds in seconds
  ◦  eg { played: 0.12, playedSeconds: 11.3, loaded: 0.34, loadedSeconds: 16.7 }
onDuration Callback containing duration of the media, in seconds
onPause Called when media is paused
onBuffer Called when media starts buffering
onBufferEnd Called when media has finished buffering
  ◦  Works for files, YouTube and Facebook
onSeek Called when media seeks with seconds parameter
onPlaybackRateChange Called when playback rate of the player changed
  ◦  Only supported by YouTube, Vimeo (if enabled), Wistia, and file paths
onEnded Called when media finishes playing
  ◦  Does not fire when loop is set to true
onError Called when an error occurs whilst attempting to play media
onClickPreview Called when user clicks the light mode preview
onEnablePIP Called when picture-in-picture mode is enabled
onDisablePIP Called when picture-in-picture mode is disabled

Config prop

There is a single config prop to override settings for each type of player:

<ReactPlayer
  url={url}
  config={{
    youtube: {
      playerVars: { showinfo: 1 },
    },
    facebook: {
      appId: "12345",
    },
  }}
/>

Settings for each player live under different keys:

Key Options
youtube playerVars: Override the default player vars
embedOptions: Override the default embed options
onUnstarted: Called when state changes to unstarted (usually when video fails to autoplay)
facebook appId: Your own Facebook app ID
version: Facebook SDK version
playerId: Override player ID for consistent server-side rendering (use with react-uid)
attributes: Extra data attributes to pass to the fb-video element
soundcloud options: Override the default player options
vimeo playerOptions: Override the default params
title: Set the player iframe title attribute
wistia options: Override the default player options
playerId: Override player ID for consistent server-side rendering (use with react-uid)
mixcloud options: Override the default player options
dailymotion params: Override the default player vars
twitch options: Override the default player options
playerId: Override player ID for consistent server-side rendering (use with react-uid)
file attributes: Apply element attributes
forceVideo: Always render a <video> element
forceAudio: Always render an <audio> element
forceHLS: Use hls.js for HLS streams
forceSafariHLS: Use hls.js for HLS streams, even on Safari
forceDASH: Always use dash.js for DASH streams
forceFLV: Always use flv.js
hlsOptions: Override the default hls.js options
hlsVersion: Override the hls.js version loaded from jsdelivr, default: 0.13.1
dashVersion: Override the dash.js version loaded from cdnjs, default: 2.9.2
flvVersion: Override the flv.js version loaded from jsdelivr, default: 1.5.0

Methods

Static Methods

Method Description
ReactPlayer.canPlay(url) Determine if a URL can be played. This does not detect media that is unplayable due to privacy settings, streaming permissions, etc. In that case, the onError prop will be invoked after attempting to play. Any URL that does not match any patterns will fall back to a native HTML5 media player.
ReactPlayer.canEnablePiP(url) Determine if a URL can be played in picture-in-picture mode
ReactPlayer.addCustomPlayer(CustomPlayer) Add a custom player. See Adding custom players
ReactPlayer.removeCustomPlayers() Remove any players that have been added using addCustomPlayer()

Instance Methods

Use ref to call instance methods on the player. See the demo app for an example of this.

Method Description
seekTo(amount, type) Seek to the given number of seconds, or fraction if amount is between 0 and 1
  ◦  type parameter lets you specify 'seconds' or 'fraction' to override default behaviour
getCurrentTime() Returns the number of seconds that have been played
  ◦  Returns null if unavailable
getSecondsLoaded() Returns the number of seconds that have been loaded
  ◦  Returns null if unavailable or unsupported
getDuration() Returns the duration (in seconds) of the currently playing media
  ◦  Returns null if duration is unavailable
getInternalPlayer() Returns the internal player of whatever is currently playing
  ◦  eg the YouTube player instance, or the <video> element when playing a video file
  ◦  Use getInternalPlayer('hls') to get the hls.js player
  ◦  Use getInternalPlayer('dash') to get the dash.js player
  ◦  Returns null if the internal player is unavailable
showPreview() When using light mode, returns to the preview overlay

Advanced Usage

Light player

The light prop will render a video thumbnail with simple play icon, and only load the full player once a user has interacted with the image. Noembed is used to fetch thumbnails for a video URL. Note that automatic thumbnail fetching for Facebook, Wistia, Mixcloud and file URLs are not supported, and ongoing support for other URLs is not guaranteed.

If you want to pass in your own thumbnail to use, set light to the image URL rather than true.

You can also pass a component through the light prop:

<ReactPlayer
  light={<img src="https://example.com/thumbnail.png" alt="Thumbnail" />}
/>

The styles for the preview image and play icon can be overridden by targeting the CSS classes react-player__preview, react-player__shadow and react-player__play-icon.

Responsive player

Set width and height to 100% and wrap the player in a fixed aspect ratio box to get a responsive player:

class ResponsivePlayer extends Component {
  render() {
    return (
      <div className="player-wrapper">
        <ReactPlayer
          className="react-player"
          url="https://www.youtube.com/watch?v=ysz5S6PUM-U"
          width="100%"
          height="100%"
        />
      </div>
    );
  }
}
.player-wrapper {
  position: relative;
  padding-top: 56.25%; /* Player ratio: 100 / (1280 / 720) */
}

.react-player {
  position: absolute;
  top: 0;
  left: 0;
}

See jsFiddle example

SDK Overrides

You can use your own version of any player SDK, assuming the correct window global is set before the player mounts. For example, to use a local version of hls.js, add <script src='/path/hls.js'></script> to your app. If window.Hls is available when ReactPlayer mounts, it will use that instead of loading hls.js from cdnjs. See #605 for more information.

Standalone player

If you aren’t using React, you can still render a player using the standalone library:

<script src="https://unpkg.com/react-player/dist/ReactPlayer.standalone.js"></script>
<script>
  const container = document.getElementById("container");
  const url = "https://www.youtube.com/watch?v=d46Azg3Pm4c";

  renderReactPlayer(container, { url, playing: true });

  function pausePlayer() {
    renderReactPlayer(container, { url, playing: false });
  }
</script>

See jsFiddle example

Adding custom players

If you have your own player that is compatible with ReactPlayer’s internal architecture, you can add it using addCustomPlayer:

import YourOwnPlayer from "./somewhere";
ReactPlayer.addCustomPlayer(YourOwnPlayer);

Use removeCustomPlayers to clear all custom players:

ReactPlayer.removeCustomPlayers();

It is your responsibility to ensure that custom players keep up with any internal changes to ReactPlayer in later versions.

Mobile considerations

Due to various restrictions, ReactPlayer is not guaranteed to function properly on mobile devices. The YouTube player documentation, for example, explains that certain mobile browsers require user interaction before playing:

The HTML5 <video> element, in certain mobile browsers (such as Chrome and Safari), only allows playback to take place if it’s initiated by a user interaction (such as tapping on the player).

Multiple Sources and Tracks

Passing an array of YouTube URLs to the url prop will load them as an untitled playlist.

<ReactPlayer
  url={[
    "https://www.youtube.com/watch?v=oUFJJNQGwhk",
    "https://www.youtube.com/watch?v=jNgP6d9HraI",
  ]}
/>

When playing file paths, an array of sources can be passed to the url prop to render multiple <source> tags.

<ReactPlayer playing url={["foo.webm", "foo.ogg"]} />

You can also specify a type for each source by using objects with src and type properties.

<ReactPlayer
  playing
  url={[
    { src: "foo.webm", type: "video/webm" },
    { src: "foo.ogg", type: "video/ogg" },
  ]}
/>

<track> elements for subtitles can be added using config.file:

<ReactPlayer
  playing
  url="foo.webm"
  config={{
    file: {
      tracks: [
        {
          kind: "subtitles",
          src: "subs/subtitles.en.vtt",
          srcLang: "en",
          default: true,
        },
        { kind: "subtitles", src: "subs/subtitles.ja.vtt", srcLang: "ja" },
        { kind: "subtitles", src: "subs/subtitles.de.vtt", srcLang: "de" },
      ],
    },
  }}
/>

Supported media

Contributing

See the contribution guidelines before creating a pull request.

Thanks


Jackson Doherty

Joseph Fung

标签:学习,use,ReactPlayer,media,when,react,player
From: https://www.cnblogs.com/gjzsa/p/17651937.html

相关文章

  • docker 命令学习
    1.dockerpullnginx 拉取镜像2.dockerrun -d -it --namenginx01-p4433:80nginx 运行容器3.dockerps查看运行的容器4.docker stop nginx01 停止容器5.dockerstart nginx01 启动容器6.dockerrmnginx01删除容器7.dockerstats 查看容器......
  • 网工学习(三)
    Wifi标准2.4G和5G优缺点对比-2.4G: -优点:兼容性好(所有设备都支持),抗衰性能强(穿墙能力强) -缺点:速度慢-5G: -优点:速度快 -缺点:兼容性差(老设备不支持),抗衰性差(穿墙能力若) -应用情况: -以前:2.4G是主流 -现在:5G是主流(要兼容老终端,无线网络......
  • vue3 和 react18 对比
    Vue3和React18是目前最新的版本,它们都是非常受欢迎的前端框架。下面是对Vue3和React18进行深度对比的一些关键点:组件模型:Vue3:Vue3采用了基于函数的组件模型,即使用setup函数来定义组件逻辑。这种方式更加直观和灵活,允许开发人员以更简洁的方式编写组件。React18:React18仍然......
  • Lnton羚通视频算法算力云平台【PyTorch】教程:学习基础知识如何保存和加载模型
    保存和加载模型是指将训练好的神经网络模型保存到文件中,以便在需要时重新加载该模型进行预测、推断或继续训练。保存模型的过程是将模型的参数和其他相关信息(如优化器状态等)保存到文件中。通过保存模型,我们可以在不重新训练的情况下保留模型的状态,方便后续使用。加载模型的过程是从......
  • Python基础入门学习笔记 077 GUI的终极选择:Tkinter14
    Tkinter提供了三种标准对话框模块,分别是:messagebox、filedialog、colorchoosermessagebox(消息对话框)实例1:askokcancel函数1fromtkinterimport*23print(messagebox.askokcancel("FishCDemo","发射核弹?"))45mainloop() 实例2:askquestion函数 实例3:asire......
  • Python基础入门学习笔记 074 GUI的终极选择:Tkinter11
    事件绑定对于每个组件来说,可以通过bind()方法将函数或方法绑定到具体的事件上。当被触发的事件满足该组件绑定的事件时,Tkinter就会带着事件描述去调用handler()方法实例1:捕获单击鼠标位置1fromtkinterimport*23root=Tk()45defcallback(event):6prin......
  • Python基础入门学习笔记 075 GUI的终极选择:Tkinter12
    Message组件Message(消息)组件是Label组件的变体,用于显示多行文本信息。Message组件能够自动换行,并调整文本的尺寸使其适应给定得尺寸。实例1:1fromtkinterimport*23root=Tk()4w1=Message(root,text="这是一则消息",width=100)5w1.pack()6w2=Message(root,......
  • Python基础入门学习笔记 071 GUI的终极选择:Tkinter8
    Canvas(画布)组件一个可以让你随心所欲绘制界面的组件。通常用于显示和编辑图形,可以用它来绘制直线、图形、多边形,甚至是绘制其他组件。实例1:1fromtkinterimport*2root=Tk()3#创建canvas对象框,设置其宽度、高度与背景色4w=Canvas(root,width=200,height=100,b......
  • [React Typescript] JSX.IntrinsicElements
    interfaceIntrinsicElements{//HTMLa:React.DetailedHTMLProps<React.AnchorHTMLAttributes<HTMLAnchorElement>,HTMLAnchorElement>;abbr:React.DetailedHTMLProps<React.HTMLAttributes<HTMLElemen......
  • Python基础入门学习笔记 073 GUI的终极选择:Tkinter10
    Munu组件Tkinter提供了一个Menu组件,用于实现顶级菜单、下拉菜单和弹出菜单。实例1:创建一个顶级菜单(或称窗口主菜单)1fromtkinterimport*23defcallback():4print("被调用了")56root=Tk()789menubar=Menu(root)#创建一个顶级菜单10m......