UNPKG

player-56s

Version:

Web audio-player with playlist and minimalistic view as option

1,413 lines (1,312 loc) 121 kB
/* * jPlayer Plugin for jQuery JavaScript Library * http://www.jplayer.org * * Copyright (c) 2009 - 2014 Happyworm Ltd * Licensed under the MIT license. * http://opensource.org/licenses/MIT * * Author: Mark J Panaghiston * Version: 2.9.2 * Date: 14th December 2014 */ /* Support for Zepto 1.0 compiled with optional data module. * For AMD or NODE/CommonJS support, you will need to manually switch the related 2 lines in the code below. * Search terms: "jQuery Switch" and "Zepto Switch" */ (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); // jQuery Switch // define(['zepto'], factory); // Zepto Switch } else if (typeof exports === 'object') { // Node/CommonJS factory(require('jquery')); // jQuery Switch //factory(require('zepto')); // Zepto Switch } else { // Browser globals if(root.jQuery) { // Use jQuery if available factory(root.jQuery); } else { // Otherwise, use Zepto factory(root.Zepto); } } }(this, function ($, undefined) { // Adapted from jquery.ui.widget.js (1.8.7): $.widget.bridge - Tweaked $.data(this,XYZ) to $(this).data(XYZ) for Zepto $.fn.jPlayer = function( options ) { var name = "jPlayer"; var isMethodCall = typeof options === "string", args = Array.prototype.slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.extend.apply( null, [ true, options ].concat(args) ) : options; // prevent calls to internal methods if ( isMethodCall && options.charAt( 0 ) === "_" ) { return returnValue; } if ( isMethodCall ) { this.each(function() { var instance = $(this).data( name ), methodValue = instance && $.isFunction( instance[options] ) ? instance[ options ].apply( instance, args ) : instance; if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue; return false; } }); } else { this.each(function() { var instance = $(this).data( name ); if ( instance ) { // instance.option( options || {} )._init(); // Orig jquery.ui.widget.js code: Not recommend for jPlayer. ie., Applying new options to an existing instance (via the jPlayer constructor) and performing the _init(). The _init() is what concerns me. It would leave a lot of event handlers acting on jPlayer instance and the interface. instance.option( options || {} ); // The new constructor only changes the options. Changing options only has basic support atm. } else { $(this).data( name, new $.jPlayer( options, this ) ); } }); } return returnValue; }; $.jPlayer = function( options, element ) { // allow instantiation without initializing for simple inheritance if ( arguments.length ) { this.element = $(element); this.options = $.extend(true, {}, this.options, options ); var self = this; this.element.bind( "remove.jPlayer", function() { self.destroy(); }); this._init(); } }; // End of: (Adapted from jquery.ui.widget.js (1.8.7)) // Zepto is missing one of the animation methods. if(typeof $.fn.stop !== 'function') { $.fn.stop = function() {}; } // Emulated HTML5 methods and properties $.jPlayer.emulateMethods = "load play pause"; $.jPlayer.emulateStatus = "src readyState networkState currentTime duration paused ended playbackRate"; $.jPlayer.emulateOptions = "muted volume"; // Reserved event names generated by jPlayer that are not part of the HTML5 Media element spec $.jPlayer.reservedEvent = "ready flashreset resize repeat error warning"; // Events generated by jPlayer $.jPlayer.event = {}; $.each( [ 'ready', 'setmedia', // Fires when the media is set 'flashreset', // Similar to the ready event if the Flash solution is set to display:none and then shown again or if it's reloaded for another reason by the browser. For example, using CSS position:fixed on Firefox for the full screen feature. 'resize', // Occurs when the size changes through a full/restore screen operation or if the size/sizeFull options are changed. 'repeat', // Occurs when the repeat status changes. Usually through clicks on the repeat button of the interface. 'click', // Occurs when the user clicks on one of the following: poster image, html video, flash video. 'error', // Event error code in event.jPlayer.error.type. See $.jPlayer.error 'warning', // Event warning code in event.jPlayer.warning.type. See $.jPlayer.warning // Other events match HTML5 spec. 'loadstart', 'progress', 'suspend', 'abort', 'emptied', 'stalled', 'play', 'pause', 'loadedmetadata', 'loadeddata', 'waiting', 'playing', 'canplay', 'canplaythrough', 'seeking', 'seeked', 'timeupdate', 'ended', 'ratechange', 'durationchange', 'volumechange' ], function() { $.jPlayer.event[ this ] = 'jPlayer_' + this; } ); $.jPlayer.htmlEvent = [ // These HTML events are bubbled through to the jPlayer event, without any internal action. "loadstart", // "progress", // jPlayer uses internally before bubbling. // "suspend", // jPlayer uses internally before bubbling. "abort", // "error", // jPlayer uses internally before bubbling. "emptied", "stalled", // "play", // jPlayer uses internally before bubbling. // "pause", // jPlayer uses internally before bubbling. "loadedmetadata", // "loadeddata", // jPlayer uses internally before bubbling. // "waiting", // jPlayer uses internally before bubbling. // "playing", // jPlayer uses internally before bubbling. "canplay", "canplaythrough" // "seeking", // jPlayer uses internally before bubbling. // "seeked", // jPlayer uses internally before bubbling. // "timeupdate", // jPlayer uses internally before bubbling. // "ended", // jPlayer uses internally before bubbling. // "ratechange" // jPlayer uses internally before bubbling. // "durationchange" // jPlayer uses internally before bubbling. // "volumechange" // jPlayer uses internally before bubbling. ]; $.jPlayer.pause = function() { $.jPlayer.prototype.destroyRemoved(); $.each($.jPlayer.prototype.instances, function(i, element) { if(element.data("jPlayer").status.srcSet) { // Check that media is set otherwise would cause error event. element.jPlayer("pause"); } }); }; // Default for jPlayer option.timeFormat $.jPlayer.timeFormat = { showHour: false, showMin: true, showSec: true, padHour: false, padMin: true, padSec: true, sepHour: ":", sepMin: ":", sepSec: "" }; var ConvertTime = function() { this.init(); }; ConvertTime.prototype = { init: function() { this.options = { timeFormat: $.jPlayer.timeFormat }; }, time: function(s) { // function used on jPlayer.prototype._convertTime to enable per instance options. s = (s && typeof s === 'number') ? s : 0; var myTime = new Date(s * 1000), hour = myTime.getUTCHours(), min = this.options.timeFormat.showHour ? myTime.getUTCMinutes() : myTime.getUTCMinutes() + hour * 60, sec = this.options.timeFormat.showMin ? myTime.getUTCSeconds() : myTime.getUTCSeconds() + min * 60, strHour = (this.options.timeFormat.padHour && hour < 10) ? "0" + hour : hour, strMin = (this.options.timeFormat.padMin && min < 10) ? "0" + min : min, strSec = (this.options.timeFormat.padSec && sec < 10) ? "0" + sec : sec, strTime = ""; strTime += this.options.timeFormat.showHour ? strHour + this.options.timeFormat.sepHour : ""; strTime += this.options.timeFormat.showMin ? strMin + this.options.timeFormat.sepMin : ""; strTime += this.options.timeFormat.showSec ? strSec + this.options.timeFormat.sepSec : ""; return strTime; } }; var myConvertTime = new ConvertTime(); $.jPlayer.convertTime = function(s) { return myConvertTime.time(s); }; // Adapting jQuery 1.4.4 code for jQuery.browser. Required since jQuery 1.3.2 does not detect Chrome as webkit. $.jPlayer.uaBrowser = function( userAgent ) { var ua = userAgent.toLowerCase(); // Useragent RegExp var rwebkit = /(webkit)[ \/]([\w.]+)/; var ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/; var rmsie = /(msie) ([\w.]+)/; var rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/; var match = rwebkit.exec( ua ) || ropera.exec( ua ) || rmsie.exec( ua ) || ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || []; return { browser: match[1] || "", version: match[2] || "0" }; }; // Platform sniffer for detecting mobile devices $.jPlayer.uaPlatform = function( userAgent ) { var ua = userAgent.toLowerCase(); // Useragent RegExp var rplatform = /(ipad|iphone|ipod|android|blackberry|playbook|windows ce|webos)/; var rtablet = /(ipad|playbook)/; var randroid = /(android)/; var rmobile = /(mobile)/; var platform = rplatform.exec( ua ) || []; var tablet = rtablet.exec( ua ) || !rmobile.exec( ua ) && randroid.exec( ua ) || []; if(platform[1]) { platform[1] = platform[1].replace(/\s/g, "_"); // Change whitespace to underscore. Enables dot notation. } return { platform: platform[1] || "", tablet: tablet[1] || "" }; }; $.jPlayer.browser = { }; $.jPlayer.platform = { }; var browserMatch = $.jPlayer.uaBrowser(navigator.userAgent); if ( browserMatch.browser ) { $.jPlayer.browser[ browserMatch.browser ] = true; $.jPlayer.browser.version = browserMatch.version; } var platformMatch = $.jPlayer.uaPlatform(navigator.userAgent); if ( platformMatch.platform ) { $.jPlayer.platform[ platformMatch.platform ] = true; $.jPlayer.platform.mobile = !platformMatch.tablet; $.jPlayer.platform.tablet = !!platformMatch.tablet; } // Internet Explorer (IE) Browser Document Mode Sniffer. Based on code at: // http://msdn.microsoft.com/en-us/library/cc288325%28v=vs.85%29.aspx#GetMode $.jPlayer.getDocMode = function() { var docMode; if ($.jPlayer.browser.msie) { if (document.documentMode) { // IE8 or later docMode = document.documentMode; } else { // IE 5-7 docMode = 5; // Assume quirks mode unless proven otherwise if (document.compatMode) { if (document.compatMode === "CSS1Compat") { docMode = 7; // standards mode } } } } return docMode; }; $.jPlayer.browser.documentMode = $.jPlayer.getDocMode(); $.jPlayer.nativeFeatures = { init: function() { /* Fullscreen function naming influenced by W3C naming. * No support for: Mozilla Proposal: https://wiki.mozilla.org/Gecko:FullScreenAPI */ var d = document, v = d.createElement('video'), spec = { // http://www.w3.org/TR/fullscreen/ w3c: [ 'fullscreenEnabled', 'fullscreenElement', 'requestFullscreen', 'exitFullscreen', 'fullscreenchange', 'fullscreenerror' ], // https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode moz: [ 'mozFullScreenEnabled', 'mozFullScreenElement', 'mozRequestFullScreen', 'mozCancelFullScreen', 'mozfullscreenchange', 'mozfullscreenerror' ], // http://developer.apple.com/library/safari/#documentation/WebKit/Reference/ElementClassRef/Element/Element.html // http://developer.apple.com/library/safari/#documentation/UserExperience/Reference/DocumentAdditionsReference/DocumentAdditions/DocumentAdditions.html webkit: [ '', 'webkitCurrentFullScreenElement', 'webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitfullscreenchange', '' ], // http://developer.apple.com/library/safari/#documentation/AudioVideo/Reference/HTMLVideoElementClassReference/HTMLVideoElement/HTMLVideoElement.html // https://developer.apple.com/library/safari/samplecode/HTML5VideoEventFlow/Listings/events_js.html#//apple_ref/doc/uid/DTS40010085-events_js-DontLinkElementID_5 // Events: 'webkitbeginfullscreen' and 'webkitendfullscreen' webkitVideo: [ 'webkitSupportsFullscreen', 'webkitDisplayingFullscreen', 'webkitEnterFullscreen', 'webkitExitFullscreen', '', '' ], ms: [ '', 'msFullscreenElement', 'msRequestFullscreen', 'msExitFullscreen', 'MSFullscreenChange', 'MSFullscreenError' ] }, specOrder = [ 'w3c', 'moz', 'webkit', 'webkitVideo', 'ms' ], fs, i, il; this.fullscreen = fs = { support: { w3c: !!d[spec.w3c[0]], moz: !!d[spec.moz[0]], webkit: typeof d[spec.webkit[3]] === 'function', webkitVideo: typeof v[spec.webkitVideo[2]] === 'function', ms: typeof v[spec.ms[2]] === 'function' }, used: {} }; // Store the name of the spec being used and as a handy boolean. for(i = 0, il = specOrder.length; i < il; i++) { var n = specOrder[i]; if(fs.support[n]) { fs.spec = n; fs.used[n] = true; break; } } if(fs.spec) { var s = spec[fs.spec]; fs.api = { fullscreenEnabled: true, fullscreenElement: function(elem) { elem = elem ? elem : d; // Video element required for webkitVideo return elem[s[1]]; }, requestFullscreen: function(elem) { return elem[s[2]](); // Chrome and Opera want parameter (Element.ALLOW_KEYBOARD_INPUT) but Safari fails if flag used. }, exitFullscreen: function(elem) { elem = elem ? elem : d; // Video element required for webkitVideo return elem[s[3]](); } }; fs.event = { fullscreenchange: s[4], fullscreenerror: s[5] }; } else { fs.api = { fullscreenEnabled: false, fullscreenElement: function() { return null; }, requestFullscreen: function() {}, exitFullscreen: function() {} }; fs.event = {}; } } }; $.jPlayer.nativeFeatures.init(); // The keyboard control system. // The current jPlayer instance in focus. $.jPlayer.focus = null; // The list of element node names to ignore with key controls. $.jPlayer.keyIgnoreElementNames = "A INPUT TEXTAREA SELECT BUTTON"; // The function that deals with key presses. var keyBindings = function(event) { var f = $.jPlayer.focus, ignoreKey; // A jPlayer instance must be in focus. ie., keyEnabled and the last one played. if(f) { // What generated the key press? $.each( $.jPlayer.keyIgnoreElementNames.split(/\s+/g), function(i, name) { // The strings should already be uppercase. if(event.target.nodeName.toUpperCase() === name.toUpperCase()) { ignoreKey = true; return false; // exit each. } }); if(!ignoreKey) { // See if the key pressed matches any of the bindings. $.each(f.options.keyBindings, function(action, binding) { // The binding could be a null when the default has been disabled. ie., 1st clause in if() if( (binding && $.isFunction(binding.fn)) && ((typeof binding.key === 'number' && event.which === binding.key) || (typeof binding.key === 'string' && event.key === binding.key)) ) { event.preventDefault(); // Key being used by jPlayer, so prevent default operation. binding.fn(f); return false; // exit each. } }); } } }; $.jPlayer.keys = function(en) { var event = "keydown.jPlayer"; // Remove any binding, just in case enabled more than once. $(document.documentElement).unbind(event); if(en) { $(document.documentElement).bind(event, keyBindings); } }; // Enable the global key control handler ready for any jPlayer instance with the keyEnabled option enabled. $.jPlayer.keys(true); $.jPlayer.prototype = { count: 0, // Static Variable: Change it via prototype. version: { // Static Object script: "2.9.2", needFlash: "2.9.0", flash: "unknown" }, options: { // Instanced in $.jPlayer() constructor swfPath: "js", // Path to jquery.jplayer.swf. Can be relative, absolute or server root relative. solution: "html, flash", // Valid solutions: html, flash, aurora. Order defines priority. 1st is highest, supplied: "mp3", // Defines which formats jPlayer will try and support and the priority by the order. 1st is highest, auroraFormats: "wav", // List the aurora.js codecs being loaded externally. Its core supports "wav". Specify format in jPlayer context. EG., The aac.js codec gives the "m4a" format. preload: 'metadata', // HTML5 Spec values: none, metadata, auto. volume: 0.8, // The volume. Number 0 to 1. muted: false, remainingDuration: false, // When true, the remaining time is shown in the duration GUI element. toggleDuration: false, // When true, clicks on the duration toggle between the duration and remaining display. captureDuration: true, // When true, clicks on the duration are captured and no longer propagate up the DOM. playbackRate: 1, defaultPlaybackRate: 1, minPlaybackRate: 0.5, maxPlaybackRate: 4, wmode: "opaque", // Valid wmode: window, transparent, opaque, direct, gpu. backgroundColor: "#000000", // To define the jPlayer div and Flash background color. cssSelectorAncestor: "#jp_container_1", cssSelector: { // * denotes properties that should only be required when video media type required. _cssSelector() would require changes to enable splitting these into Audio and Video defaults. videoPlay: ".jp-video-play", // * play: ".jp-play", pause: ".jp-pause", stop: ".jp-stop", seekBar: ".jp-seek-bar", playBar: ".jp-play-bar", mute: ".jp-mute", unmute: ".jp-unmute", volumeBar: ".jp-volume-bar", volumeBarValue: ".jp-volume-bar-value", volumeMax: ".jp-volume-max", playbackRateBar: ".jp-playback-rate-bar", playbackRateBarValue: ".jp-playback-rate-bar-value", currentTime: ".jp-current-time", duration: ".jp-duration", title: ".jp-title", fullScreen: ".jp-full-screen", // * restoreScreen: ".jp-restore-screen", // * repeat: ".jp-repeat", repeatOff: ".jp-repeat-off", gui: ".jp-gui", // The interface used with autohide feature. noSolution: ".jp-no-solution" // For error feedback when jPlayer cannot find a solution. }, stateClass: { // Classes added to the cssSelectorAncestor to indicate the state. playing: "jp-state-playing", seeking: "jp-state-seeking", muted: "jp-state-muted", looped: "jp-state-looped", fullScreen: "jp-state-full-screen", noVolume: "jp-state-no-volume" }, useStateClassSkin: false, // A state class skin relies on the state classes to change the visual appearance. The single control toggles the effect, for example: play then pause, mute then unmute. autoBlur: true, // GUI control handlers will drop focus after clicks. smoothPlayBar: false, // Smooths the play bar transitions, which affects clicks and short media with big changes per second. fullScreen: false, // Native Full Screen fullWindow: false, autohide: { restored: false, // Controls the interface autohide feature. full: true, // Controls the interface autohide feature. fadeIn: 200, // Milliseconds. The period of the fadeIn anim. fadeOut: 600, // Milliseconds. The period of the fadeOut anim. hold: 1000 // Milliseconds. The period of the pause before autohide beings. }, loop: false, repeat: function(event) { // The default jPlayer repeat event handler if(event.jPlayer.options.loop) { $(this).unbind(".jPlayerRepeat").bind($.jPlayer.event.ended + ".jPlayer.jPlayerRepeat", function() { $(this).jPlayer("play"); }); } else { $(this).unbind(".jPlayerRepeat"); } }, nativeVideoControls: { // Works well on standard browsers. // Phone and tablet browsers can have problems with the controls disappearing. }, noFullWindow: { msie: /msie [0-6]\./, ipad: /ipad.*?os [0-4]\./, iphone: /iphone/, ipod: /ipod/, android_pad: /android [0-3]\.(?!.*?mobile)/, android_phone: /(?=.*android)(?!.*chrome)(?=.*mobile)/, blackberry: /blackberry/, windows_ce: /windows ce/, iemobile: /iemobile/, webos: /webos/ }, noVolume: { ipad: /ipad/, iphone: /iphone/, ipod: /ipod/, android_pad: /android(?!.*?mobile)/, android_phone: /android.*?mobile/, blackberry: /blackberry/, windows_ce: /windows ce/, iemobile: /iemobile/, webos: /webos/, playbook: /playbook/ }, timeFormat: { // Specific time format for this instance. The supported options are defined in $.jPlayer.timeFormat // For the undefined options we use the default from $.jPlayer.timeFormat }, keyEnabled: false, // Enables keyboard controls. audioFullScreen: false, // Enables keyboard controls to enter full screen with audio media. keyBindings: { // The key control object, defining the key codes and the functions to execute. // The parameter, f = $.jPlayer.focus, will be checked truethy before attempting to call any of these functions. // Properties may be added to this object, in key/fn pairs, to enable other key controls. EG, for the playlist add-on. play: { key: 80, // p fn: function(f) { if(f.status.paused) { f.play(); } else { f.pause(); } } }, fullScreen: { key: 70, // f fn: function(f) { if(f.status.video || f.options.audioFullScreen) { f._setOption("fullScreen", !f.options.fullScreen); } } }, muted: { key: 77, // m fn: function(f) { f._muted(!f.options.muted); } }, volumeUp: { key: 190, // . fn: function(f) { f.volume(f.options.volume + 0.1); } }, volumeDown: { key: 188, // , fn: function(f) { f.volume(f.options.volume - 0.1); } }, loop: { key: 76, // l fn: function(f) { f._loop(!f.options.loop); } } }, verticalVolume: false, // Calculate volume from the bottom of the volume bar. Default is from the left. Also volume affects either width or height. verticalPlaybackRate: false, globalVolume: false, // Set to make volume and muted changes affect all jPlayer instances with this option enabled idPrefix: "jp", // Prefix for the ids of html elements created by jPlayer. For flash, this must not include characters: . - + * / \ noConflict: "jQuery", emulateHtml: false, // Emulates the HTML5 Media element on the jPlayer element. consoleAlerts: true, // Alerts are sent to the console.log() instead of alert(). errorAlerts: false, warningAlerts: false }, optionsAudio: { size: { width: "0px", height: "0px", cssClass: "" }, sizeFull: { width: "0px", height: "0px", cssClass: "" } }, optionsVideo: { size: { width: "480px", height: "270px", cssClass: "jp-video-270p" }, sizeFull: { width: "100%", height: "100%", cssClass: "jp-video-full" } }, instances: {}, // Static Object status: { // Instanced in _init() src: "", media: {}, paused: true, format: {}, formatType: "", waitForPlay: true, // Same as waitForLoad except in case where preloading. waitForLoad: true, srcSet: false, video: false, // True if playing a video seekPercent: 0, currentPercentRelative: 0, currentPercentAbsolute: 0, currentTime: 0, duration: 0, remaining: 0, videoWidth: 0, // Intrinsic width of the video in pixels. videoHeight: 0, // Intrinsic height of the video in pixels. readyState: 0, networkState: 0, playbackRate: 1, // Warning - Now both an option and a status property ended: 0 /* Persistant status properties created dynamically at _init(): width height cssClass nativeVideoControls noFullWindow noVolume playbackRateEnabled // Warning - Technically, we can have both Flash and HTML, so this might not be correct if the Flash is active. That is a niche case. */ }, internal: { // Instanced in _init() ready: false // instance: undefined // domNode: undefined // htmlDlyCmdId: undefined // autohideId: undefined // mouse: undefined // cmdsIgnored }, solution: { // Static Object: Defines the solutions built in jPlayer. html: true, aurora: true, flash: true }, // 'MPEG-4 support' : canPlayType('video/mp4; codecs="mp4v.20.8"') format: { // Static Object mp3: { codec: 'audio/mpeg', flashCanPlay: true, media: 'audio' }, m4a: { // AAC / MP4 codec: 'audio/mp4; codecs="mp4a.40.2"', flashCanPlay: true, media: 'audio' }, m3u8a: { // AAC / MP4 / Apple HLS codec: 'application/vnd.apple.mpegurl; codecs="mp4a.40.2"', flashCanPlay: false, media: 'audio' }, m3ua: { // M3U codec: 'audio/mpegurl', flashCanPlay: false, media: 'audio' }, oga: { // OGG codec: 'audio/ogg; codecs="vorbis, opus"', flashCanPlay: false, media: 'audio' }, flac: { // FLAC codec: 'audio/x-flac', flashCanPlay: false, media: 'audio' }, wav: { // PCM codec: 'audio/wav; codecs="1"', flashCanPlay: false, media: 'audio' }, webma: { // WEBM codec: 'audio/webm; codecs="vorbis"', flashCanPlay: false, media: 'audio' }, fla: { // FLV / F4A codec: 'audio/x-flv', flashCanPlay: true, media: 'audio' }, rtmpa: { // RTMP AUDIO codec: 'audio/rtmp; codecs="rtmp"', flashCanPlay: true, media: 'audio' }, m4v: { // H.264 / MP4 codec: 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"', flashCanPlay: true, media: 'video' }, m3u8v: { // H.264 / AAC / MP4 / Apple HLS codec: 'application/vnd.apple.mpegurl; codecs="avc1.42E01E, mp4a.40.2"', flashCanPlay: false, media: 'video' }, m3uv: { // M3U codec: 'audio/mpegurl', flashCanPlay: false, media: 'video' }, ogv: { // OGG codec: 'video/ogg; codecs="theora, vorbis"', flashCanPlay: false, media: 'video' }, webmv: { // WEBM codec: 'video/webm; codecs="vorbis, vp8"', flashCanPlay: false, media: 'video' }, flv: { // FLV / F4V codec: 'video/x-flv', flashCanPlay: true, media: 'video' }, rtmpv: { // RTMP VIDEO codec: 'video/rtmp; codecs="rtmp"', flashCanPlay: true, media: 'video' } }, _init: function() { var self = this; this.element.empty(); this.status = $.extend({}, this.status); // Copy static to unique instance. this.internal = $.extend({}, this.internal); // Copy static to unique instance. // Initialize the time format this.options.timeFormat = $.extend({}, $.jPlayer.timeFormat, this.options.timeFormat); // On iOS, assume commands will be ignored before user initiates them. this.internal.cmdsIgnored = $.jPlayer.platform.ipad || $.jPlayer.platform.iphone || $.jPlayer.platform.ipod; this.internal.domNode = this.element.get(0); // Add key bindings focus to 1st jPlayer instanced with key control enabled. if(this.options.keyEnabled && !$.jPlayer.focus) { $.jPlayer.focus = this; } // A fix for Android where older (2.3) and even some 4.x devices fail to work when changing the *audio* SRC and then playing immediately. this.androidFix = { setMedia: false, // True when media set play: false, // True when a progress event will instruct the media to play pause: false, // True when a progress event will instruct the media to pause at a time. time: NaN // The play(time) parameter }; if($.jPlayer.platform.android) { this.options.preload = this.options.preload !== 'auto' ? 'metadata' : 'auto'; // Default to metadata, but allow auto. } this.formats = []; // Array based on supplied string option. Order defines priority. this.solutions = []; // Array based on solution string option. Order defines priority. this.require = {}; // Which media types are required: video, audio. this.htmlElement = {}; // DOM elements created by jPlayer this.html = {}; // In _init()'s this.desired code and setmedia(): Accessed via this[solution], where solution from this.solutions array. this.html.audio = {}; this.html.video = {}; this.aurora = {}; // In _init()'s this.desired code and setmedia(): Accessed via this[solution], where solution from this.solutions array. this.aurora.formats = []; this.aurora.properties = []; this.flash = {}; // In _init()'s this.desired code and setmedia(): Accessed via this[solution], where solution from this.solutions array. this.css = {}; this.css.cs = {}; // Holds the css selector strings this.css.jq = {}; // Holds jQuery selectors. ie., $(css.cs.method) this.ancestorJq = []; // Holds jQuery selector of cssSelectorAncestor. Init would use $() instead of [], but it is only 1.4+ this.options.volume = this._limitValue(this.options.volume, 0, 1); // Limit volume value's bounds. // Create the formats array, with prority based on the order of the supplied formats string $.each(this.options.supplied.toLowerCase().split(","), function(index1, value1) { var format = value1.replace(/^\s+|\s+$/g, ""); //trim if(self.format[format]) { // Check format is valid. var dupFound = false; $.each(self.formats, function(index2, value2) { // Check for duplicates if(format === value2) { dupFound = true; return false; } }); if(!dupFound) { self.formats.push(format); } } }); // Create the solutions array, with prority based on the order of the solution string $.each(this.options.solution.toLowerCase().split(","), function(index1, value1) { var solution = value1.replace(/^\s+|\s+$/g, ""); //trim if(self.solution[solution]) { // Check solution is valid. var dupFound = false; $.each(self.solutions, function(index2, value2) { // Check for duplicates if(solution === value2) { dupFound = true; return false; } }); if(!dupFound) { self.solutions.push(solution); } } }); // Create Aurora.js formats array $.each(this.options.auroraFormats.toLowerCase().split(","), function(index1, value1) { var format = value1.replace(/^\s+|\s+$/g, ""); //trim if(self.format[format]) { // Check format is valid. var dupFound = false; $.each(self.aurora.formats, function(index2, value2) { // Check for duplicates if(format === value2) { dupFound = true; return false; } }); if(!dupFound) { self.aurora.formats.push(format); } } }); this.internal.instance = "jp_" + this.count; this.instances[this.internal.instance] = this.element; // Check the jPlayer div has an id and create one if required. Important for Flash to know the unique id for comms. if(!this.element.attr("id")) { this.element.attr("id", this.options.idPrefix + "_jplayer_" + this.count); } this.internal.self = $.extend({}, { id: this.element.attr("id"), jq: this.element }); this.internal.audio = $.extend({}, { id: this.options.idPrefix + "_audio_" + this.count, jq: undefined }); this.internal.video = $.extend({}, { id: this.options.idPrefix + "_video_" + this.count, jq: undefined }); this.internal.flash = $.extend({}, { id: this.options.idPrefix + "_flash_" + this.count, jq: undefined, swf: this.options.swfPath + (this.options.swfPath.toLowerCase().slice(-4) !== ".swf" ? (this.options.swfPath && this.options.swfPath.slice(-1) !== "/" ? "/" : "") + "jquery.jplayer.swf" : "") }); this.internal.poster = $.extend({}, { id: this.options.idPrefix + "_poster_" + this.count, jq: undefined }); // Register listeners defined in the constructor $.each($.jPlayer.event, function(eventName,eventType) { if(self.options[eventName] !== undefined) { self.element.bind(eventType + ".jPlayer", self.options[eventName]); // With .jPlayer namespace. self.options[eventName] = undefined; // Destroy the handler pointer copy on the options. Reason, events can be added/removed in other ways so this could be obsolete and misleading. } }); // Determine if we require solutions for audio, video or both media types. this.require.audio = false; this.require.video = false; $.each(this.formats, function(priority, format) { self.require[self.format[format].media] = true; }); // Now required types are known, finish the options default settings. if(this.require.video) { this.options = $.extend(true, {}, this.optionsVideo, this.options ); } else { this.options = $.extend(true, {}, this.optionsAudio, this.options ); } this._setSize(); // update status and jPlayer element size // Determine the status for Blocklisted options. this.status.nativeVideoControls = this._uaBlocklist(this.options.nativeVideoControls); this.status.noFullWindow = this._uaBlocklist(this.options.noFullWindow); this.status.noVolume = this._uaBlocklist(this.options.noVolume); // Create event handlers if native fullscreen is supported if($.jPlayer.nativeFeatures.fullscreen.api.fullscreenEnabled) { this._fullscreenAddEventListeners(); } // The native controls are only for video and are disabled when audio is also used. this._restrictNativeVideoControls(); // Create the poster image. this.htmlElement.poster = document.createElement('img'); this.htmlElement.poster.id = this.internal.poster.id; this.htmlElement.poster.onload = function() { // Note that this did not work on Firefox 3.6: poster.addEventListener("onload", function() {}, false); Did not investigate x-browser. if(!self.status.video || self.status.waitForPlay) { self.internal.poster.jq.show(); } }; this.element.append(this.htmlElement.poster); this.internal.poster.jq = $("#" + this.internal.poster.id); this.internal.poster.jq.css({'width': this.status.width, 'height': this.status.height}); this.internal.poster.jq.hide(); this.internal.poster.jq.bind("click.jPlayer", function() { self._trigger($.jPlayer.event.click); }); // Generate the required media elements this.html.audio.available = false; if(this.require.audio) { // If a supplied format is audio this.htmlElement.audio = document.createElement('audio'); this.htmlElement.audio.id = this.internal.audio.id; this.html.audio.available = !!this.htmlElement.audio.canPlayType && this._testCanPlayType(this.htmlElement.audio); // Test is for IE9 on Win Server 2008. } this.html.video.available = false; if(this.require.video) { // If a supplied format is video this.htmlElement.video = document.createElement('video'); this.htmlElement.video.id = this.internal.video.id; this.html.video.available = !!this.htmlElement.video.canPlayType && this._testCanPlayType(this.htmlElement.video); // Test is for IE9 on Win Server 2008. } this.flash.available = this._checkForFlash(10.1); this.html.canPlay = {}; this.aurora.canPlay = {}; this.flash.canPlay = {}; $.each(this.formats, function(priority, format) { self.html.canPlay[format] = self.html[self.format[format].media].available && "" !== self.htmlElement[self.format[format].media].canPlayType(self.format[format].codec); self.aurora.canPlay[format] = ($.inArray(format, self.aurora.formats) > -1); self.flash.canPlay[format] = self.format[format].flashCanPlay && self.flash.available; }); this.html.desired = false; this.aurora.desired = false; this.flash.desired = false; $.each(this.solutions, function(solutionPriority, solution) { if(solutionPriority === 0) { self[solution].desired = true; } else { var audioCanPlay = false; var videoCanPlay = false; $.each(self.formats, function(formatPriority, format) { if(self[self.solutions[0]].canPlay[format]) { // The other solution can play if(self.format[format].media === 'video') { videoCanPlay = true; } else { audioCanPlay = true; } } }); self[solution].desired = (self.require.audio && !audioCanPlay) || (self.require.video && !videoCanPlay); } }); // This is what jPlayer will support, based on solution and supplied. this.html.support = {}; this.aurora.support = {}; this.flash.support = {}; $.each(this.formats, function(priority, format) { self.html.support[format] = self.html.canPlay[format] && self.html.desired; self.aurora.support[format] = self.aurora.canPlay[format] && self.aurora.desired; self.flash.support[format] = self.flash.canPlay[format] && self.flash.desired; }); // If jPlayer is supporting any format in a solution, then the solution is used. this.html.used = false; this.aurora.used = false; this.flash.used = false; $.each(this.solutions, function(solutionPriority, solution) { $.each(self.formats, function(formatPriority, format) { if(self[solution].support[format]) { self[solution].used = true; return false; } }); }); // Init solution active state and the event gates to false. this._resetActive(); this._resetGate(); // Set up the css selectors for the control and feedback entities. this._cssSelectorAncestor(this.options.cssSelectorAncestor); // If neither html nor aurora nor flash are being used by this browser, then media playback is not possible. Trigger an error event. if(!(this.html.used || this.aurora.used || this.flash.used)) { this._error( { type: $.jPlayer.error.NO_SOLUTION, context: "{solution:'" + this.options.solution + "', supplied:'" + this.options.supplied + "'}", message: $.jPlayer.errorMsg.NO_SOLUTION, hint: $.jPlayer.errorHint.NO_SOLUTION }); if(this.css.jq.noSolution.length) { this.css.jq.noSolution.show(); } } else { if(this.css.jq.noSolution.length) { this.css.jq.noSolution.hide(); } } // Add the flash solution if it is being used. if(this.flash.used) { var htmlObj, flashVars = 'jQuery=' + encodeURI(this.options.noConflict) + '&id=' + encodeURI(this.internal.self.id) + '&vol=' + this.options.volume + '&muted=' + this.options.muted; // Code influenced by SWFObject 2.2: http://code.google.com/p/swfobject/ // Non IE browsers have an initial Flash size of 1 by 1 otherwise the wmode affected the Flash ready event. if($.jPlayer.browser.msie && (Number($.jPlayer.browser.version) < 9 || $.jPlayer.browser.documentMode < 9)) { var objStr = '<object id="' + this.internal.flash.id + '" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="0" height="0" tabindex="-1"></object>'; var paramStr = [ '<param name="movie" value="' + this.internal.flash.swf + '" />', '<param name="FlashVars" value="' + flashVars + '" />', '<param name="allowScriptAccess" value="always" />', '<param name="bgcolor" value="' + this.options.backgroundColor + '" />', '<param name="wmode" value="' + this.options.wmode + '" />' ]; htmlObj = document.createElement(objStr); for(var i=0; i < paramStr.length; i++) { htmlObj.appendChild(document.createElement(paramStr[i])); } } else { var createParam = function(el, n, v) { var p = document.createElement("param"); p.setAttribute("name", n); p.setAttribute("value", v); el.appendChild(p); }; htmlObj = document.createElement("object"); htmlObj.setAttribute("id", this.internal.flash.id); htmlObj.setAttribute("name", this.internal.flash.id); htmlObj.setAttribute("data", this.internal.flash.swf); htmlObj.setAttribute("type", "application/x-shockwave-flash"); htmlObj.setAttribute("width", "1"); // Non-zero htmlObj.setAttribute("height", "1"); // Non-zero htmlObj.setAttribute("tabindex", "-1"); createParam(htmlObj, "flashvars", flashVars); createParam(htmlObj, "allowscriptaccess", "always"); createParam(htmlObj, "bgcolor", this.options.backgroundColor); createParam(htmlObj, "wmode", this.options.wmode); } this.element.append(htmlObj); this.internal.flash.jq = $(htmlObj); } // Setup playbackRate ability before using _addHtmlEventListeners() if(this.html.used && !this.flash.used) { // If only HTML // Using the audio element capabilities for playbackRate. ie., Assuming video element is the same. this.status.playbackRateEnabled = this._testPlaybackRate('audio'); } else { this.status.playbackRateEnabled = false; } this._updatePlaybackRate(); // Add the HTML solution if being used. if(this.html.used) { // The HTML Audio handlers if(this.html.audio.available) { this._addHtmlEventListeners(this.htmlElement.audio, this.html.audio); this.element.append(this.htmlElement.audio); this.internal.audio.jq = $("#" + this.internal.audio.id); } // The HTML Video handlers if(this.html.video.available) { this._addHtmlEventListeners(this.htmlElement.video, this.html.video); this.element.append(this.htmlElement.video); this.internal.video.jq = $("#" + this.internal.video.id); if(this.status.nativeVideoControls) { this.internal.video.jq.css({'width': this.status.width, 'height': this.status.height}); } else { this.internal.video.jq.css({'width':'0px', 'height':'0px'}); // Using size 0x0 since a .hide() causes issues in iOS } this.internal.video.jq.bind("click.jPlayer", function() { self._trigger($.jPlayer.event.click); }); } } // Add the Aurora.js solution if being used. if(this.aurora.used) { // Aurora.js player need to be created for each media, see setMedia function. } // Create the bridge that emulates the HTML Media element on the jPlayer DIV if( this.options.emulateHtml ) { this._emulateHtmlBridge(); } if((this.html.used || this.aurora.used) && !this.flash.used) { // If only HTML, then emulate flash ready() call after 100ms. setTimeout( function() { self.internal.ready = true; self.version.flash = "n/a"; self._trigger($.jPlayer.event.repeat); // Trigger the repeat event so its handler can initialize itself with the loop option. self._trigger($.jPlayer.event.ready); }, 100); } // Initialize the interface components with the options. this._updateNativeVideoControls(); // The other controls are now setup in _cssSelectorAncestor() if(this.css.jq.videoPlay.length) { this.css.jq.videoPlay.hide(); } $.jPlayer.prototype.count++; // Change static variable via prototype. }, destroy: function() { // MJP: The background change remains. Would need to store the original to restore it correctly. // MJP: The jPlayer element's size change remains. // Clear the media to reset the GUI and stop any downloads. Streams on some browsers had persited. (Chrome) this.clearMedia(); // Remove the size/sizeFull cssClass from the cssSelectorAncestor this._removeUiClass(); // Remove the times from the GUI if(this.css.jq.currentTime.length) { this.css.jq.currentTime.text(""); } if(this.css.jq.duration.length) { this.css.jq.duration.text(""); } // Remove any bindings from the interface controls. $.each(this.css.jq, function(fn, jq) { // Check selector is valid before trying to execute method. if(jq.length) { jq.unbind(".jPlayer"); } }); // Remove the click handlers for $.jPlayer.event.click this.internal.poster.jq.unbind(".jPlayer"); if(this.internal.video.jq) { this.internal.video.jq.unbind(".jPlayer"); } // Remove the fullscreen event handlers this._fullscreenRemoveEventListeners(); // Remove key bindings if(this === $.jPlayer.focus) { $.jPlayer.focus = null; } // Destroy the HTML bridge. if(this.options.emulateHtml) { this._destroyHtmlBridge(); } this.element.removeData("jPlayer"); // Remove jPlayer data this.element.unbind(".jPlayer"); // Remove all event handlers created by the jPlayer constructor this.element.empty(); // Remove the inserted child elements delete this.instances[this.internal.instance]; // Clear the instance on the static instance object }, destroyRemoved: function() { // Destroy any instances that have gone away. var self = this; $.each(this.instances, function(i, element) { if(self.element !== element) { // Do not destroy this instance. if(!element.data("jPlayer")) { // Check that element is a real jPlayer. element.jPlayer("destroy"); delete self.instances[i]; } } }); }, enable: function() { // Plan to implement // options.disabled = false }, disable: function () { // Plan to implement // options.disabled = true }, _testCanPlayType: function(elem) { // IE9 on Win Server 2008 did not implement canPlayType(), but it has the property. try { elem.canPlayType(this.format.mp3.codec); // The type is irrelevant. return true; } catch(err) { return false; } }, _testPlaybackRate: function(type) { // type: String 'audio' or 'video' var el, rate = 0.5; type = typeof type === 'string' ? type : 'audio'; el = document.createElement(type); // Wrapping in a try/catch, just in case older HTML5 browsers throw and error. try { if('playbackRate' in el) { el.playbackRate = rate; return el.playbackRate === rate; } else { return false; } } catch(err) { return false; } }, _uaBlocklist: function(list) { // list : object with properties that are all regular expressions. Property names are irrelevant. // Returns true if the user agent is matched in list. var ua = navigator.userAgent.toLowerCase(), block = false; $.each(list, function(p, re) { if(re && re.test(ua)) { block = true; return false; // exit $.each. } }); return block; }, _restrictNativeVideoControls: function() { // Fallback to noFullWindow when nativeVideoControls is true and audio media is being used. Affects when both media types are used. if(this.require.audio) { if(this.status.nativeVideoControls) { this.status.nativeVideoControls = false; this.status.noFullWindow = true; } } }, _updateNativeVideoControls: function() { if(this.html.video.available && this.html.used) { // Turn the HTML Video controls on/off this.htmlElement.video.controls = this.status.nativeVideoControls; // Show/hide the jPlayer GUI. this._updateAutohide(); // For when option changed. The poster image is not updated, as it is dealt with in setMedia(). Acceptable degradation since seriously doubt these options will change on the fly. Can again review later. if(this.status.nativeVideoControls && this.require.video) { this.internal.poster.jq.hide(); this.internal.video.jq.css({'width': this.status.width, 'height': this.status.height}); } else if(this.status.waitForPlay && this.status.video) { this.internal.poster.jq.show(); this.internal.video.jq.css({'width': '0px', 'height': '0px'}); } } }, _addHtmlEventListeners: function(mediaElement, entity) { var self = this; mediaElement.preload = this.options.preload; mediaElement.muted = this.options.muted; mediaElement.volume = this.options.volume; if(this.status.playbackRateEnabled) { mediaElement.defaultPlaybackRate = this.options.defaultPlaybackRate; mediaElement.playbackRate = this.options.playbackRate; } // Create the event listeners // Only want the active entity to affect jPlayer and bubble events. // Using entity.gate so that object is referenced and gate property always current mediaElement.addEventListener("progress", function() { if(entity.gate) { if(self.internal.cmdsIgnored && this.readyState > 0) { // Detect iOS executed the command self.internal.cmdsIgnored = false; } self._getHtmlStatus(mediaElement); self._updateInterface(); self._trigger($.jPlayer.event.progress); } }, false); mediaElement.addEventListener("loadeddata", function() { if(entity.gate) { self.androidFix.setMedia = false; // Disable the fix after the first progress event. if(self.androidFix.play) { // Play Android audio - performing the fix. self.androidFix.play = false; self.play(self.androidFix.time); } if(self.androidFix.pause) { // Pause Android audio at time - performing the fix. self.androidFix.pause = false; self.pause(self.androidFix.time); } self._trigger($.jPlayer.event.loadeddata); } }, false); mediaElement.addEventListener("timeupdate", function() { if(entity.gate) { self._getHtmlStatus(mediaElement); self._updateInterface(); self._trigger($.jPlayer.event.timeupdate); } }, false); mediaElement.addEventListener("durationchange", function() { if(entity.gate) { self._getHtmlStatus(mediaElement); self._updateInterface(); self._trigger($.jPlayer.event.durationchange); } }, false); mediaElement.addEventListener("play", function() { if(entity.gate) { self._updateButtons(true); self._html_checkWaitForPlay(); // So the native controls update this variable and puts the hidden interface in the correct state. Affects toggling native controls. self._trigger($.jPlayer.event.play); } }, false); mediaElement.addEventListener("playing", function() { if(entity.gate) { self._updateButtons(true); self._seeked(); self._trigger($.jPlayer.event.playing); } }, false); mediaElement.addEventListener("pause", function() { if(entity.gate) { self._updateButtons(false); self._trigger($.jPlayer.event.pause); } }, false); mediaElement.addEventListener("waiting", function() { if(entity.gate) { self._seeking(); self._trigger($.jPlayer.event.waiting); }