plyr.js 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089
  1. // ==========================================================================
  2. // Plyr
  3. // plyr.js v1.3.6
  4. // https://github.com/selz/plyr
  5. // License: The MIT License (MIT)
  6. // ==========================================================================
  7. // Credits: http://paypal.github.io/accessible-html5-video-player/
  8. // ==========================================================================
  9. (function (api) {
  10. 'use strict';
  11. /*global YT*/
  12. // Globals
  13. var fullscreen, config, callbacks = {
  14. youtube: []
  15. };
  16. // Default config
  17. var defaults = {
  18. enabled: true,
  19. debug: false,
  20. seekTime: 10,
  21. volume: 5,
  22. click: true,
  23. tooltips: true,
  24. displayDuration: true,
  25. iconPrefix: 'icon',
  26. selectors: {
  27. container: '.player',
  28. controls: '.player-controls',
  29. labels: '[data-player] .sr-only, label .sr-only',
  30. buttons: {
  31. seek: '[data-player="seek"]',
  32. play: '[data-player="play"]',
  33. pause: '[data-player="pause"]',
  34. restart: '[data-player="restart"]',
  35. rewind: '[data-player="rewind"]',
  36. forward: '[data-player="fast-forward"]',
  37. mute: '[data-player="mute"]',
  38. volume: '[data-player="volume"]',
  39. captions: '[data-player="captions"]',
  40. fullscreen: '[data-player="fullscreen"]'
  41. },
  42. progress: {
  43. container: '.player-progress',
  44. buffer: '.player-progress-buffer',
  45. played: '.player-progress-played'
  46. },
  47. captions: '.player-captions',
  48. currentTime: '.player-current-time',
  49. duration: '.player-duration'
  50. },
  51. classes: {
  52. videoWrapper: 'player-video-wrapper',
  53. embedWrapper: 'player-video-embed',
  54. type: 'player-{0}',
  55. stopped: 'stopped',
  56. playing: 'playing',
  57. muted: 'muted',
  58. loading: 'loading',
  59. tooltip: 'player-tooltip',
  60. hidden: 'sr-only',
  61. hover: 'player-hover',
  62. captions: {
  63. enabled: 'captions-enabled',
  64. active: 'captions-active'
  65. },
  66. fullscreen: {
  67. enabled: 'fullscreen-enabled',
  68. active: 'fullscreen-active',
  69. hideControls: 'fullscreen-hide-controls'
  70. }
  71. },
  72. captions: {
  73. defaultActive: false
  74. },
  75. fullscreen: {
  76. enabled: true,
  77. fallback: true,
  78. hideControls: true
  79. },
  80. storage: {
  81. enabled: true,
  82. key: 'plyr_volume'
  83. },
  84. controls: ['restart', 'rewind', 'play', 'fast-forward', 'current-time', 'duration', 'mute', 'volume', /*'captions',*/ 'fullscreen'],
  85. i18n: {
  86. restart: '重新播放',
  87. rewind: '后退{seektime}秒',
  88. play: '播放',
  89. pause: '暂停',
  90. forward: '快进{seektime}秒',
  91. played: '播放中',
  92. buffered: '缓冲中',
  93. currentTime: '当前时间',
  94. duration: '持续时间',
  95. volume: '音量',
  96. toggleMute: '静音',
  97. toggleCaptions: '字幕',
  98. toggleFullscreen: '全屏'
  99. }
  100. };
  101. // Build the default HTML
  102. function _buildControls() {
  103. // Open and add the progress and seek elements
  104. var html = [
  105. '<div class="player-controls">',
  106. '<div class="player-progress">',
  107. '<label for="seek{id}" class="sr-only">Seek</label>',
  108. '<input id="seek{id}" class="player-progress-seek" type="range" min="0" max="100" step="0.5" value="0" data-player="seek">',
  109. '<progress class="player-progress-played" max="100" value="0">',
  110. '<span>0</span>% ' + config.i18n.played,
  111. '</progress>',
  112. '<progress class="player-progress-buffer" max="100" value="0">',
  113. '<span>0</span>% ' + config.i18n.buffered,
  114. '</progress>',
  115. '</div>',
  116. '<span class="player-controls-left">'];
  117. // Restart button
  118. if (_inArray(config.controls, 'restart')) {
  119. html.push(
  120. '<button type="button" data-player="restart">',
  121. '<svg><use xlink:href="#' + config.iconPrefix + '-restart" /></svg>',
  122. '<span class="sr-only">' + config.i18n.restart + '</span>',
  123. '</button>'
  124. );
  125. }
  126. // Rewind button
  127. if (_inArray(config.controls, 'rewind')) {
  128. html.push(
  129. '<button type="button" data-player="rewind">',
  130. '<svg><use xlink:href="#' + config.iconPrefix + '-rewind" /></svg>',
  131. '<span class="sr-only">' + config.i18n.rewind + '</span>',
  132. '</button>'
  133. );
  134. }
  135. // Play/pause button
  136. if (_inArray(config.controls, 'play')) {
  137. html.push(
  138. '<button type="button" data-player="play">',
  139. '<svg><use xlink:href="#' + config.iconPrefix + '-play" /></svg>',
  140. '<span class="sr-only">' + config.i18n.play + '</span>',
  141. '</button>',
  142. '<button type="button" data-player="pause">',
  143. '<svg><use xlink:href="#' + config.iconPrefix + '-pause" /></svg>',
  144. '<span class="sr-only">' + config.i18n.pause + '</span>',
  145. '</button>'
  146. );
  147. }
  148. // Fast forward button
  149. if (_inArray(config.controls, 'fast-forward')) {
  150. html.push(
  151. '<button type="button" data-player="fast-forward">',
  152. '<svg><use xlink:href="#' + config.iconPrefix + '-fast-forward" /></svg>',
  153. '<span class="sr-only">' + config.i18n.forward + '</span>',
  154. '</button>'
  155. );
  156. }
  157. // Media current time display
  158. if (_inArray(config.controls, 'current-time')) {
  159. html.push(
  160. '<span class="player-time">',
  161. '<span class="sr-only">' + config.i18n.currentTime + '</span>',
  162. '<span class="player-current-time">00:00</span>',
  163. '</span>'
  164. );
  165. }
  166. // Media duration display
  167. if (_inArray(config.controls, 'duration')) {
  168. html.push(
  169. '<span class="player-time">',
  170. '<span class="sr-only">' + config.i18n.duration + '</span>',
  171. '<span class="player-duration">00:00</span>',
  172. '</span>'
  173. );
  174. }
  175. // Close left controls
  176. html.push(
  177. '</span>',
  178. '<span class="player-controls-right">'
  179. );
  180. // Toggle mute button
  181. if (_inArray(config.controls, 'mute')) {
  182. html.push(
  183. '<button type="button" data-player="mute">',
  184. '<svg class="icon-muted"><use xlink:href="#' + config.iconPrefix + '-muted" /></svg>',
  185. '<svg><use xlink:href="#' + config.iconPrefix + '-volume" /></svg>',
  186. '<span class="sr-only">' + config.i18n.toggleMute + '</span>',
  187. '</button>'
  188. );
  189. }
  190. // Volume range control
  191. if (_inArray(config.controls, 'volume')) {
  192. html.push(
  193. '<label for="volume{id}" class="sr-only">' + config.i18n.volume + '</label>',
  194. '<input id="volume{id}" class="player-volume" type="range" min="0" max="10" value="5" data-player="volume">'
  195. );
  196. }
  197. // Toggle captions button
  198. if (_inArray(config.controls, 'captions')) {
  199. html.push(
  200. '<button type="button" data-player="captions">',
  201. '<svg class="icon-captions-on"><use xlink:href="#' + config.iconPrefix + '-captions-on" /></svg>',
  202. '<svg><use xlink:href="#' + config.iconPrefix + '-captions-off" /></svg>',
  203. '<span class="sr-only">' + config.i18n.toggleCaptions + '</span>',
  204. '</button>'
  205. );
  206. }
  207. // Toggle fullscreen button
  208. if (_inArray(config.controls, 'fullscreen')) {
  209. html.push(
  210. '<button type="button" data-player="fullscreen">',
  211. '<svg class="icon-exit-fullscreen"><use xlink:href="#' + config.iconPrefix + '-exit-fullscreen" /></svg>',
  212. '<svg><use xlink:href="#' + config.iconPrefix + '-enter-fullscreen" /></svg>',
  213. '<span class="sr-only">' + config.i18n.toggleFullscreen + '</span>',
  214. '</button>'
  215. );
  216. }
  217. // Close everything
  218. html.push(
  219. '</span>',
  220. '</div>'
  221. );
  222. return html.join('');
  223. }
  224. // Debugging
  225. function _log(text, error) {
  226. if (config.debug && window.console) {
  227. console[(error ? 'error' : 'log')](text);
  228. }
  229. }
  230. // Credits: http://paypal.github.io/accessible-html5-video-player/
  231. // Unfortunately, due to mixed support, UA sniffing is required
  232. function _browserSniff() {
  233. var nAgt = navigator.userAgent,
  234. name = navigator.appName,
  235. fullVersion = '' + parseFloat(navigator.appVersion),
  236. majorVersion = parseInt(navigator.appVersion, 10),
  237. nameOffset,
  238. verOffset,
  239. ix;
  240. // MSIE 11
  241. if ((navigator.appVersion.indexOf('Windows NT') !== -1) && (navigator.appVersion.indexOf('rv:11') !== -1)) {
  242. name = 'IE';
  243. fullVersion = '11;';
  244. }
  245. // MSIE
  246. else if ((verOffset = nAgt.indexOf('MSIE')) !== -1) {
  247. name = 'IE';
  248. fullVersion = nAgt.substring(verOffset + 5);
  249. }
  250. // Chrome
  251. else if ((verOffset = nAgt.indexOf('Chrome')) !== -1) {
  252. name = 'Chrome';
  253. fullVersion = nAgt.substring(verOffset + 7);
  254. }
  255. // Safari
  256. else if ((verOffset = nAgt.indexOf('Safari')) !== -1) {
  257. name = 'Safari';
  258. fullVersion = nAgt.substring(verOffset + 7);
  259. if ((verOffset = nAgt.indexOf('Version')) !== -1) {
  260. fullVersion = nAgt.substring(verOffset + 8);
  261. }
  262. }
  263. // Firefox
  264. else if ((verOffset = nAgt.indexOf('Firefox')) !== -1) {
  265. name = 'Firefox';
  266. fullVersion = nAgt.substring(verOffset + 8);
  267. }
  268. // In most other browsers, 'name/version' is at the end of userAgent
  269. else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
  270. name = nAgt.substring(nameOffset, verOffset);
  271. fullVersion = nAgt.substring(verOffset + 1);
  272. if (name.toLowerCase() == name.toUpperCase()) {
  273. name = navigator.appName;
  274. }
  275. }
  276. // Trim the fullVersion string at semicolon/space if present
  277. if ((ix = fullVersion.indexOf(';')) !== -1) {
  278. fullVersion = fullVersion.substring(0, ix);
  279. }
  280. if ((ix = fullVersion.indexOf(' ')) !== -1) {
  281. fullVersion = fullVersion.substring(0, ix);
  282. }
  283. // Get major version
  284. majorVersion = parseInt('' + fullVersion, 10);
  285. if (isNaN(majorVersion)) {
  286. fullVersion = '' + parseFloat(navigator.appVersion);
  287. majorVersion = parseInt(navigator.appVersion, 10);
  288. }
  289. // Return data
  290. return {
  291. name: name,
  292. version: majorVersion,
  293. ios: /(iPad|iPhone|iPod)/g.test(navigator.platform)
  294. };
  295. }
  296. // Check for mime type support against a player instance
  297. // Credits: http://diveintohtml5.info/everything.html
  298. // Related: http://www.leanbackplayer.com/test/h5mt.html
  299. function _supportMime(player, mimeType) {
  300. var media = player.media;
  301. // Only check video types for video players
  302. if (player.type == 'video') {
  303. // Check type
  304. switch (mimeType) {
  305. case 'video/webm':
  306. return !!(media.canPlayType && media.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/no/, ''));
  307. case 'video/mp4':
  308. return !!(media.canPlayType && media.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"').replace(/no/, ''));
  309. case 'video/ogg':
  310. return !!(media.canPlayType && media.canPlayType('video/ogg; codecs="theora"').replace(/no/, ''));
  311. }
  312. }
  313. // Only check audio types for audio players
  314. else if (player.type == 'audio') {
  315. // Check type
  316. switch (mimeType) {
  317. case 'audio/mpeg':
  318. return !!(media.canPlayType && media.canPlayType('audio/mpeg;').replace(/no/, ''));
  319. case 'audio/ogg':
  320. return !!(media.canPlayType && media.canPlayType('audio/ogg; codecs="vorbis"').replace(/no/, ''));
  321. case 'audio/wav':
  322. return !!(media.canPlayType && media.canPlayType('audio/wav; codecs="1"').replace(/no/, ''));
  323. }
  324. }
  325. // If we got this far, we're stuffed
  326. return false;
  327. }
  328. // Inject a script
  329. function _injectScript(source) {
  330. if (document.querySelectorAll('script[src="' + source + '"]').length) {
  331. return;
  332. }
  333. var tag = document.createElement('script');
  334. tag.src = source;
  335. var firstScriptTag = document.getElementsByTagName('script')[0];
  336. firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  337. }
  338. // Element exists in an array
  339. function _inArray(haystack, needle) {
  340. return Array.prototype.indexOf && (haystack.indexOf(needle) != -1);
  341. }
  342. // Replace all
  343. function _replaceAll(string, find, replace) {
  344. return string.replace(new RegExp(find.replace(/([.*+?\^=!:${}()|\[\]\/\\])/g, '\\$1'), 'g'), replace);
  345. }
  346. // Wrap an element
  347. function _wrap(elements, wrapper) {
  348. // Convert `elements` to an array, if necessary.
  349. if (!elements.length) {
  350. elements = [elements];
  351. }
  352. // Loops backwards to prevent having to clone the wrapper on the
  353. // first element (see `child` below).
  354. for (var i = elements.length - 1; i >= 0; i--) {
  355. var child = (i > 0) ? wrapper.cloneNode(true) : wrapper;
  356. var element = elements[i];
  357. // Cache the current parent and sibling.
  358. var parent = element.parentNode;
  359. var sibling = element.nextSibling;
  360. // Wrap the element (is automatically removed from its current
  361. // parent).
  362. child.appendChild(element);
  363. // If the element had a sibling, insert the wrapper before
  364. // the sibling to maintain the HTML structure; otherwise, just
  365. // append it to the parent.
  366. if (sibling) {
  367. parent.insertBefore(child, sibling);
  368. } else {
  369. parent.appendChild(child);
  370. }
  371. }
  372. }
  373. // Unwrap an element
  374. // http://plainjs.com/javascript/manipulation/unwrap-a-dom-element-35/
  375. function _unwrap(wrapper) {
  376. // Get the element's parent node
  377. var parent = wrapper.parentNode;
  378. // Move all children out of the element
  379. while (wrapper.firstChild) {
  380. parent.insertBefore(wrapper.firstChild, wrapper);
  381. }
  382. // Remove the empty element
  383. parent.removeChild(wrapper);
  384. }
  385. // Remove an element
  386. function _remove(element) {
  387. element.parentNode.removeChild(element);
  388. }
  389. // Prepend child
  390. function _prependChild(parent, element) {
  391. parent.insertBefore(element, parent.firstChild);
  392. }
  393. // Set attributes
  394. function _setAttributes(element, attributes) {
  395. for (var key in attributes) {
  396. element.setAttribute(key, attributes[key]);
  397. }
  398. }
  399. // Toggle class on an element
  400. function _toggleClass(element, name, state) {
  401. if (element) {
  402. if (element.classList) {
  403. element.classList[state ? 'add' : 'remove'](name);
  404. } else {
  405. var className = (' ' + element.className + ' ').replace(/\s+/g, ' ').replace(' ' + name + ' ', '');
  406. element.className = className + (state ? ' ' + name : '');
  407. }
  408. }
  409. }
  410. // Toggle event
  411. function _toggleHandler(element, events, callback, toggle) {
  412. var eventList = events.split(' ');
  413. // If a nodelist is passed, call itself on each node
  414. if (element instanceof NodeList) {
  415. for (var x = 0; x < element.length; x++) {
  416. if (element[x] instanceof Node) {
  417. _toggleHandler(element[x], arguments[1], arguments[2], arguments[3]);
  418. }
  419. }
  420. return;
  421. }
  422. // If a single node is passed, bind the event listener
  423. for (var i = 0; i < eventList.length; i++) {
  424. element[toggle ? 'addEventListener' : 'removeEventListener'](eventList[i], callback, false);
  425. }
  426. }
  427. // Bind event
  428. function _on(element, events, callback) {
  429. if (element) {
  430. _toggleHandler(element, events, callback, true);
  431. }
  432. }
  433. // Unbind event
  434. function _off(element, events, callback) {
  435. if (element) {
  436. _toggleHandler(element, events, callback, false);
  437. }
  438. }
  439. // Trigger event
  440. function _triggerEvent(element, event) {
  441. // Create faux event
  442. var fauxEvent = document.createEvent('MouseEvents');
  443. // Set the event type
  444. fauxEvent.initEvent(event, true, true);
  445. // Dispatch the event
  446. element.dispatchEvent(fauxEvent);
  447. }
  448. // Toggle aria-pressed state on a toggle button
  449. function _toggleState(target, state) {
  450. // Get state
  451. state = (typeof state === 'boolean' ? state : !target.getAttribute('aria-pressed'));
  452. // Set the attribute on target
  453. target.setAttribute('aria-pressed', state);
  454. return state;
  455. }
  456. // Get percentage
  457. function _getPercentage(current, max) {
  458. if (current === 0 || max === 0 || isNaN(current) || isNaN(max)) {
  459. return 0;
  460. }
  461. return ((current / max) * 100).toFixed(2);
  462. }
  463. // Deep extend/merge two Objects
  464. // http://andrewdupont.net/2009/08/28/deep-extending-objects-in-javascript/
  465. // Removed call to arguments.callee (used explicit function name instead)
  466. function _extend(destination, source) {
  467. for (var property in source) {
  468. if (source[property] && source[property].constructor && source[property].constructor === Object) {
  469. destination[property] = destination[property] || {};
  470. _extend(destination[property], source[property]);
  471. } else {
  472. destination[property] = source[property];
  473. }
  474. }
  475. return destination;
  476. }
  477. // Fullscreen API
  478. function _fullscreen() {
  479. var fullscreen = {
  480. supportsFullScreen: false,
  481. isFullScreen: function () {
  482. return false;
  483. },
  484. requestFullScreen: function () {},
  485. cancelFullScreen: function () {},
  486. fullScreenEventName: '',
  487. element: null,
  488. prefix: ''
  489. },
  490. browserPrefixes = 'webkit moz o ms khtml'.split(' ');
  491. // Check for native support
  492. if (typeof document.cancelFullScreen !== 'undefined') {
  493. fullscreen.supportsFullScreen = true;
  494. } else {
  495. // Check for fullscreen support by vendor prefix
  496. for (var i = 0, il = browserPrefixes.length; i < il; i++) {
  497. fullscreen.prefix = browserPrefixes[i];
  498. if (typeof document[fullscreen.prefix + 'CancelFullScreen'] !== 'undefined') {
  499. fullscreen.supportsFullScreen = true;
  500. break;
  501. }
  502. // Special case for MS (when isn't it?)
  503. else if (typeof document.msExitFullscreen !== 'undefined' && document.msFullscreenEnabled) {
  504. fullscreen.prefix = 'ms';
  505. fullscreen.supportsFullScreen = true;
  506. break;
  507. }
  508. }
  509. }
  510. // Update methods to do something useful
  511. if (fullscreen.supportsFullScreen) {
  512. // Yet again Microsoft awesomeness,
  513. // Sometimes the prefix is 'ms', sometimes 'MS' to keep you on your toes
  514. fullscreen.fullScreenEventName = (fullscreen.prefix == 'ms' ? 'MSFullscreenChange' : fullscreen.prefix + 'fullscreenchange');
  515. fullscreen.isFullScreen = function (element) {
  516. if (typeof element === 'undefined') {
  517. element = document.body;
  518. }
  519. switch (this.prefix) {
  520. case '':
  521. return document.fullscreenElement == element;
  522. case 'moz':
  523. return document.mozFullScreenElement == element;
  524. default:
  525. return document[this.prefix + 'FullscreenElement'] == element;
  526. }
  527. };
  528. fullscreen.requestFullScreen = function (element) {
  529. if (typeof element === 'undefined') {
  530. element = document.body;
  531. }
  532. return (this.prefix === '') ? element.requestFullScreen() : element[this.prefix + (this.prefix == 'ms' ? 'RequestFullscreen' : 'RequestFullScreen')]();
  533. };
  534. fullscreen.cancelFullScreen = function () {
  535. return (this.prefix === '') ? document.cancelFullScreen() : document[this.prefix + (this.prefix == 'ms' ? 'ExitFullscreen' : 'CancelFullScreen')]();
  536. };
  537. fullscreen.element = function () {
  538. return (this.prefix === '') ? document.fullscreenElement : document[this.prefix + 'FullscreenElement'];
  539. };
  540. }
  541. return fullscreen;
  542. }
  543. // Local storage
  544. function _storage() {
  545. var storage = {
  546. supported: (function () {
  547. try {
  548. return 'localStorage' in window && window.localStorage !== null;
  549. } catch (e) {
  550. return false;
  551. }
  552. })()
  553. };
  554. return storage;
  555. }
  556. // Player instance
  557. function Plyr(container) {
  558. var player = this;
  559. player.container = container;
  560. // Captions functions
  561. // Seek the manual caption time and update UI
  562. function _seekManualCaptions(time) {
  563. // If it's not video, or we're using textTracks, bail.
  564. if (player.usingTextTracks || player.type !== 'video' || !player.supported.full) {
  565. return;
  566. }
  567. // Reset subcount
  568. player.subcount = 0;
  569. // Check time is a number, if not use currentTime
  570. // IE has a bug where currentTime doesn't go to 0
  571. // https://twitter.com/Sam_Potts/status/573715746506731521
  572. time = typeof time === 'number' ? time : player.media.currentTime;
  573. while (_timecodeMax(player.captions[player.subcount][0]) < time.toFixed(1)) {
  574. player.subcount++;
  575. if (player.subcount > player.captions.length - 1) {
  576. player.subcount = player.captions.length - 1;
  577. break;
  578. }
  579. }
  580. // Check if the next caption is in the current time range
  581. if (player.media.currentTime.toFixed(1) >= _timecodeMin(player.captions[player.subcount][0]) &&
  582. player.media.currentTime.toFixed(1) <= _timecodeMax(player.captions[player.subcount][0])) {
  583. player.currentCaption = player.captions[player.subcount][1];
  584. // Trim caption text
  585. var content = player.currentCaption.trim();
  586. // Render the caption (only if changed)
  587. if (player.captionsContainer.innerHTML != content) {
  588. // Empty caption
  589. // Otherwise NVDA reads it twice
  590. player.captionsContainer.innerHTML = '';
  591. // Set new caption text
  592. player.captionsContainer.innerHTML = content;
  593. }
  594. } else {
  595. player.captionsContainer.innerHTML = '';
  596. }
  597. }
  598. // Display captions container and button (for initialization)
  599. function _showCaptions() {
  600. // If there's no caption toggle, bail
  601. if (!player.buttons.captions) {
  602. return;
  603. }
  604. _toggleClass(player.container, config.classes.captions.enabled, true);
  605. if (config.captions.defaultActive) {
  606. _toggleClass(player.container, config.classes.captions.active, true);
  607. _toggleState(player.buttons.captions, true);
  608. }
  609. }
  610. // Utilities for caption time codes
  611. function _timecodeMin(tc) {
  612. var tcpair = [];
  613. tcpair = tc.split(' --> ');
  614. return _subTcSecs(tcpair[0]);
  615. }
  616. function _timecodeMax(tc) {
  617. var tcpair = [];
  618. tcpair = tc.split(' --> ');
  619. return _subTcSecs(tcpair[1]);
  620. }
  621. function _subTcSecs(tc) {
  622. if (tc === null || tc === undefined) {
  623. return 0;
  624. } else {
  625. var tc1 = [],
  626. tc2 = [],
  627. seconds;
  628. tc1 = tc.split(',');
  629. tc2 = tc1[0].split(':');
  630. seconds = Math.floor(tc2[0] * 60 * 60) + Math.floor(tc2[1] * 60) + Math.floor(tc2[2]);
  631. return seconds;
  632. }
  633. }
  634. // Find all elements
  635. function _getElements(selector) {
  636. return player.container.querySelectorAll(selector);
  637. }
  638. // Find a single element
  639. function _getElement(selector) {
  640. return _getElements(selector)[0];
  641. }
  642. // Determine if we're in an iframe
  643. function _inFrame() {
  644. try {
  645. return window.self !== window.top;
  646. } catch (e) {
  647. return true;
  648. }
  649. }
  650. // Insert controls
  651. function _injectControls() {
  652. // Make a copy of the html
  653. var html = config.html;
  654. // Insert custom video controls
  655. _log('Injecting custom controls.');
  656. // If no controls are specified, create default
  657. if (!html) {
  658. html = _buildControls();
  659. }
  660. // Replace seek time instances
  661. html = _replaceAll(html, '{seektime}', config.seekTime);
  662. // Replace all id references with random numbers
  663. html = _replaceAll(html, '{id}', Math.floor(Math.random() * (10000)));
  664. // Inject into the container
  665. player.container.insertAdjacentHTML('beforeend', html);
  666. // Setup tooltips
  667. if (config.tooltips) {
  668. var labels = _getElements(config.selectors.labels);
  669. for (var i = labels.length - 1; i >= 0; i--) {
  670. var label = labels[i];
  671. _toggleClass(label, config.classes.hidden, false);
  672. _toggleClass(label, config.classes.tooltip, true);
  673. }
  674. }
  675. }
  676. // Find the UI controls and store references
  677. function _findElements() {
  678. try {
  679. player.controls = _getElement(config.selectors.controls);
  680. // Buttons
  681. player.buttons = {};
  682. player.buttons.seek = _getElement(config.selectors.buttons.seek);
  683. player.buttons.play = _getElement(config.selectors.buttons.play);
  684. player.buttons.pause = _getElement(config.selectors.buttons.pause);
  685. player.buttons.restart = _getElement(config.selectors.buttons.restart);
  686. player.buttons.rewind = _getElement(config.selectors.buttons.rewind);
  687. player.buttons.forward = _getElement(config.selectors.buttons.forward);
  688. player.buttons.fullscreen = _getElement(config.selectors.buttons.fullscreen);
  689. // Inputs
  690. player.buttons.mute = _getElement(config.selectors.buttons.mute);
  691. player.buttons.captions = _getElement(config.selectors.buttons.captions);
  692. player.checkboxes = _getElements('[type="checkbox"]');
  693. // Progress
  694. player.progress = {};
  695. player.progress.container = _getElement(config.selectors.progress.container);
  696. // Progress - Buffering
  697. player.progress.buffer = {};
  698. player.progress.buffer.bar = _getElement(config.selectors.progress.buffer);
  699. player.progress.buffer.text = player.progress.buffer.bar && player.progress.buffer.bar.getElementsByTagName('span')[0];
  700. // Progress - Played
  701. player.progress.played = {};
  702. player.progress.played.bar = _getElement(config.selectors.progress.played);
  703. player.progress.played.text = player.progress.played.bar && player.progress.played.bar.getElementsByTagName('span')[0];
  704. // Volume
  705. player.volume = _getElement(config.selectors.buttons.volume);
  706. // Timing
  707. player.duration = _getElement(config.selectors.duration);
  708. player.currentTime = _getElement(config.selectors.currentTime);
  709. player.seekTime = _getElements(config.selectors.seekTime);
  710. return true;
  711. } catch (e) {
  712. _log('It looks like there\'s a problem with your controls html. Bailing.', true);
  713. // Restore native video controls
  714. player.media.setAttribute('controls', '');
  715. return false;
  716. }
  717. }
  718. // Setup aria attribute for play
  719. function _setupPlayAria() {
  720. // If there's no play button, bail
  721. if (!player.buttons.play) {
  722. return;
  723. }
  724. // Find the current text
  725. var label = player.buttons.play.innerText || config.i18n.play;
  726. // If there's a media title set, use that for the label
  727. if (typeof (config.title) !== 'undefined' && config.title.length) {
  728. label += ', ' + config.title;
  729. }
  730. player.buttons.play.setAttribute('aria-label', label);
  731. }
  732. // Setup media
  733. function _setupMedia() {
  734. // If there's no media, bail
  735. if (!player.media) {
  736. _log('No audio or video element found!', true);
  737. return false;
  738. }
  739. if (player.supported.full) {
  740. // Remove native video controls
  741. player.media.removeAttribute('controls');
  742. // Add type class
  743. _toggleClass(player.container, config.classes.type.replace('{0}', player.type), true);
  744. // If there's no autoplay attribute, assume the video is stopped and add state class
  745. _toggleClass(player.container, config.classes.stopped, (player.media.getAttribute('autoplay') === null));
  746. // Add iOS class
  747. if (player.browser.ios) {
  748. _toggleClass(player.container, 'ios', true);
  749. }
  750. // Inject the player wrapper
  751. if (player.type === 'video') {
  752. // Create the wrapper div
  753. var wrapper = document.createElement('div');
  754. wrapper.setAttribute('class', config.classes.videoWrapper);
  755. // Wrap the video in a container
  756. _wrap(player.media, wrapper);
  757. // Cache the container
  758. player.videoContainer = wrapper;
  759. }
  760. }
  761. // YouTube
  762. if (player.type == 'youtube') {
  763. _setupYouTube(player.media.getAttribute('data-video-id'));
  764. }
  765. // Autoplay
  766. if (player.media.getAttribute('autoplay') !== null) {
  767. _play();
  768. }
  769. }
  770. // Setup YouTube
  771. function _setupYouTube(id) {
  772. // Remove old containers
  773. var containers = _getElements('[id^="youtube"]');
  774. for (var i = containers.length - 1; i >= 0; i--) {
  775. _remove(containers[i]);
  776. }
  777. // Create the YouTube container
  778. var container = document.createElement('div');
  779. container.setAttribute('id', 'youtube-' + Math.floor(Math.random() * (10000)));
  780. player.media.appendChild(container);
  781. // Add embed class for responsive
  782. _toggleClass(player.media, config.classes.videoWrapper, true);
  783. _toggleClass(player.media, config.classes.embedWrapper, true);
  784. if (typeof YT === 'object') {
  785. _YTReady(id, container);
  786. } else {
  787. // Load the API
  788. _injectScript('https://www.youtube.com/iframe_api');
  789. // Add callback to queue
  790. callbacks.youtube.push(function () {
  791. _YTReady(id, container);
  792. });
  793. // Setup callback for the API
  794. window.onYouTubeIframeAPIReady = function () {
  795. for (var i = callbacks.youtube.length - 1; i >= 0; i--) {
  796. // Fire callback
  797. callbacks.youtube[i]();
  798. // Remove from queue
  799. callbacks.youtube.splice(i, 1);
  800. }
  801. };
  802. }
  803. }
  804. // Handle API ready
  805. function _YTReady(id, container) {
  806. _log('YouTube API Ready');
  807. // Setup timers object
  808. // We have to poll YouTube for updates
  809. if (!('timer' in player)) {
  810. player.timer = {};
  811. }
  812. // Setup instance
  813. // https://developers.google.com/youtube/iframe_api_reference
  814. player.embed = new YT.Player(container.id, {
  815. videoId: id,
  816. playerVars: {
  817. autoplay: 0,
  818. controls: (player.supported.full ? 0 : 1),
  819. rel: 0,
  820. showinfo: 0,
  821. iv_load_policy: 3,
  822. cc_load_policy: (config.captions.defaultActive ? 1 : 0),
  823. cc_lang_pref: 'en',
  824. wmode: 'transparent',
  825. modestbranding: 1,
  826. disablekb: 1
  827. },
  828. events: {
  829. 'onReady': function (event) {
  830. // Get the instance
  831. var instance = event.target;
  832. // Create a faux HTML5 API using the YouTube API
  833. player.media.play = function () {
  834. instance.playVideo();
  835. };
  836. player.media.pause = function () {
  837. instance.pauseVideo();
  838. };
  839. player.media.stop = function () {
  840. instance.stopVideo();
  841. };
  842. player.media.duration = instance.getDuration();
  843. player.media.paused = true;
  844. player.media.currentTime = instance.getCurrentTime();
  845. player.media.muted = instance.isMuted();
  846. // Trigger timeupdate
  847. _triggerEvent(player.media, 'timeupdate');
  848. // Reset timer
  849. window.clearInterval(player.timer.buffering);
  850. // Setup buffering
  851. player.timer.buffering = window.setInterval(function () {
  852. // Get loaded % from YouTube
  853. player.media.buffered = instance.getVideoLoadedFraction();
  854. // Trigger progress
  855. _triggerEvent(player.media, 'progress');
  856. // Bail if we're at 100%
  857. if (player.media.buffered === 1) {
  858. window.clearInterval(player.timer.buffering);
  859. }
  860. }, 200);
  861. if (player.supported.full) {
  862. // Only setup controls once
  863. if (!player.container.querySelectorAll(config.selectors.controls).length) {
  864. _setupInterface();
  865. }
  866. // Display duration if available
  867. if (config.displayDuration) {
  868. _displayDuration();
  869. }
  870. }
  871. },
  872. 'onStateChange': function (event) {
  873. // Get the instance
  874. var instance = event.target;
  875. // Reset timer
  876. window.clearInterval(player.timer.playing);
  877. // Handle events
  878. // -1 Unstarted
  879. // 0 Ended
  880. // 1 Playing
  881. // 2 Paused
  882. // 3 Buffering
  883. // 5 Video cued
  884. switch (event.data) {
  885. case 0:
  886. player.media.paused = true;
  887. _triggerEvent(player.media, 'ended');
  888. break;
  889. case 1:
  890. player.media.paused = false;
  891. _triggerEvent(player.media, 'play');
  892. // Poll to get playback progress
  893. player.timer.playing = window.setInterval(function () {
  894. // Set the current time
  895. player.media.currentTime = instance.getCurrentTime();
  896. // Trigger timeupdate
  897. _triggerEvent(player.media, 'timeupdate');
  898. }, 200);
  899. break;
  900. case 2:
  901. player.media.paused = true;
  902. _triggerEvent(player.media, 'pause');
  903. }
  904. }
  905. }
  906. });
  907. }
  908. // Setup captions
  909. function _setupCaptions() {
  910. if (player.type === 'video') {
  911. // Inject the container
  912. player.videoContainer.insertAdjacentHTML('afterbegin', '<div class="' + config.selectors.captions.replace('.', '') + '"><span></span></div>');
  913. // Cache selector
  914. player.captionsContainer = _getElement(config.selectors.captions).querySelector('span');
  915. // Determine if HTML5 textTracks is supported
  916. player.usingTextTracks = false;
  917. if (player.media.textTracks) {
  918. player.usingTextTracks = true;
  919. }
  920. // Get URL of caption file if exists
  921. var captionSrc = '',
  922. kind,
  923. children = player.media.childNodes;
  924. for (var i = 0; i < children.length; i++) {
  925. if (children[i].nodeName.toLowerCase() === 'track') {
  926. kind = children[i].kind;
  927. if (kind === 'captions' || kind === 'subtitles') {
  928. captionSrc = children[i].getAttribute('src');
  929. }
  930. }
  931. }
  932. // Record if caption file exists or not
  933. player.captionExists = true;
  934. if (captionSrc === '') {
  935. player.captionExists = false;
  936. _log('No caption track found.');
  937. } else {
  938. _log('Caption track found; URI: ' + captionSrc);
  939. }
  940. // If no caption file exists, hide container for caption text
  941. if (!player.captionExists) {
  942. _toggleClass(player.container, config.classes.captions.enabled);
  943. }
  944. // If caption file exists, process captions
  945. else {
  946. // Turn off native caption rendering to avoid double captions
  947. // This doesn't seem to work in Safari 7+, so the <track> elements are removed from the dom below
  948. var tracks = player.media.textTracks;
  949. for (var x = 0; x < tracks.length; x++) {
  950. tracks[x].mode = 'hidden';
  951. }
  952. // Enable UI
  953. _showCaptions(player);
  954. // Disable unsupported browsers than report false positive
  955. if ((player.browser.name === 'IE' && player.browser.version >= 10) ||
  956. (player.browser.name === 'Firefox' && player.browser.version >= 31) ||
  957. (player.browser.name === 'Chrome' && player.browser.version >= 43) ||
  958. (player.browser.name === 'Safari' && player.browser.version >= 7)) {
  959. // Debugging
  960. _log('Detected unsupported browser for HTML5 captions. Using fallback.');
  961. // Set to false so skips to 'manual' captioning
  962. player.usingTextTracks = false;
  963. }
  964. // Rendering caption tracks
  965. // Native support required - http://caniuse.com/webvtt
  966. if (player.usingTextTracks) {
  967. _log('TextTracks supported.');
  968. for (var y = 0; y < tracks.length; y++) {
  969. var track = tracks[y];
  970. if (track.kind === 'captions' || track.kind === 'subtitles') {
  971. _on(track, 'cuechange', function () {
  972. // Clear container
  973. player.captionsContainer.innerHTML = '';
  974. // Display a cue, if there is one
  975. if (this.activeCues[0] && this.activeCues[0].hasOwnProperty('text')) {
  976. player.captionsContainer.appendChild(this.activeCues[0].getCueAsHTML().trim());
  977. }
  978. });
  979. }
  980. }
  981. }
  982. // Caption tracks not natively supported
  983. else {
  984. _log('TextTracks not supported so rendering captions manually.');
  985. // Render captions from array at appropriate time
  986. player.currentCaption = '';
  987. player.captions = [];
  988. if (captionSrc !== '') {
  989. // Create XMLHttpRequest Object
  990. var xhr = new XMLHttpRequest();
  991. xhr.onreadystatechange = function () {
  992. if (xhr.readyState === 4) {
  993. if (xhr.status === 200) {
  994. var records = [],
  995. record,
  996. req = xhr.responseText;
  997. records = req.split('\n\n');
  998. for (var r = 0; r < records.length; r++) {
  999. record = records[r];
  1000. player.captions[r] = [];
  1001. player.captions[r] = record.split('\n');
  1002. }
  1003. // Remove first element ('VTT')
  1004. player.captions.shift();
  1005. _log('Successfully loaded the caption file via AJAX.');
  1006. } else {
  1007. _log('There was a problem loading the caption file via AJAX.', true);
  1008. }
  1009. }
  1010. };
  1011. xhr.open('get', captionSrc, true);
  1012. xhr.send();
  1013. }
  1014. }
  1015. // If Safari 7+, removing track from DOM [see 'turn off native caption rendering' above]
  1016. if (player.browser.name === 'Safari' && player.browser.version >= 7) {
  1017. _log('Safari 7+ detected; removing track from DOM.');
  1018. // Find all <track> elements
  1019. tracks = player.media.getElementsByTagName('track');
  1020. // Loop through and remove one by one
  1021. for (var t = 0; t < tracks.length; t++) {
  1022. player.media.removeChild(tracks[t]);
  1023. }
  1024. }
  1025. }
  1026. }
  1027. }
  1028. // Setup fullscreen
  1029. function _setupFullscreen() {
  1030. if (player.type != 'audio' && config.fullscreen.enabled) {
  1031. // Check for native support
  1032. var nativeSupport = fullscreen.supportsFullScreen;
  1033. if (nativeSupport || (config.fullscreen.fallback && !_inFrame())) {
  1034. _log((nativeSupport ? 'Native' : 'Fallback') + ' fullscreen enabled.');
  1035. // Add styling hook
  1036. _toggleClass(player.container, config.classes.fullscreen.enabled, true);
  1037. } else {
  1038. _log('Fullscreen not supported and fallback disabled.');
  1039. }
  1040. // Toggle state
  1041. _toggleState(player.buttons.fullscreen, false);
  1042. // Set control hide class hook
  1043. if (config.fullscreen.hideControls) {
  1044. _toggleClass(player.container, config.classes.fullscreen.hideControls, true);
  1045. }
  1046. }
  1047. }
  1048. // Play media
  1049. function _play() {
  1050. player.media.play();
  1051. }
  1052. // Pause media
  1053. function _pause() {
  1054. player.media.pause();
  1055. }
  1056. // Toggle playback
  1057. function _togglePlay(toggle) {
  1058. // Play
  1059. if (toggle === true) {
  1060. _play();
  1061. }
  1062. // Pause
  1063. else if (toggle === false) {
  1064. _pause();
  1065. }
  1066. // True toggle
  1067. else {
  1068. player.media[player.media.paused ? 'play' : 'pause']();
  1069. }
  1070. }
  1071. // Rewind
  1072. function _rewind(seekTime) {
  1073. // Use default if needed
  1074. if (typeof seekTime !== 'number') {
  1075. seekTime = config.seekTime;
  1076. }
  1077. _seek(player.media.currentTime - seekTime);
  1078. }
  1079. // Fast forward
  1080. function _forward(seekTime) {
  1081. // Use default if needed
  1082. if (typeof seekTime !== 'number') {
  1083. seekTime = config.seekTime;
  1084. }
  1085. _seek(player.media.currentTime + seekTime);
  1086. }
  1087. // Seek to time
  1088. // The input parameter can be an event or a number
  1089. function _seek(input) {
  1090. var targetTime = 0,
  1091. paused = player.media.paused;
  1092. // Explicit position
  1093. if (typeof input === 'number') {
  1094. targetTime = input;
  1095. }
  1096. // Event
  1097. else if (typeof input === 'object' && (input.type === 'input' || input.type === 'change')) {
  1098. // It's the seek slider
  1099. // Seek to the selected time
  1100. targetTime = ((input.target.value / input.target.max) * player.media.duration);
  1101. }
  1102. // Normalise targetTime
  1103. if (targetTime < 0) {
  1104. targetTime = 0;
  1105. } else if (targetTime > player.media.duration) {
  1106. targetTime = player.media.duration;
  1107. }
  1108. // Set the current time
  1109. // Try/catch incase the media isn't set and we're calling seek() from source() and IE moans
  1110. try {
  1111. player.media.currentTime = targetTime.toFixed(1);
  1112. } catch (e) {}
  1113. // YouTube
  1114. if (player.type == 'youtube') {
  1115. player.embed.seekTo(targetTime);
  1116. if (paused) {
  1117. _pause();
  1118. }
  1119. // Trigger timeupdate
  1120. _triggerEvent(player.media, 'timeupdate');
  1121. }
  1122. // Logging
  1123. _log('Seeking to ' + player.media.currentTime + ' seconds');
  1124. // Special handling for 'manual' captions
  1125. _seekManualCaptions(targetTime);
  1126. }
  1127. // Check playing state
  1128. function _checkPlaying() {
  1129. _toggleClass(player.container, config.classes.playing, !player.media.paused);
  1130. _toggleClass(player.container, config.classes.stopped, player.media.paused);
  1131. }
  1132. // Toggle fullscreen
  1133. function _toggleFullscreen(event) {
  1134. // Check for native support
  1135. var nativeSupport = fullscreen.supportsFullScreen;
  1136. // If it's a fullscreen change event, it's probably a native close
  1137. if (event && event.type === fullscreen.fullScreenEventName) {
  1138. player.isFullscreen = fullscreen.isFullScreen(player.container);
  1139. }
  1140. // If there's native support, use it
  1141. else if (nativeSupport) {
  1142. // Request fullscreen
  1143. if (!fullscreen.isFullScreen(player.container)) {
  1144. fullscreen.requestFullScreen(player.container);
  1145. }
  1146. // Bail from fullscreen
  1147. else {
  1148. fullscreen.cancelFullScreen();
  1149. }
  1150. // Check if we're actually full screen (it could fail)
  1151. player.isFullscreen = fullscreen.isFullScreen(player.container);
  1152. } else {
  1153. // Otherwise, it's a simple toggle
  1154. player.isFullscreen = !player.isFullscreen;
  1155. // Bind/unbind escape key
  1156. if (player.isFullscreen) {
  1157. _on(document, 'keyup', _handleEscapeFullscreen);
  1158. document.body.style.overflow = 'hidden';
  1159. } else {
  1160. _off(document, 'keyup', _handleEscapeFullscreen);
  1161. document.body.style.overflow = '';
  1162. }
  1163. }
  1164. // Set class hook
  1165. _toggleClass(player.container, config.classes.fullscreen.active, player.isFullscreen);
  1166. // Set button state
  1167. _toggleState(player.buttons.fullscreen, player.isFullscreen);
  1168. // Toggle controls visibility based on mouse movement and location
  1169. var hoverTimer, isMouseOver = false;
  1170. // Show the player controls
  1171. function _showControls() {
  1172. // Set shown class
  1173. _toggleClass(player.container, config.classes.hover, true);
  1174. // Clear timer every movement
  1175. window.clearTimeout(hoverTimer);
  1176. // If the mouse is not over the controls, set a timeout to hide them
  1177. if (!isMouseOver) {
  1178. hoverTimer = window.setTimeout(function () {
  1179. _toggleClass(player.container, config.classes.hover, false);
  1180. }, 2000);
  1181. }
  1182. }
  1183. // Check mouse is over the controls
  1184. function _setMouseOver(event) {
  1185. isMouseOver = (event.type === 'mouseenter');
  1186. }
  1187. if (config.fullscreen.hideControls) {
  1188. // Hide on entering full screen
  1189. _toggleClass(player.controls, config.classes.hover, false);
  1190. // Keep an eye on the mouse location in relation to controls
  1191. _toggleHandler(player.controls, 'mouseenter mouseleave', _setMouseOver, player.isFullscreen);
  1192. // Show the controls on mouse move
  1193. _toggleHandler(player.container, 'mousemove', _showControls, player.isFullscreen);
  1194. }
  1195. }
  1196. // Bail from faux-fullscreen
  1197. function _handleEscapeFullscreen(event) {
  1198. // If it's a keypress and not escape, bail
  1199. if ((event.which || event.charCode || event.keyCode) === 27 && player.isFullscreen) {
  1200. _toggleFullscreen();
  1201. }
  1202. }
  1203. // Set volume
  1204. function _setVolume(volume) {
  1205. // Use default if no value specified
  1206. if (typeof volume === 'undefined') {
  1207. if (config.storage.enabled && _storage().supported) {
  1208. volume = window.localStorage[config.storage.key] || config.volume;
  1209. } else {
  1210. volume = config.volume;
  1211. }
  1212. }
  1213. // Maximum is 10
  1214. if (volume > 10) {
  1215. volume = 10;
  1216. }
  1217. // Minimum is 0
  1218. if (volume < 0) {
  1219. volume = 0;
  1220. }
  1221. // Set the player volume
  1222. player.media.volume = parseFloat(volume / 10);
  1223. // YouTube
  1224. if (player.type == 'youtube') {
  1225. player.embed.setVolume(player.media.volume * 100);
  1226. // Trigger timeupdate
  1227. _triggerEvent(player.media, 'volumechange');
  1228. }
  1229. // Toggle muted state
  1230. if (player.media.muted && volume > 0) {
  1231. _toggleMute();
  1232. }
  1233. }
  1234. // Mute
  1235. function _toggleMute(muted) {
  1236. // If the method is called without parameter, toggle based on current value
  1237. if (typeof muted !== 'boolean') {
  1238. muted = !player.media.muted;
  1239. }
  1240. // Set button state
  1241. _toggleState(player.buttons.mute, muted);
  1242. // Set mute on the player
  1243. player.media.muted = muted;
  1244. // YouTube
  1245. if (player.type === 'youtube') {
  1246. player.embed[player.media.muted ? 'mute' : 'unMute']();
  1247. // Trigger timeupdate
  1248. _triggerEvent(player.media, 'volumechange');
  1249. }
  1250. }
  1251. // Update volume UI and storage
  1252. function _updateVolume() {
  1253. // Get the current volume
  1254. var volume = player.media.muted ? 0 : (player.media.volume * 10);
  1255. // Update the <input type="range"> if present
  1256. if (player.supported.full && player.volume) {
  1257. player.volume.value = volume;
  1258. }
  1259. // Store the volume in storage
  1260. if (config.storage.enabled && _storage().supported) {
  1261. window.localStorage.setItem(config.storage.key, volume);
  1262. }
  1263. // Toggle class if muted
  1264. _toggleClass(player.container, config.classes.muted, (volume === 0));
  1265. // Update checkbox for mute state
  1266. if (player.supported.full && player.buttons.mute) {
  1267. _toggleState(player.buttons.mute, (volume === 0));
  1268. }
  1269. }
  1270. // Toggle captions
  1271. function _toggleCaptions(show) {
  1272. // If there's no full support, or there's no caption toggle
  1273. if (!player.supported.full || !player.buttons.captions) {
  1274. return;
  1275. }
  1276. // If the method is called without parameter, toggle based on current value
  1277. if (typeof show !== 'boolean') {
  1278. show = (player.container.className.indexOf(config.classes.captions.active) === -1);
  1279. }
  1280. // Toggle state
  1281. _toggleState(player.buttons.captions, show);
  1282. // Add class hook
  1283. _toggleClass(player.container, config.classes.captions.active, show);
  1284. }
  1285. // Check if media is loading
  1286. function _checkLoading(event) {
  1287. var loading = (event.type === 'waiting');
  1288. // Clear timer
  1289. clearTimeout(player.loadingTimer);
  1290. // Timer to prevent flicker when seeking
  1291. player.loadingTimer = setTimeout(function () {
  1292. _toggleClass(player.container, config.classes.loading, loading);
  1293. }, (loading ? 250 : 0));
  1294. }
  1295. // Update <progress> elements
  1296. function _updateProgress(event) {
  1297. var progress = player.progress.played.bar,
  1298. text = player.progress.played.text,
  1299. value = 0;
  1300. if (event) {
  1301. switch (event.type) {
  1302. // Video playing
  1303. case 'timeupdate':
  1304. case 'seeking':
  1305. value = _getPercentage(player.media.currentTime, player.media.duration);
  1306. // Set seek range value only if it's a 'natural' time event
  1307. if (event.type == 'timeupdate' && player.buttons.seek) {
  1308. player.buttons.seek.value = value;
  1309. }
  1310. break;
  1311. // Events from seek range
  1312. case 'change':
  1313. case 'input':
  1314. value = event.target.value;
  1315. break;
  1316. // Check buffer status
  1317. case 'playing':
  1318. case 'progress':
  1319. progress = player.progress.buffer.bar;
  1320. text = player.progress.buffer.text;
  1321. value = (function () {
  1322. var buffered = player.media.buffered;
  1323. // HTML5
  1324. if (buffered && buffered.length) {
  1325. return _getPercentage(buffered.end(0), player.media.duration);
  1326. }
  1327. // YouTube returns between 0 and 1
  1328. else if (typeof buffered === 'number') {
  1329. return (buffered * 100);
  1330. }
  1331. return 0;
  1332. })();
  1333. }
  1334. }
  1335. // Set values
  1336. if (progress) {
  1337. progress.value = value;
  1338. }
  1339. if (text) {
  1340. text.innerHTML = value;
  1341. }
  1342. }
  1343. // Update the displayed time
  1344. function _updateTimeDisplay(time, element) {
  1345. // Bail if there's no duration display
  1346. if (!element) {
  1347. return;
  1348. }
  1349. player.secs = parseInt(time % 60);
  1350. player.mins = parseInt((time / 60) % 60);
  1351. player.hours = parseInt(((time / 60) / 60) % 60);
  1352. // Do we need to display hours?
  1353. var displayHours = (parseInt(((player.media.duration / 60) / 60) % 60) > 0);
  1354. // Ensure it's two digits. For example, 03 rather than 3.
  1355. player.secs = ('0' + player.secs).slice(-2);
  1356. player.mins = ('0' + player.mins).slice(-2);
  1357. // Render
  1358. element.innerHTML = (displayHours ? player.hours + ':' : '') + player.mins + ':' + player.secs;
  1359. }
  1360. // Show the duration on metadataloaded
  1361. function _displayDuration() {
  1362. var duration = player.media.duration || 0;
  1363. // If there's only one time display, display duration there
  1364. if (!player.duration && config.displayDuration && player.media.paused) {
  1365. _updateTimeDisplay(duration, player.currentTime);
  1366. }
  1367. // If there's a duration element, update content
  1368. if (player.duration) {
  1369. _updateTimeDisplay(duration, player.duration);
  1370. }
  1371. }
  1372. // Handle time change event
  1373. function _timeUpdate(event) {
  1374. // Duration
  1375. _updateTimeDisplay(player.media.currentTime, player.currentTime);
  1376. // Playing progress
  1377. _updateProgress(event);
  1378. }
  1379. // Remove <source> children and src attribute
  1380. function _removeSources() {
  1381. // Find child <source> elements
  1382. var sources = player.media.querySelectorAll('source');
  1383. // Remove each
  1384. for (var i = sources.length - 1; i >= 0; i--) {
  1385. _remove(sources[i]);
  1386. }
  1387. // Remove src attribute
  1388. player.media.removeAttribute('src');
  1389. }
  1390. // Inject a source
  1391. function _addSource(attributes) {
  1392. if (attributes.src) {
  1393. // Create a new <source>
  1394. var element = document.createElement('source');
  1395. // Set all passed attributes
  1396. _setAttributes(element, attributes);
  1397. // Inject the new source
  1398. _prependChild(player.media, element);
  1399. }
  1400. }
  1401. // Update source
  1402. // Sources are not checked for support so be careful
  1403. function _parseSource(sources) {
  1404. // YouTube
  1405. if (player.type === 'youtube' && typeof sources === 'string') {
  1406. // Destroy YouTube instance
  1407. player.embed.destroy();
  1408. // Re-setup YouTube
  1409. // We don't use loadVideoBy[x] here since it has issues
  1410. _setupYouTube(sources);
  1411. // Update times
  1412. _timeUpdate();
  1413. // Bail
  1414. return;
  1415. }
  1416. // Pause playback (webkit freaks out)
  1417. _pause();
  1418. // Restart
  1419. _seek();
  1420. // Remove current sources
  1421. _removeSources();
  1422. // If a single source is passed
  1423. // .source('path/to/video.mp4')
  1424. if (typeof sources === 'string') {
  1425. _addSource({
  1426. src: sources
  1427. });
  1428. }
  1429. // An array of source objects
  1430. // Check if a source exists, use that or set the 'src' attribute?
  1431. // .source([{ src: 'path/to/video.mp4', type: 'video/mp4' },{ src: 'path/to/video.webm', type: 'video/webm' }])
  1432. else if (sources.constructor === Array) {
  1433. for (var index in sources) {
  1434. _addSource(sources[index]);
  1435. }
  1436. }
  1437. if (player.supported.full) {
  1438. // Reset time display
  1439. _timeUpdate();
  1440. // Update the UI
  1441. _checkPlaying();
  1442. }
  1443. // Re-load sources
  1444. player.media.load();
  1445. // Play if autoplay attribute is present
  1446. if (player.media.getAttribute('autoplay') !== null) {
  1447. _play();
  1448. }
  1449. }
  1450. // Update poster
  1451. function _updatePoster(source) {
  1452. if (player.type === 'video') {
  1453. player.media.setAttribute('poster', source);
  1454. }
  1455. }
  1456. // Listen for events
  1457. function _listeners() {
  1458. // IE doesn't support input event, so we fallback to change
  1459. var inputEvent = (player.browser.name == 'IE' ? 'change' : 'input');
  1460. // Detect tab focus
  1461. function checkFocus() {
  1462. var focused = document.activeElement;
  1463. if (!focused || focused == document.body) {
  1464. focused = null;
  1465. } else if (document.querySelector) {
  1466. focused = document.querySelector(':focus');
  1467. }
  1468. for (var button in player.buttons) {
  1469. var element = player.buttons[button];
  1470. _toggleClass(element, 'tab-focus', (element === focused));
  1471. }
  1472. }
  1473. _on(window, 'keyup', function (event) {
  1474. var code = (event.keyCode ? event.keyCode : event.which);
  1475. if (code == 9) {
  1476. checkFocus();
  1477. }
  1478. });
  1479. for (var button in player.buttons) {
  1480. var element = player.buttons[button];
  1481. _on(element, 'blur', function () {
  1482. _toggleClass(element, 'tab-focus', false);
  1483. });
  1484. }
  1485. // Play
  1486. _on(player.buttons.play, 'click', function () {
  1487. _play();
  1488. setTimeout(function () {
  1489. player.buttons.pause.focus();
  1490. }, 100);
  1491. });
  1492. // Pause
  1493. _on(player.buttons.pause, 'click', function () {
  1494. _pause();
  1495. setTimeout(function () {
  1496. player.buttons.play.focus();
  1497. }, 100);
  1498. });
  1499. // Restart
  1500. _on(player.buttons.restart, 'click', _seek);
  1501. // Rewind
  1502. _on(player.buttons.rewind, 'click', _rewind);
  1503. // Fast forward
  1504. _on(player.buttons.forward, 'click', _forward);
  1505. // Seek
  1506. _on(player.buttons.seek, inputEvent, _seek);
  1507. // Set volume
  1508. _on(player.volume, inputEvent, function () {
  1509. _setVolume(this.value);
  1510. });
  1511. // Mute
  1512. _on(player.buttons.mute, 'click', _toggleMute);
  1513. // Fullscreen
  1514. _on(player.buttons.fullscreen, 'click', _toggleFullscreen);
  1515. // Handle user exiting fullscreen by escaping etc
  1516. if (fullscreen.supportsFullScreen) {
  1517. _on(document, fullscreen.fullScreenEventName, _toggleFullscreen);
  1518. }
  1519. // Time change on media
  1520. _on(player.media, 'timeupdate seeking', _timeUpdate);
  1521. // Update manual captions
  1522. _on(player.media, 'timeupdate', _seekManualCaptions);
  1523. // Display duration
  1524. _on(player.media, 'loadedmetadata', _displayDuration);
  1525. // Captions
  1526. _on(player.buttons.captions, 'click', _toggleCaptions);
  1527. // Handle the media finishing
  1528. _on(player.media, 'ended', function () {
  1529. // Clear
  1530. if (player.type === 'video') {
  1531. player.captionsContainer.innerHTML = '';
  1532. }
  1533. // Reset UI
  1534. _checkPlaying();
  1535. });
  1536. // Check for buffer progress
  1537. _on(player.media, 'progress playing', _updateProgress);
  1538. // Handle native mute
  1539. _on(player.media, 'volumechange', _updateVolume);
  1540. // Handle native play/pause
  1541. _on(player.media, 'play pause', _checkPlaying);
  1542. // Loading
  1543. _on(player.media, 'waiting canplay seeked', _checkLoading);
  1544. // Click video
  1545. if (player.type === 'video' && config.click) {
  1546. _on(player.videoContainer, 'click', function () {
  1547. if (player.media.paused) {
  1548. _triggerEvent(player.buttons.play, 'click');
  1549. } else if (player.media.ended) {
  1550. _seek();
  1551. _triggerEvent(player.buttons.play, 'click');
  1552. } else {
  1553. _triggerEvent(player.buttons.pause, 'click');
  1554. }
  1555. });
  1556. }
  1557. }
  1558. // Destroy an instance
  1559. // Event listeners are removed when elements are removed
  1560. // http://stackoverflow.com/questions/12528049/if-a-dom-element-is-removed-are-its-listeners-also-removed-from-memory
  1561. function _destroy() {
  1562. // Bail if the element is not initialized
  1563. if (!player.init) {
  1564. return null;
  1565. }
  1566. // Reset container classname
  1567. player.container.setAttribute('class', config.selectors.container.replace('.', ''));
  1568. // Remove init flag
  1569. player.init = false;
  1570. // Remove controls
  1571. _remove(_getElement(config.selectors.controls));
  1572. // YouTube
  1573. if (player.type === 'youtube') {
  1574. player.embed.destroy();
  1575. return;
  1576. }
  1577. // If video, we need to remove some more
  1578. if (player.type === 'video') {
  1579. // Remove captions
  1580. _remove(_getElement(config.selectors.captions));
  1581. // Remove video wrapper
  1582. _unwrap(player.videoContainer);
  1583. }
  1584. // Restore native video controls
  1585. player.media.setAttribute('controls', '');
  1586. // Clone the media element to remove listeners
  1587. // http://stackoverflow.com/questions/19469881/javascript-remove-all-event-listeners-of-specific-type
  1588. var clone = player.media.cloneNode(true);
  1589. player.media.parentNode.replaceChild(clone, player.media);
  1590. }
  1591. // Setup a player
  1592. function _init() {
  1593. // Bail if the element is initialized
  1594. if (player.init) {
  1595. return null;
  1596. }
  1597. // Setup the fullscreen api
  1598. fullscreen = _fullscreen();
  1599. // Sniff out the browser
  1600. player.browser = _browserSniff();
  1601. // Get the media element
  1602. player.media = player.container.querySelectorAll('audio, video, div')[0];
  1603. // Set media type
  1604. var tagName = player.media.tagName.toLowerCase();
  1605. if (tagName === 'div') {
  1606. player.type = player.media.getAttribute('data-type');
  1607. } else {
  1608. player.type = tagName;
  1609. }
  1610. // Check for full support
  1611. player.supported = api.supported(player.type);
  1612. // If no native support, bail
  1613. if (!player.supported.basic) {
  1614. return false;
  1615. }
  1616. // Debug info
  1617. _log(player.browser.name + ' ' + player.browser.version);
  1618. // Setup media
  1619. _setupMedia();
  1620. // Setup interface
  1621. if (player.type == 'video' || player.type == 'audio') {
  1622. // Bail if no support
  1623. if (!player.supported.full) {
  1624. // Successful setup
  1625. player.init = true;
  1626. // Don't inject controls if no full support
  1627. return;
  1628. }
  1629. // Setup UI
  1630. _setupInterface();
  1631. // Display duration if available
  1632. if (config.displayDuration) {
  1633. _displayDuration();
  1634. }
  1635. // Set up aria-label for Play button with the title option
  1636. _setupPlayAria();
  1637. }
  1638. // Successful setup
  1639. player.init = true;
  1640. }
  1641. function _setupInterface() {
  1642. // Inject custom controls
  1643. _injectControls();
  1644. // Find the elements
  1645. if (!_findElements()) {
  1646. return false;
  1647. }
  1648. // Captions
  1649. _setupCaptions();
  1650. // Set volume
  1651. _setVolume();
  1652. _updateVolume();
  1653. // Setup fullscreen
  1654. _setupFullscreen();
  1655. // Listeners
  1656. _listeners();
  1657. }
  1658. // Initialize instance
  1659. _init();
  1660. // If init failed, return an empty object
  1661. if (!player.init) {
  1662. return {};
  1663. }
  1664. return {
  1665. media: player.media,
  1666. play: _play,
  1667. pause: _pause,
  1668. restart: _seek,
  1669. rewind: _rewind,
  1670. forward: _forward,
  1671. seek: _seek,
  1672. source: _parseSource,
  1673. poster: _updatePoster,
  1674. setVolume: _setVolume,
  1675. togglePlay: _togglePlay,
  1676. toggleMute: _toggleMute,
  1677. toggleCaptions: _toggleCaptions,
  1678. toggleFullscreen: _toggleFullscreen,
  1679. isFullscreen: function () {
  1680. return player.isFullscreen || false;
  1681. },
  1682. support: function (mimeType) {
  1683. return _supportMime(player, mimeType);
  1684. },
  1685. destroy: _destroy,
  1686. restore: _init
  1687. };
  1688. }
  1689. // Check for support
  1690. api.supported = function (type) {
  1691. var browser = _browserSniff(),
  1692. oldIE = (browser.name === 'IE' && browser.version <= 9),
  1693. iPhone = /iPhone|iPod/i.test(navigator.userAgent),
  1694. audio = !!document.createElement('audio').canPlayType,
  1695. video = !!document.createElement('video').canPlayType,
  1696. basic, full;
  1697. switch (type) {
  1698. case 'video':
  1699. basic = video;
  1700. full = (basic && (!oldIE && !iPhone));
  1701. break;
  1702. case 'audio':
  1703. basic = audio;
  1704. full = (basic && !oldIE);
  1705. break;
  1706. case 'youtube':
  1707. basic = true;
  1708. full = (!oldIE && !iPhone);
  1709. break;
  1710. default:
  1711. basic = (audio && video);
  1712. full = (basic && !oldIE);
  1713. }
  1714. return {
  1715. basic: basic,
  1716. full: full
  1717. };
  1718. };
  1719. // Expose setup function
  1720. api.setup = function (options) {
  1721. // Extend the default options with user specified
  1722. config = _extend(defaults, options);
  1723. // Bail if disabled or no basic support
  1724. // You may want to disable certain UAs etc
  1725. if (!config.enabled || !api.supported().basic) {
  1726. return false;
  1727. }
  1728. // Get the players
  1729. var elements = document.querySelectorAll(config.selectors.container),
  1730. players = [];
  1731. // Create a player instance for each element
  1732. for (var i = elements.length - 1; i >= 0; i--) {
  1733. // Get the current element
  1734. var element = elements[i];
  1735. // Setup a player instance and add to the element
  1736. if (typeof element.plyr === 'undefined') {
  1737. // Create new instance
  1738. var instance = new Plyr(element);
  1739. // Set plyr to false if setup failed
  1740. element.plyr = (Object.keys(instance).length ? instance : false);
  1741. // Callback
  1742. if (typeof config.onSetup === 'function') {
  1743. config.onSetup.apply(element.plyr);
  1744. }
  1745. }
  1746. // Add to return array even if it's already setup
  1747. players.push(element.plyr);
  1748. }
  1749. return players;
  1750. };
  1751. }(this.plyr = this.plyr || {}));