From: stevenaw Date: Tue, 12 Apr 2011 20:40:38 +0000 (-0400) Subject: [#380] Branch remade X-Git-Tag: v0.5~1^2~8 X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=33f90ccba4a916509c8f1205b9cae3e90cf1ca21;p=popcorn-js.git [#380] Branch remade --- diff --git a/players/soundcloud/lib/soundcloud.player.api.js b/players/soundcloud/lib/soundcloud.player.api.js new file mode 100644 index 0000000..2b3d783 --- /dev/null +++ b/players/soundcloud/lib/soundcloud.player.api.js @@ -0,0 +1,140 @@ +/* +* JavaScript interface for the SoundCloud Player widget +* Author: Matas Petrikas, matas@soundcloud.com +* Copyright (c) 2009 SoundCloud Ltd. +* Licensed under the MIT license: +* http://www.opensource.org/licenses/mit-license.php +*/ +(function(){ + var isIE = (/msie/i).test(navigator.userAgent) && !(/opera/i).test(navigator.userAgent); + + var soundcloud = window.soundcloud = { + version: "0.1", + debug: false, + _listeners: [], + // re-dispatches widget events in the DOM, using JS library support, the events also should bubble up the DOM + _redispatch: function(eventType, flashId, data) { + var playerNode, + lsnrs = this._listeners[eventType] || [], + // construct the custom eventType e.g. 'soundcloud:onPlayerReady' + customEventType = 'soundcloud:' + eventType; + + try{ + // find the flash player, might throw an exception + playerNode = this.getPlayer(flashId); + }catch(e){ + if(this.debug && window.console){ + console.error('unable to dispatch widget event ' + eventType + ' for the widget id ' + flashId, data, e); + } + return; + } + // re-dispatch SoundCloud events up in the DOM + if(window.jQuery){ + // if jQuery is available, trigger the custom event + jQuery(playerNode).trigger(customEventType, [data]); + }else if(window.Prototype){ + // if Prototype.js is available, fire the custom event + $(playerNode).fire(customEventType, data); + }else{ + // TODO add more JS libraries that support custom DOM events + } + // if there are any listeners registered to this event, trigger them all + for(var i = 0, l = lsnrs.length; i < l; i += 1) { + lsnrs[i].apply(playerNode, [playerNode, data]); + } + // log the events in debug mode + if(this.debug && window.console){ + console.log(customEventType, eventType, flashId, data); + } + + }, + // you can add multiple listeners to a certain event + // e.g. soundcloud.addEventListener('onPlayerReady', myFunctionOne); + // soundcloud.addEventListener('onPlayerReady', myFunctionTwo); + addEventListener: function(eventType, callback) { + if(!this._listeners[eventType]){ + this._listeners[eventType] = []; + } + this._listeners[eventType].push(callback); + }, + // you can also remove the function listener if e.g you want to trigger it only once + // soundcloud.removeEventListener('onMediaPlay', myFunctionOne); + removeEventListener: function(eventType, callback) { + var lsnrs = this._listeners[eventType] || []; + for(var i = 0, l = lsnrs.length; i < l; i += 1) { + if(lsnrs[i] === callback){ + lsnrs.splice(i, 1); + } + } + }, + // get widget node based on its id (if object tag) or name (if embed tag) + // if you're using SWFObject or other dynamic Flash generators, please make sure that you set the id parameter + // only if the DOM has an id/name it's possible to call player's methods. + // Important!: because of the bug in Opera browser, the Flash can't get its own id + // so the generator should set it additionally through flashvars parameter 'object_id' + getPlayer: function(id){ + var flash; + try{ + if(!id){ + throw "The SoundCloud Widget DOM object needs an id atribute, please refer to SoundCloud Widget API documentation."; + } + flash = isIE ? window[id] : document[id]; + if(flash){ + if(flash.api_getFlashId){ + return flash; + }else{ + throw "The SoundCloud Widget External Interface is not accessible. Check that allowscriptaccess is set to 'always' in embed code"; + } + }else{ + throw "The SoundCloud Widget with an id " + id + " couldn't be found"; + } + }catch(e){ + if (console && console.error) { + console.error(e); + } + throw e; + } + }, + // fired when widget has loaded its data and is ready to accept calls from outside + // the widget will call these functions only if in it's flashvars there's a parameter enable_api=true + // @flashId: the widget id, basically the Flash node should be accessible to JS with soundcloud.getPlayer(flashId) + // @data: an object containing .mediaUri (eg. 'http://api.soundcloud.com/tracks/49931') .mediaId (e.g. '4532') + // in buffering events data contains also .percent = (e.g. '99') + onPlayerReady: function(flashId, data) { + this._redispatch('onPlayerReady', flashId, data); + }, + // fired when widget starts playing current track (fired only once per track) + onMediaStart : function(flashId, data) { + this._redispatch('onMediaStart', flashId, data); + }, + // fired when the track/playlist has finished playing + onMediaEnd : function(flashId, data) { + this._redispatch('onMediaEnd', flashId, data); + }, + // fired when widget starts playing current track (fired on every play, seek) + onMediaPlay : function(flashId, data) { + this._redispatch('onMediaPlay', flashId, data); + }, + // fired when track was paused + onMediaPause : function(flashId, data) { + this._redispatch('onMediaPause', flashId, data); + }, + // fired when the widget is still buffering, means you can't seek in the track fully yet + onMediaBuffering : function(flashId, data) { + this._redispatch('onMediaBuffering', flashId, data); + }, + // fired when the user seeks in the track + onMediaSeek : function(flashId, data) { + this._redispatch('onMediaSeek', flashId, data); + }, + // fired when the widget is done buffering and the whole track length is seekable + onMediaDoneBuffering : function(flashId, data) { + this._redispatch('onMediaDoneBuffering', flashId, data); + }, + // fired when the widget can't get the requested data from the server (the resource is removed, hidden, etc.) + onPlayerError : function(flashId, data) { + this._redispatch('onPlayerError', flashId, data); + } + }; + +})(); diff --git a/players/soundcloud/popcorn.soundcloud.html b/players/soundcloud/popcorn.soundcloud.html new file mode 100644 index 0000000..f3e8d2b --- /dev/null +++ b/players/soundcloud/popcorn.soundcloud.html @@ -0,0 +1,241 @@ + + + + Popcorn Soundcloud Player Example + + + + + + + + + + + + + + + + + + +

+ +
+ + + + +
+ +
+ Current Time (s): +
Duration (s): +
Volume (0-1): +
Ready State: 0 +
+
+ Comment Area +
+
+ +
+
+

Description

+

+ This demo will showcase how the Soundcloud flash audio player can be integrated into Popcorn.js. This is done by making the flash audio player masquerade as HTML 5 media element.
+ Due to the Flash security model, this demo must be run from a web server
+


+ Soundcloud does not support their player to be chromeless (hidden controls), but custom controls have been developed and tied into their player for demo purposes.
+ Clicking play/pause or seeking in either the Soundcloud player or via custsom controls will cause the other to update.
+ The Soundcloud audio can be specified in the HTML source by giving the Soundcloud song url to either the Popcorn.soundcloud constructor or as the div data-src attribute.
+ Specifying the source in the constructor will override any source specified on the container element.
+ Player width/height can be specified as container attributes (data-width, data-height), or as styles (width, height). Styles can be inline or CSS.
+ If no width or height are given, they default to '100%' and '81px' respectively.
+ Width/height precendence is in this order: constructor, container attributes, natural (manually given inline/CSS styles), default
+

+

Expected Events

+ +
+
+
+
+ Footnote Area
+
+
+ Attributions Area
+
+
+ Flickr Area
+
+
+ Twitter Area
+
+
+ Image Area
+
+
+ Google Feed Area
+
+
+ Web Page Area
+
+
+ +
+
+ + \ No newline at end of file diff --git a/players/soundcloud/popcorn.soundcloud.js b/players/soundcloud/popcorn.soundcloud.js new file mode 100644 index 0000000..04e8b3c --- /dev/null +++ b/players/soundcloud/popcorn.soundcloud.js @@ -0,0 +1,656 @@ +// Popcorn Soundcloud Player Wrapper +( function( Popcorn, global ) { + /** + * Soundcloud wrapper for Popcorn. + * This player adds enables Popcorn.js to handle Soundcloud audio. It does so by masking an embedded Soundcloud Flash object + * as a video and implementing the HTML5 Media Element interface. + * + * You can specify the video in four ways: + * 1. Use the embed code path supplied by Soundcloud as a div's data-src attribute, and pass the div id into a new Popcorn.soundcloud object + * + *
+ * + * + * 2. Pass the div id and the embed code path supplied by Soundcloud into a new Popcorn.soundcloud object + * + *
+ * + * + * The player can be further configured when it is created by adding other attrributes. A complete list (all optional): + * + * var popcorn = Popcorn( Popcorn.soundcloud( "player_1", { + * src: "http://soundcloud.com/forss/flickermood", // The Soundcloud track to play + * width: "100%", // The width for the player. May also be as '##px' + * height: "81px", // The height for the player. May also be as '###%' + * api_key: "abcdefsdfsdf", // Soundcloud API key, required for retrieving comments + * commentdiv: "divId_for_output", // Div Id for outputting comments + * commentformat: function( comment ) {} // Function to format a comment. Returns HTML string + * })); + * + * Height, width and track source may be specified in other ways. Height and width may be throughh CSS or inline on the container + * div's attributes (data-height, data-width). Track source may be specified on the container element as an attribute (data-src). + * See above example. Values may be overridden if height, width or souurce are specified in moree than one way. + * The hierarchy is: + * + * constructor -> inline -> CSS + * + * Comments are retrieved from Soundcloud when the player is registered with Popcorn by calling the registerWithPopcorn() + * function. For this to work, the api_key and commentdiv attributes must be set. Comments are output by default similar to + * how Soundcloud formats them in-player, but a custom formatting function may be supplied. It receives a comment object and + * the current date. A comment object has: + * + * var comment = { + * start: 0, // Required. Start time in ms. + * date: new Date(), // Required. Date comment wasa posted. + * text: "", // Required. Comment text + * user: { // Required. Describes the user who posted the comment + * name: "", // Required. User name + * profile: "", // Required. User profile link + * avatar: "" // Required. User avatar link + * } + * } + * + * These events are completely custom-implemented and may be subscribed to at any time: + * canplaythrough + * durationchange + * load + * loadedmetadata + * loadstart + * play + * readystatechange + * volumechange + * + * These events are related to player functionality and must be subscribed to during or after the load event: + * canplay + * ended + * error + * pause + * playing + * progress + * seeked + * timeupdate + * + * These events are not supported: + * abort + * emptied + * loadeddata + * ratechange + * seeking + * stalled + * suspend + * waiting + * + * Supported media attributes: + * autoplay ( via Popcorn ) + * currentTime + * defaultPlaybackRate ( get only ) + * duration ( get only ) + * ended ( get only ) + * initialTime ( get only, always 0 ) + * loop ( get only, set by calling setLoop() ) + * muted ( get only ) + * paused ( get only ) + * playbackRate ( get only ) + * played ( get only, 0/1 only ) + * readyState ( get only ) + * src ( get only ) + * volume + * + * load() function + * mute() function ( toggles on/off ) + * play() function + * pause() function + * + * Unsupported media attributes: + * buffered + * networkState + * preload + * seekable + * seeking + * startOffsetTime + * + * canPlayType() function + */ + + // Trackers + var timeupdateInterval = 33, + timeCheckInterval = 0.25, + abs = Math.abs, + floor = Math.floor, + round = Math.round, + registry = {}; + + function hasAllDependencies() { + return global.swfobject && global.soundcloud; + } + + // Borrowed from: http://www.quirksmode.org/dom/getstyles.html + // Gets the style for the given element + function getStyle( elem, styleProp ) { + if ( elem.currentStyle ) { + // IE way + return elem.currentStyle[styleProp]; + } else if ( global.getComputedStyle ) { + // Firefox, Chrome, et. al + return document.defaultView.getComputedStyle( elem, null ).getPropertyValue( styleProp ); + } + } + + function formatComment( comment ) { + // Calclate the difference between d and now, express as "n units ago" + function ago( d ) { + var diff = ( ( new Date() ).getTime() - d.getTime() )/1000; + + function pluralize( value, unit ) { + return value + " " + unit + ( value > 1 ? "s" : "") + " ago"; + } + + if ( diff < 60 ) { + return pluralize( round( diff ), "second" ); + } + diff /= 60; + + if ( diff < 60 ) { + return pluralize( round( diff ), "minute" ); + } + diff /= 60; + + if ( diff < 24 ) { + return pluralize( round( diff ), "hour" ); + } + diff /= 24; + + // Rough approximation of months + if ( diff < 30 ) { + return pluralize( round( diff ), "day" ); + } + + if ( diff < 365 ) { + return pluralize( round( diff/30 ), "month" ); + } + + return pluralize( round( diff/365 ), "year" ); + } + + // Converts sec to min.sec + function timeToFraction ( totalSec ) { + var min = floor( totalSec / 60 ), + sec = round( totalSec % 60 ); + + return min + "." + ( sec < 10 ? "0" : "" ) + sec; + } + + return '
' + + '' + + comment.user.name + ' at ' + timeToFraction( comment.start ) + ' ' + + ago( comment.date ) + + '
' + comment.text + ''; + } + + function isReady( self ) { + if ( !hasAllDependencies() ) { + setTimeout( function() { + isReady( self ); + }, 15 ); + return; + } + + var flashvars = { + enable_api: true, + object_id: self._playerId, + url: self.src, + // Hide comments in player if showing them elsewhere + show_comments: !self._options.api_key && !self._options.commentdiv + }, + params = { + allowscriptaccess: "always", + // This is so we can overlay html ontop of Flash + wmode: 'transparent' + }, + attributes = { + id: self._playerId, + name: self._playerId + }, + actualTarget = document.createElement( 'div' ); + + actualTarget.setAttribute( "id", self._playerId ); + self._container.appendChild( actualTarget ); + + swfobject.embedSWF( "http://player.soundcloud.com/player.swf", self._playerId, self.offsetWidth, self.height, "9.0.0", "expressInstall.swf", flashvars, params, attributes ); + } + + Popcorn.getScript( "http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js" ); + + // Source file originally from 'https://github.com/soundcloud/Widget-JS-API/raw/master/soundcloud.player.api.js' + Popcorn.getScript( "lib/soundcloud.player.api.js", function() { + // Play event is fired twice when player is first started. Ignore second one + var ignorePlayEvt = 1; + + // Register the wrapper's load event with the player + soundcloud.addEventListener( 'onPlayerReady', function( object, data ) { + var wrapper = registry[object.api_getFlashId()]; + + wrapper.swfObj = object; + wrapper.duration = object.api_getTrackDuration(); + wrapper.currentTime = object.api_getTrackPosition(); + // This eliminates volumechangee event from firing on load + wrapper.volume = wrapper.previousVolume = object.api_getVolume()/100; + + // The numeric id of the track for use with Soundcloud API + wrapper._mediaId = data.mediaId; + + wrapper.dispatchEvent( 'load' ); + wrapper.dispatchEvent( 'canplay' ); + wrapper.dispatchEvent( 'durationchange' ); + + wrapper.timeupdate(); + }); + + // Register events for when the flash player plays a track for the first time + soundcloud.addEventListener( 'onMediaStart', function( object, data ) { + var wrapper = registry[object.api_getFlashId()]; + wrapper.played = 1; + wrapper.dispatchEvent( 'playing' ); + }); + + // Register events for when the flash player plays a track + soundcloud.addEventListener( 'onMediaPlay', function( object, data ) { + if ( ignorePlayEvt ) { + ignorePlayEvt = 0; + return; + } + + var wrapper = registry[object.api_getFlashId()]; + wrapper.dispatchEvent( 'play' ); + }); + + // Register events for when the flash player pauses a track + soundcloud.addEventListener( 'onMediaPause', function( object, data ) { + var wrapper = registry[object.api_getFlashId()]; + wrapper.dispatchEvent( 'pause' ); + }); + + // Register events for when the flash player is buffering + soundcloud.addEventListener( 'onMediaBuffering', function( object, data ) { + var wrapper = registry[object.api_getFlashId()]; + + wrapper.dispatchEvent( 'progress' ); + + if ( wrapper.readyState === 0 ) { + wrapper.readyState = 3; + wrapper.dispatchEvent( "readystatechange" ); + } + }); + + // Register events for when the flash player is done buffering + soundcloud.addEventListener( 'onMediaDoneBuffering', function( object, data ) { + var wrapper = registry[object.api_getFlashId()]; + wrapper.dispatchEvent( 'canplaythrough' ); + }); + + // Register events for when the flash player has finished playing + soundcloud.addEventListener( 'onMediaEnd', function( object, data ) { + var wrapper = registry[object.api_getFlashId()]; + wrapper.paused = 1; + //wrapper.pause(); + wrapper.dispatchEvent( 'ended' ); + }); + + // Register events for when the flash player has seeked + soundcloud.addEventListener( 'onMediaSeek', function( object, data ) { + var wrapper = registry[object.api_getFlashId()]; + + wrapper.setCurrentTime( object.api_getTrackPosition() ); + + if ( wrapper.paused ) { + wrapper.dispatchEvent( "timeupdate" ); + } + }); + + // Register events for when the flash player has errored + soundcloud.addEventListener( 'onPlayerError', function( object, data ) { + var wrapper = registry[object.api_getFlashId()]; + wrapper.dispatchEvent( 'error' ); + }); + }); + + Popcorn.soundcloud = function( containerId, options ) { + return new Popcorn.soundcloud.init( containerId, options ); + }; + + // A constructor, but we need to wrap it to allow for "static" functions + Popcorn.soundcloud.init = (function() { + function pullFromContainer( that, options ) { + var container = that._container, + bounds = container.getBoundingClientRect(), + tmp, + undef; + + that.width = options.width || container.getAttribute( "data-width" ) || getStyle( container, "width" ) || "100%"; + that.height = options.height || container.getAttribute( "data-height" ) || getStyle( container, "height" ) || "81px"; + that.src = options.src || container.getAttribute( "data-src" ); + that.autoplay = container.getAttribute( "data-autoplay" ) || undef; + + if ( parseFloat( that.height, 10 ) !== 81 ) { + that.height = "81px"; + } + + that.offsetLeft = bounds.left; + that.offsetTop = bounds.top; + that.offsetHeight = parseFloat( that.height, 10 ); + that.offsetWidth = parseFloat( that.width, 10 ); + + // Width and height may've been specified as a %, find the value now in case a plugin needs it (like subtitle) + if ( /[\d]+%/.test( that.width ) ) { + tmp = getStyle( container, "width" ); + that._container.style.width = that.width; + that.offsetWidth = that._container.offsetWidth; + that._container.style.width = tmp; + } + + if ( /[\d]+%/.test( that.height ) ) { + tmp = getStyle( container, "height" ); + that._container.style.height = that.height; + that.offsetHeight = that._container.offsetHeight; + that._container.style.height = tmp; + } + } + + // If container id is not supplied, assumed to be same as player id + var ctor = function ( containerId, options ) { + if ( !containerId ) { + throw "Must supply an id!"; + } else if ( /file/.test( location.protocol ) ) { + throw "Must run from a web server!"; + } + + var container = this._container = document.getElementById( containerId ); + + if ( !container ) { + throw "Could not find that container in the DOM!"; + } + + options = options || {}; + + options.commentformat = options.commentformat || formatComment + + this._mediaId = 0; + this._listeners = {}; + this._playerId = Popcorn.guid( containerId ); + this._containerId = containerId; + this._options = options; + this._comments = []; + this._popcorn; + + this._options.src = options.src || container.getAttribute( "data-src" ); + + pullFromContainer( this, this._options ); + + this.duration = 0; + this.volume = 1; + this.currentTime = 0; + this.ended = 0; + this.paused = 1; + this.readyState = 0; + this.playbackRate = 1; + + this.top = 0; + this.left = 0; + + this.autoplay; + this.played = 0; + + this.addEventListener( "load", function() { + var boundRect = this.getBoundingClientRect(); + + this.top = boundRect.top; + this.left = boundRect.left; + + this.offsetWidth = this.swfObj.offsetWidth; + this.offsetHeight = this.swfObj.offsetHeight; + this.offsetLeft = this.swfObj.offsetLeft; + this.offsetTop = this.swfObj.offsetTop; + }); + + registry[ this._playerId ] = this; + isReady( this ); + } + return ctor; + })(); + + Popcorn.soundcloud.init.prototype = Popcorn.soundcloud.prototype; + + // Sequence object prototype + Popcorn.extend( Popcorn.soundcloud.prototype, { + // Set the volume as a value between 0 and 1 + setVolume: function( val ) { + if ( !val && val !== 0 ) { + return; + } + + // Normalize in case outside range of expected values of 0 .. 1 + if ( val < 0 ) { + val = -val; + } + + if ( val > 1 ) { + val %= 1; + } + + // HTML video expects to be 0.0 -> 1.0, Flash object expects 0-100 + this.volume = this.previousVolume = val; + this.swfObj.api_setVolume( val*100 ); + this.dispatchEvent( "volumechange" ); + }, + // Seeks the video + setCurrentTime: function ( time ) { + if ( !time && time !== 0 ) { + return; + } + + this.currentTime = this.previousCurrentTime = time; + this.ended = time >= this.duration; + + // Fire events for seeking and time change + this.dispatchEvent( "seeked" ); + }, + // Play the video + play: function() { + // In case someone is cheeky enough to try this before loaded + if ( !this.swfObj ) { + this.addEventListener( "load", this.play ); + return; + } else if ( !this.paused ) { + // No need to process if already playing + return; + } + + this.paused = 0; + this.swfObj.api_play(); + }, + // Pause the video + pause: function() { + // In case someone is cheeky enough to try this before loaded + if ( !this.swfObj ) { + this.addEventListener( "load", this.pause ); + return; + } else if ( this.paused ) { + // No need to process if already playing + return; + } + + this.paused = 1; + this.swfObj.api_pause(); + }, + // Toggle video muting + // Unmuting will leave it at the old value + mute: function() { + // In case someone is cheeky enough to try this before loaded + if ( !this.swfObj ) { + this.addEventListener( "load", this.mute ); + return; + } + + if ( !this.muted() ) { + this.oldVol = this.volume; + + if ( this.paused ) { + this.setVolume( 0 ); + } else { + this.volume = 0; + } + } else { + if ( this.paused ) { + this.setVolume( this.oldVol ); + } else { + this.volume = this.oldVol; + } + } + }, + muted: function() { + return this.volume === 0; + }, + // Force loading by playing the player. Pause afterwards + load: function() { + // In case someone is cheeky enough to try this before loaded + if ( !this.swfObj ) { + this.addEventListener( "load", this.load ); + return; + } + + this.play(); + this.pause(); + }, + // Hook an event listener for the player event into internal event system + // Stick to HTML conventions of add event listener and keep lowercase, without prepending "on" + addEventListener: function( evt, fn ) { + if ( !this._listeners[evt] ) { + this._listeners[evt] = []; + } + + this._listeners[evt].push( fn ); + return fn; + }, + dispatchEvent: function( evt ) { + var self = this, + evtName = evt.type || evt; + + // Manually triggered a UI event, have it invoke rather than just the event handlers + if ( evtName === "play" && this.paused || evtName === "pause" && !this.paused ) { + this[evtName](); + return; + } + + Popcorn.forEach( this._listeners[evtName], function( fn ) { + fn.call( self ); + }); + }, + timeupdate: function() { + var self = this, + checkedVolume = this.swfObj.api_getVolume()/100, + seeked = 0; + + // If has been changed through setting currentTime attribute + if ( abs( this.currentTime - this.previousCurrentTime ) > timeCheckInterval ) { + // Has programatically set the currentTime + this.swfObj.api_seekTo( this.currentTime ); + seeked = 1; + } else { + this.previousCurrentTime = this.currentTime = this.swfObj.api_getTrackPosition(); + } + + // If has been changed throughh volume attribute + if ( checkedVolume !== this.previousVolume ) { + this.setVolume( checkedVolume ); + } else if ( this.volume !== this.previousVolume ) { + this.setVolume( this.volume ); + } + + if ( !this.paused ) { + this.dispatchEvent( 'timeupdate' ); + } + + if( !self.ended ) { + setTimeout( function() { + self.timeupdate.call( self ); + }, timeupdateInterval); + } + }, + getBoundingClientRect: function() { + return !this.swfObj || this.swfObj.getBoundingClientRect(); + }, + registerPopcornWithPlayer: function( popcorn ) { + if ( !this.swfObj ) { + this.addEventListener( "load", function() { + this.registerPopcornWithPlayer( popcorn ); + }); + return; + } + + this._popcorn = popcorn; + + if ( this._options && this._options.api_key && this._options.commentdiv ) { + var self = this; + + Popcorn.xhr({ + url: "http://api.soundcloud.com/tracks/" + self._mediaId + "/comments.js?consumer_key=" + self._options.api_key, + success: function( data ) { + Popcorn.forEach( data.json, function ( obj ) { + self.addComment({ + start: obj.timestamp/1000, + date: new Date( obj.created_at ), + text: obj.body, + user: { + name: obj.user.username, + profile: obj.user.permalink_url, + avatar: obj.user.avatar_url + } + }); + }); + } + }); + } + } + }); + + Popcorn.extend( Popcorn.soundcloud.prototype, { + addComment: function( obj, displayFn ) { + var self = this, + comment = { + start: obj.start || 0, + date: obj.date || new Date(), + text: obj.text || "", + user: { + name: obj.user.name || "", + profile: obj.user.profile || "", + avatar: obj.user.avatar || "" + }, + display: function() { + return ( displayFn || self._options.commentformat )( comment ); + } + } + + this._comments.push( comment ); + + if ( !this._popcorn ) { + return; + } + + this._popcorn.subtitle({ + start: comment.start, + target: this._options.commentdiv, + display: 'inline', + language: 'en', + text: comment.display() + }); + } + }); +})( Popcorn, window ); \ No newline at end of file diff --git a/players/soundcloud/popcorn.soundcloud.unit.html b/players/soundcloud/popcorn.soundcloud.unit.html new file mode 100644 index 0000000..dc2e486 --- /dev/null +++ b/players/soundcloud/popcorn.soundcloud.unit.html @@ -0,0 +1,43 @@ + + + + Popcorn Base Player Plugin + + + + + + + + + + + + +

Popcorn Base Player Plugin

+

+
+

+
    +
    + +
    +
    + + + diff --git a/players/soundcloud/popcorn.soundcloud.unit.js b/players/soundcloud/popcorn.soundcloud.unit.js new file mode 100644 index 0000000..7246058 --- /dev/null +++ b/players/soundcloud/popcorn.soundcloud.unit.js @@ -0,0 +1,409 @@ +module( "Popcorn Soundcloud Player" ); +test( "API", function () { + + var expects = 0, + count = 0, + player = Popcorn.soundcloud( "player_1", { + src: "http://soundcloud.com/forss/flickermood" + }), + members = { + // HTMLMediaElement members + 'readyState' : 'number', + 'currentTime' : 'number', + 'duration' : 'number', + 'paused' : 'number', + 'ended' : 'number', + 'volume' : 'number', + 'muted' : 'function', + 'playbackRate' : 'number', + 'autoplay' : 'undefined', + 'loop' : 'undefined', + 'load' : 'function', + 'play' : 'function', + 'pause' : 'function', + 'timeupdate' : 'function', + 'src' : 'string', + + // DOMElement members + 'addEventListener' : 'function', + 'dispatchEvent' : 'function', + 'getBoundingClientRect' : 'function', + 'width' : 'string', + 'height' : 'string', + 'top' : 'number', + 'left' : 'number', + 'offsetLeft' : 'number', + 'offsetTop' : 'number', + 'offsetHeight' : 'number', + 'offsetWidth' : 'number', + + // Helper functions and members + 'setVolume' : 'function', + 'setCurrentTime' : 'function', + 'timeupdate' : 'function', + 'registerPopcornWithPlayer' : 'function' + }; + + function plus() { + if ( ++count === expects ) { + start(); + } + } + + Popcorn.forEach( members, function () { + expects++; + }); + + expect( expects ); + stop( 10000 ); + + Popcorn.forEach( members, function ( type, prop ) { + ok( typeof player[prop] === type, "player." + prop + " is type: '" + player[prop] + "', should be '" + type + "'" ); + plus(); + }); +}); + +test( "Default Attribute Functionality", function () { + var expects = 7, + count = 0, + playerDefault, + playerOverride, + members = { + // HTMLMediaElement members + 'currentTime' : 0, + 'readyState' : 0, + 'duration' : 0, + 'volume' : 1, + 'paused' : 1, + 'ended' : 0, + 'muted' : false, + 'playbackRate' : 1, + 'src' : 'http://soundcloud.com/forss/flickermood', + + // DOMElement members + 'height' : '81px', + 'top' : 0, + 'left' : 0, + 'offsetHeight' : 81, + }; + + function plus() { + if ( ++count === expects ) { + start(); + cleanup(); + } + } + + Popcorn.forEach( members, function () { + expects++; + }); + + expect( expects ); + stop( 10000 ); + + playerDefault = Popcorn.soundcloud( "player_2" ); + playerOverride = Popcorn.soundcloud( "player_2", { + height: "100px", + width: '90%', + src: "http://soundcloud.com/forss/journeyman" + }); + + playerDefault.addEventListener( "load", function() { + equals( playerDefault.duration, 213.89, "Duration updated" ); + plus(); + }); + + Popcorn.forEach( members, function ( val, prop ) { + var actual = playerDefault[prop]; + + if ( typeof playerDefault[prop] === 'function' ) { + actual = playerDefault[prop](); + } + + equals( actual, val, "player." + prop + " should have default value: '" + val + "'" ); + plus(); + }); + + equals( document.getElementById( "player_2" ).children.length, 2, "The container has 2 players" ); + plus(); + + equals( playerDefault.width, playerDefault.offsetWidth+"px", "Width is stringified version of offsetWidth" ); + plus(); + + equals( playerOverride.width, "90%", "Width has been overridden" ); + plus(); + + equals( playerOverride.height, "81px", "Height has been overridden to 100px, but set back again to 81px" ); + plus(); + + notEqual( playerOverride.src, document.getElementById( "player_2" ).getAttribute( "data-src" ), "Source has been overridden" ); + plus(); + + equals( playerOverride.src, "http://soundcloud.com/forss/journeyman", "Source is set correctly" ); + plus(); +}); + +test( "Player Volume Control", function () { + var expects = 3, + count = 0, + player = Popcorn.soundcloud( "player_1" ), + targetVolume, + startVolume; + + function plus() { + if ( ++count === expects ) { + start(); + } + } + + expect(expects); + stop( 50000 ); + + player.addEventListener( "load", function() { + // VolumeChange is fired shortly after load when the volume is retrieved from the player + // Defer volume tests until after that has run + player.addEventListener( "volumechange", function() { + if ( count >= expects ) { + return; + } + + equals( player.volume, targetVolume, "Volume change set correctly" ); + plus(); + + if ( targetVolume !== 0 ) { + targetVolume = 0; + player.mute(); + } else { + targetVolume = startVolume; + // Unmute + player.mute(); + } + }); + + player.volume = targetVolume = startVolume = ( player.volume === 1 ? 0.5 : 1 ); + }); +}); + +test( "Testing Comments", function() { + var expects = 0, + count = 0, + cmtDate = new Date(), + comment, + players = { + player1: Popcorn.soundcloud( "player_1" ), + player2: Popcorn.soundcloud( "player_2", { + commentformat: function( comment ) { + return comment.text + } + }), + player3: Popcorn.soundcloud( "player_1" ) + } + // Expecteed comment output + commentOutput = { + player1: function() { + return '
    ' + + '' + + 'User 1 at 0.03 1 hour ago' + + '
    Hi'; + }, + player2: function() { + return "Hi"; + }, + player3: function() { + return "User 1 @ 3: Hi"; + } + }; + + function plus() { + if ( ++count === expects ) { + start(); + } + } + + // Set comment date to 1 hour ago + cmtDate.setTime( cmtDate.getTime() - 3600000 ); + + comment = { + start: 3, + date: cmtDate, + text: "Hi", + user: { + name: "User 1", + profile: "Hyperlink", + avatar: "Image" + } + }; + + players["player1"].addComment( comment ); + players["player2"].addComment( comment ); + players["player3"].addComment( comment, function( comment ) { + return comment.user.name + " @ " + comment.start + ": "+ comment.text; + }); + + Popcorn.forEach( players, function () { + // 1 comment per player + expects++; + }); + + expect( expects ); + stop( 1000 ); + + Popcorn.forEach( players, function ( player, name ) { + equals( player._comments[0].display(), commentOutput[name](), name + " formatted as expected" ); + plus(); + }); +}); + +test( "Popcorn Integration", function () { + var expects = 4, + count = 0, + player = Popcorn.soundcloud( "player_1" ); + + function plus() { + if ( ++count === expects ) { + start(); + } + } + + expect(expects); + stop( 10000 ); + + player.addEventListener( "load", function() { + ok( true, "Listen works (load event)" ); + plus(); + + player.addEventListener( "play", function() { + ok( true, "Play triggered by popcorn.trigger" ); + plus(); + + player.pause(); + }); + + player.addEventListener( "pause", function() { + ok( true, "Pause explicitly called" ); + plus(); + + player.volume = ( player.volume === 1 ? 0.5 : 1 ); + }); + + player.addEventListener( "volumechange", function() { + ok( true, "Volume changed explicitly called" ); + plus(); + }); + + player.play(); + + }); +}); + + +test( "Events and Player Control", function () { + var expects = 14, + count = 0, + player = Popcorn.soundcloud( "player_1" ), + targetVolume; + + function plus() { + if ( ++count === expects ) { + start(); + } + } + + expect(expects); + stop( 60000 ); + + player.addEventListener( "load", function() { + ok( true, "Load was fired" ); + plus(); + }); + + player.addEventListener( "playing", function() { + ok( true, "Playing was fired" ); + plus(); + + equals( player.paused, 0, "Paused is unset" ); + plus(); + }); + + player.addEventListener( "play", ( function() { + var hasFired = 0; + + return function() { + if ( hasFired ) { + return; + } + + hasFired = 1; + + ok( true, "Play was fired" ); + plus(); + } + })()); + + player.addEventListener( "durationchange", function() { + ok( true, "DurationChange was fired" ); + plus(); + }); + + player.addEventListener( "readystatechange", function() { + ok( true, "ReadyStateChange was fired" ); + plus(); + + equals( player.readyState, 3, "Ready State is now 3" ); + plus(); + + player.pause(); + }); + + player.addEventListener( "pause", function() { + ok( true, "Pause was fired by dispatch" ); + plus(); + + equals( player.paused, 1, "Paused is set" ); + plus(); + }); + + player.addEventListener( "timeupdate", ( function() { + var hasFired = 0; + + return function() { + if ( hasFired ) { + return; + } + hasFired = 1; + + ok( true, "Timeupdate was fired by dispatch" ); + plus(); + } + })()); + + player.addEventListener( "volumechange", function() { + ok( true, "volumechange was fired by dispatch" ); + plus(); + }); + + player.addEventListener( "canplaythrough", function() { + ok( true, "Can play through" ); + plus(); + + // Will trigger a "seeked" event to near end + player.currentTime = player.duration - 1; + }); + + player.addEventListener( "seeked", function() { + ok( true, "Seeked was fired" ); + plus(); + + player.dispatchEvent( "play" ); + }); + + player.addEventListener( "ended", function() { + ok( true, "Media is done playing" ); + plus(); + + equals( player.paused, 1, "Paused is set on end" ); + plus(); + }); + + player.play(); +});