Plyr.js 简单轻量级 HTML5 视频在线播放器

发布于 2020-10-31 21:54:07 字数 15594 浏览 3083 评论 0

Plyr.js 简单轻量级 HTML5 视频在线播放器,支持音频和视频两格式,包含自定义的控制选项切换播放,调整音量,完全支持 WebVTT 字幕和全屏幕播放。它只支持现代浏览器,轻量级方便和可定制的媒体播放器。

特性

  • 可访问性 - 完全支持字幕和屏幕阅读器
  • 轻量级 - 压缩后只有 4.8Kb
  • 可定制 - 外观可以根据需要进行调整
  • 语义化 - 使用 HTML5 的输入框进行音量和进度的调整
  • 快速响应 - 就像你预期的那样
  • 音频和视频- 支持视频和纯音频
  • API - 易用 API
  • 向下兼容 - 如果浏览器不支持,则自动使用内建播放器
  • 全屏支持 -支持原生全屏和退出全屏
  • 无依赖 - 使用原生 JS 编写,不需要 jQuery

使用方法

安装

查看 docs/index.html 和 docs/dist/docs.js 获取安装的例子。

注意,除非你让源文件包含 http 或 https,否则 index.html 文件需要放到一个 web服务器(比如 Apache, Nginx, IIS 或 similar)上来浏览。例如将 //cdn.plyr.io/1.3.5/plyr.js 变成 https://cdn.plyr.io/1.3.5/plyr.js。

Bower

你可以通过 bower 来获取 Plyr:

bower install plyr

更多关于安装依赖的信息请查看 Bower 文档

CDN

如果你想使用我们的 CDN,你可以使用下面的代码:

<link rel="stylesheet" href="https://cdn.plyr.io/1.3.5/plyr.css">
<script src="https://cdn.plyr.io/1.3.5/plyr.js"></script>

你也可以从 https://cdn.plyr.io/1.3.5/sprite.svg 获取 sprite.svg 文件。

CSS

如果你想用默认的 css 样式,从 /dist 中添加 plyr.css 文件到你的 head 标签中,或者更好的做法是,在你的发行项目中使用 /src 中的 plyr.less 或 plyr.sass 文件。

<link rel="stylesheet" href="dist/plyr.css">

SVG

考虑到性能,作为控制条图标的 SVG 精灵是通过 AJAX 加载的。最好是在 </body> 闭合标签前,先于其它任何脚本添加。

(function(d, p){
    var a = new XMLHttpRequest(),
        b = d.body;
    a.open("GET", p, true);
    a.send();
    a.onload = function(){
        var c = d.createElement("div");
        c.style.display = "none";
        c.innerHTML = a.responseText;
        b.insertBefore(c, b.childNodes[0]);
    }
})(document, "dist/sprite.svg");

HTML

使用 plyr 唯一一个需要的额外标记就是一个 <div> 包装。将源,封面和字幕用你自己的替多媒体相关链接换掉。

<div class="player">
    <video poster="https://cdn.selz.com/plyr/1.0/poster.jpg" controls crossorigin>
        <!-- 视频文件 -->
        <source src="https://cdn.selz.com/plyr/1.0/movie.mp4" type="video/mp4">
        <source src="https://cdn.selz.com/plyr/1.0/movie.webm" type="video/webm">
        <!-- 字幕文件 -->
        <track kind="captions" label="English captions" src="https://cdn.selz.com/plyr/1.0/movie_captions_en.vtt" srclang="en" default>
        <!-- 针对不支持 <video> 元素的兼容 -->
        <a href="https://cdn.selz.com/plyr/1.0/movie.mp4">Download</a>
    </video>
</div>

同样 <audio> 如下

<div class="player">
    <audio controls>
        <!-- 音频文件 -->
        <source src="https://cdn.selz.com/plyr/1.0/logistics-96-sample.mp3" type="audio/mp3">
        <source src="https://cdn.selz.com/plyr/1.0/logistics-96-sample.ogg" type="audio/ogg">
        <!-- 针对不支持 <video> 元素的兼容 -->
        <a href="https://cdn.selz.com/plyr/1.0/logistics-96-sample.mp3">Download</a>
    </audio>
</div>

针对 YouTube,Plyr 使用了标准的 YouTube API 标记(一个空的 <div>):

<div class="player">
    <div data-video-id="L1h9xxCU20g" data-type="youtube"></div>
</div>

跨域 (CORS)

你会注意到上面例子中 <video> 和 <audio> 元素的 crossorigin 属性。这是因为该多媒体是从另外一个域加载过来的,或许你需要加上这个属性。

JavaScript

播放器大多数的行为都可以在初始化的时候配置。这里是一个默认安装的例子:

<script src="dist/plyr.js"></script>
<script>plyr.setup();</script>

选项

你可以使用 plyr.setup({...}) 将下面的选项传入 setup 方法。

OptionTypeDefaultDescription
enabledBooleantrueCompletely disable Plyr. This would allow you to do a User Agent check or similar to programmatically enable or disable Plyr for a certain UA. Example below.
debugBooleanfalseDisplay debugging information in the console
controlsArray, Function or Element['play-large', 'play', 'progress', 'current-time', 'mute', 'volume', 'captions', 'settings', 'pip', 'airplay', 'fullscreen']If a function is passed, it is assumed your method will return either an element or HTML string for the controls. Three arguments will be passed to your function; id (the unique id for the player), seektime (the seektime step in seconds), and title (the media title). See CONTROLS.md for more info on how the html needs to be structured.
settingsArray['captions', 'quality', 'speed', 'loop']If the default controls are used, you can specify which settings to show in the menu
i18nObjectSee defaults.jsUsed for internationalization (i18n) of the text within the UI.
loadSpriteBooleantrueLoad the SVG sprite specified as the iconUrl option (if a URL). If false, it is assumed you are handling sprite loading yourself.
iconUrlStringnullSpecify a URL or path to the SVG sprite. See the SVG section for more info.
iconPrefixStringplyrSpecify the id prefix for the icons used in the default controls (e.g. "plyr-play" would be "plyr"). This is to prevent clashes if you're using your own SVG sprite but with the default controls. Most people can ignore this option.
blankVideoStringhttps://cdn.plyr.io/static/blank.mp4Specify a URL or path to a blank video file used to properly cancel network requests.
autoplay²BooleanfalseAutoplay the media on load. If the autoplay attribute is present on a <video> or <audio> element, this will be automatically set to true.
autopause¹BooleantrueOnly allow one player playing at once.
seekTimeNumber10The time, in seconds, to seek when a user hits fast forward or rewind.
volumeNumber1A number, between 0 and 1, representing the initial volume of the player.
mutedBooleanfalseWhether to start playback muted. If the muted attribute is present on a <video> or <audio> element, this will be automatically set to true.
clickToPlayBooleantrueClick (or tap) of the video container will toggle play/pause.
disableContextMenuBooleantrueDisable right click menu on video to help as very primitive obfuscation to prevent downloads of content.
hideControlsBooleantrueHide video controls automatically after 2s of no mouse or focus movement, on control element blur (tab out), on playback start or entering fullscreen. As soon as the mouse is moved, a control element is focused or playback is paused, the controls reappear instantly.
resetOnEndBooleanfalseReset the playback to the start once playback is complete.
keyboardObject{ focused: true, global: false }Enable keyboard shortcuts for focused players only or globally
tooltipsObject{ controls: false, seek: true }controls: Display control labels as tooltips on :hover & :focus (by default, the labels are screen reader only). seek: Display a seek tooltip to indicate on click where the media would seek to.
durationNumbernullSpecify a custom duration for media.
displayDurationBooleantrueDisplays the duration of the media on the "metadataloaded" event (on startup) in the current time display. This will only work if the preload attribute is not set to none (or is not set at all) and you choose not to display the duration (see controls option).
invertTimeBooleantrueDisplay the current time as a countdown rather than an incremental counter.
toggleInvertBooleantrueAllow users to click to toggle the above.
listenersObjectnullAllows binding of event listeners to the controls before the default handlers. See the defaults.js for available listeners. If your handler prevents default on the event (event.preventDefault()), the default handler will not fire.
captionsObject{ active: false, language: 'auto', update: false }active: Toggles if captions should be active by default. language: Sets the default language to load (if available). 'auto' uses the browser language. update: Listen to changes to tracks and update menu. This is needed for some streaming libraries, but can result in unselectable language options).
fullscreenObject{ enabled: true, fallback: true, iosNative: false, container: null }enabled: Toggles whether fullscreen should be enabled. fallback: Allow fallback to a full-window solution (true/false/'force'). iosNative: whether to use native iOS fullscreen when entering fullscreen (no custom controls). container: A selector for an ancestor of the player element, allows contextual content to remain visual in fullscreen mode. Non-ancestors are ignored.
ratioStringnullForce an aspect ratio for all videos. The format is 'w:h' - e.g. '16:9' or '4:3'. If this is not specified then the default for HTML5 and Vimeo is to use the native resolution of the video. As dimensions are not available from YouTube via SDK, 16:9 is forced as a sensible default.
storageObject{ enabled: true, key: 'plyr' }enabled: Allow use of local storage to store user settings. key: The key name to use.
speedObject{ selected: 1, options: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2] }selected: The default speed for playback. options: The speed options to display in the UI. YouTube and Vimeo will ignore any options outside of the 0.5-2 range, so options outside of this range will be hidden automatically.
qualityObject{ default: 576, options: [4320, 2880, 2160, 1440, 1080, 720, 576, 480, 360, 240] }default is the default quality level (if it exists in your sources). options are the options to display. This is used to filter the available sources.
loopObject{ active: false }active: Whether to loop the current video. If the loop attribute is present on a <video> or <audio> element, this will be automatically set to true This is an object to support future functionality.
adsObject{ enabled: false, publisherId: '', tagUrl: '' }enabled: Whether to enable advertisements. publisherId: Your unique vi.ai publisher ID. tagUrl is a URL for a custom VAST tag if you're not using Vi.
urlsObjectSee source.If you wish to override any API URLs then you can do so here. You can also set a custom download URL for the download button.
vimeoObject{ byline: false, portrait: false, title: false, speed: true, transparent: false }See Vimeo embed options. Some are set automatically based on other config options, namely: loop, autoplay, muted, gesture, playsinline
youtubeObject{ noCookie: false, rel: 0, showinfo: 0, iv_load_policy: 3, modestbranding: 1 }See YouTube embed options. The only custom option is noCookie to use an alternative to YouTube that doesn't use cookies (useful for GDPR, etc). Some are set automatically based on other config options, namely: autoplay, hl, controls, disablekb, playsinline, cc_load_policy, cc_lang_pref, widget_referrer
previewThumbnailsObject{ enabled: false, src: '' }enabled: Whether to enable the preview thumbnails (they must be generated by you). src must be either a string or an array of strings representing URLs for the VTT files containing the image URL(s). Learn more about preview thumbnails below.

更多文档请访问 github 地址:https://github.com/sampotts/plyr

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

JSmiles

生命进入颠沛而奔忙的本质状态,并将以不断告别和相遇的陈旧方式继续下去。

0 文章
0 评论
84961 人气
更多

推荐作者

亚希

文章 0 评论 0

cyp

文章 0 评论 0

北漠

文章 0 评论 0

11223456

文章 0 评论 0

坠似风落

文章 0 评论 0

游魂

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文