--- /dev/null
+/*
+* 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);
+ }
+ };
+
+})();
--- /dev/null
+<!DOCTYPE html>
+<html>
+ <head>
+ <title>Popcorn Soundcloud Player Example</title>
+ <style>
+ #media_1{
+ width: 80%;
+ }
+ </style>
+
+ <script src="../../popcorn.js"></script>
+ <script type="text/javascript" src="popcorn.soundcloud.js"></script>
+
+ <!-- Plugins for demo purposes -->
+ <script src="../../plugins/footnote/popcorn.footnote.js"></script>
+ <script src="../../plugins/flickr/popcorn.flickr.js"></script>
+ <script src="../../plugins/attribution/popcorn.attribution.js"></script>
+ <script src="../../plugins/webpage/popcorn.webpage.js"></script>
+ <script src="../../plugins/googlefeed/popcorn.googlefeed.js"></script>
+ <script src="../../plugins/image/popcorn.image.js"></script>
+ <script src="../../plugins/subtitle/popcorn.subtitle.js"></script>
+ <script src="../../plugins/twitter/popcorn.twitter.js"></script>
+
+ <script type="text/javascript">
+ //On document ready
+ document.addEventListener( "DOMContentLoaded", function() {
+ var popcorn;
+
+ document.getElementById( "btnPlay" ).addEventListener( "click", function() {
+ popcorn.play();
+ }, false);
+
+ document.getElementById( "btnPause" ).addEventListener( "click", function() {
+ popcorn.pause();
+ }, false);
+
+ document.getElementById( "btnSeek" ).addEventListener( "click", function() {
+ popcorn.currentTime( 30 );
+ }, false);
+
+ document.getElementById( "btnVolume" ).addEventListener( "click", function() {
+ if ( popcorn.volume() >= 0.5 ) {
+ popcorn.volume( popcorn.volume()/2 );
+ this.innerHTML = "Double Volume";
+ } else {
+ popcorn.volume( popcorn.volume()*2 );
+ this.innerHTML = "Halve Volume";
+ }
+ }, false);
+
+ document.getElementById( "btnMute" ).addEventListener( "click", function() {
+ popcorn.mute();
+ }, false);
+
+ popcorn = Popcorn( Popcorn.soundcloud( "media_1", {
+ width: "50%",
+ /*
+ This demo contains an api key used for retrieving comments from Soundcloud's API
+ It is to be used for demonstration purposes only, and for only this demo
+ */
+ api_key: "PRaNFlda6Bhf5utPjUsptg",
+ commentdiv: "commentDisplay",
+ commentformat: (function() {
+ var count = 0;
+
+ return function( comment ) {
+ return "<div>Comment # " + ( count++ ) + "<br />"
+ + "<em>" + comment.user.name + "</em>: " + comment.text +"</div>";
+ }
+ })()
+ }) );
+
+ popcorn.listen( "load", function() {
+
+ document.getElementById( "media_duration" ).innerHTML = popcorn.duration();
+ document.getElementById( "media_volume" ).innerHTML = popcorn.volume();
+ document.getElementById( "media_currentTime" ).innerHTML = popcorn.currentTime();
+ document.getElementById( "media_readyState" ).innerHTML = popcorn.video.readyState;
+
+ popcorn.listen( "timeupdate", function() {
+ document.getElementById( "media_currentTime" ).innerHTML = popcorn.currentTime();
+ });
+
+ popcorn.video.addEventListener( "readystatechange", function() {
+ document.getElementById( "media_readyState" ).innerHTML = popcorn.video.readyState;
+ });
+
+ popcorn.listen( "volumechange", function() {
+ document.getElementById( "media_volume" ).innerHTML = popcorn.volume();
+ });
+
+ popcorn.trigger( "play" );
+ });
+
+ // Empty for the purposes of allowing popcorn.trigger("play");
+ popcorn.listen( "play", function() {
+
+ });
+
+ popcorn.subtitle({
+ start: 5, // seconds
+ end: 15, // seconds
+ text: 'This is overlaid on top of the audio visualization. You can hightlight it!',
+ display: 'inline',
+ language: "en"
+ });
+
+ popcorn.footnote({
+ start: 5, // seconds
+ end: 40, // seconds
+ text: 'The song is "Flickermood", by Forss',
+ target: 'footnotediv'
+ })
+ .flickr({
+ start: 20, // seconds
+ end: 40, // seconds
+ tags: 'georgia',
+ numberofimages: '8',
+ target: 'flickrdiv'
+ })
+ .twitter({
+ start: 20, // seconds
+ end: 45, // seconds
+ title: 'Oil Spill',
+ src: '#oilspill',
+ target: 'twitterdiv'
+ })
+ .attribution({
+ start: 5, // seconds
+ end: 60, // seconds
+ nameofwork: "Flickermood",
+ nameofworkurl:"http://soundcloud.com/forss/flickermood",
+ copyrightholder:"Sonar Kollektiv",
+ license:"CC-BY-NC-ND",
+ licenseurl: "http://creativecommons.org/licenses/by-nc-nd/2.0/",
+ target: 'attribdiv'
+ })
+ .webpage({
+ id: "webpages-a",
+ start: 0, // seconds
+ end: 15, // seconds
+ src: 'http://webmademovies.org/',
+ target: 'webpagediv'
+ })
+ .googlefeed({
+ start: 0, // seconds
+ end: 15, // seconds
+ target: "feeddiv",
+ url: "http://zenit.senecac.on.ca/~chris.tyler/planet/rss20.xml",
+ title: "Planet Feed",
+ orientation: "Vertical"
+ })
+ .image({
+ start: 5, // seconds
+ end: 15, // seconds
+ href: 'http://www.drumbeat.org/',
+ src: 'https://www.drumbeat.org/media//images/drumbeat-logo-splash.png',
+ target: 'imagediv'
+ })
+ .video.registerPopcornWithPlayer( popcorn );
+ }, false);
+ </script>
+ </head>
+ <body>
+ <div id="media_1" data-width="" data-height="" data-src="http://soundcloud.com/forss/flickermood" ></div><br />
+
+ <div>
+ <button class="simple" id="btnPlay">Play</button>
+ <button class="simple" id="btnPause">Pause</button>
+ <button class="seek" id="btnSeek">Seek to 30</button>
+ <button class="volume" id="btnVolume">Toggle Volume</button>
+ <button class="volume" id="btnMute">Mute</button><br />
+
+ <div style="float: left;">
+ Current Time (s): <span id="media_currentTime"></span>
+ <br />Duration (s): <span id="media_duration"></span>
+ <br />Volume (0-1): <span id="media_volume"></span>
+ <br />Ready State: <span id="media_readyState">0</span>
+ </div>
+ <div style="position: absolute; left: 350px;">
+ <strong>Comment Area</strong>
+ <div id="commentDisplay"></div>
+ </div>
+
+ </div>
+ <div style="float:right; width: 100%;">
+ <h3>Description</h3>
+ <p>
+ 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.<br />
+ Due to the Flash security model, this demo must be run from a web server<br />
+ <hr >
+ 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.<br />
+ Clicking play/pause or seeking in either the Soundcloud player or via custsom controls will cause the other to update.<br />
+ 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.<br/>
+ Specifying the source in the constructor will override any source specified on the container element.<br/>
+ Player width/height can be specified as container attributes (data-width, data-height), or as styles (width, height). Styles can be inline or CSS.<br/>
+ If no width or height are given, they default to '100%' and '81px' respectively.<br/>
+ Width/height precendence is in this order: constructor, container attributes, natural (manually given inline/CSS styles), default<br/>
+ </p>
+ <h4>Expected Events</h4>
+ <ul>
+ <li>Throughout the track, user comments from Soundcloud will appear below 'Comment Area'.</li>
+ <li>From 0 to 15 seconds, the site 'http://webmademovies.org/' will appear below 'Web Page Area'.</li>
+ <li>From 0 to 20 seconds, blogs from 'http://zenit.senecac.on.ca/~chris.tyler/planet/rss20.xml' will appear below 'Google Feed Area'.</li>
+ <li>From 5 to 15 seconds, the subtitle 'This is overlaid on top of the audio visualization. You can hightlight it!' will be overlaid on the Soundcloud player.</li>
+ <li>From 5 to 15 seconds, the Mozilla Drumbeat logo will appear below 'Image Area'.</li>
+ <li>From 5 to 40 seconds, the footnote 'The song is "Flickermood", by Forss' will appear below 'Footnote Area'.</li>
+ <li>From 5 to 60 seconds, the Creative Commons license will appear below 'Attributions Area'.</li>
+ <li>From 20 to 40 seconds, the a flickr stream of 8 images tagged 'georgia' will appear below 'Flickr Area'.</li>
+ <li>From 20 to 45 seconds, tweets tagged #oilspill will appear below 'Twitter Area'.</li>
+ </ul>
+ <br />
+ <br />
+ <br />
+ <div id="footnotediv" width="50%" height="50%">
+ <strong>Footnote Area</strong><br />
+ </div>
+ <div id="attribdiv" width="50%" height="50%">
+ <strong>Attributions Area</strong><br />
+ </div>
+ <div id="flickrdiv" width="50%" height="50%">
+ <strong>Flickr Area</strong><br />
+ </div>
+ <div id="twitterdiv" width="50%" height="50%">
+ <strong>Twitter Area</strong><br />
+ </div>
+ <div id="imagediv" width="50%" height="50%">
+ <strong>Image Area</strong><br />
+ </div>
+ <div id="feeddiv" width="50%" height="50%">
+ <strong>Google Feed Area</strong><br />
+ </div>
+ <div id="webpagediv" width="100px" height="50px">
+ <strong>Web Page Area</strong><br />
+ </div>
+ </div>
+
+ <br />
+ <br />
+ </body>
+</html>
\ No newline at end of file
--- /dev/null
+// 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
+ *
+ * <div id="player_1" data-width="500" data-height="281" data-src="http://soundcloud.com/forss/flickermood" ></div>
+ * <script type="text/javascript">
+ * document.addEventListener("DOMContentLoaded", function() {
+ * var popcorn = Popcorn( Popcorn.soundcloud( "player_1" ) );
+ * }, false);
+ * </script>
+ *
+ * 2. Pass the div id and the embed code path supplied by Soundcloud into a new Popcorn.soundcloud object
+ *
+ * <div id="player_1" data-width="500" data-height="281" data-src="" ></div>
+ * <script type="text/javascript">
+ * document.addEventListener("DOMContentLoaded", function() {
+ * var popcorn = Popcorn( Popcorn.soundcloud( "player_1", { src: "http://soundcloud.com/forss/flickermood" } ) );
+ * }, false);
+ * </script>
+ *
+ * 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 '<div><a href="' + comment.user.profile + '">'
+ + '<img width="16px height="16px" src="' + comment.user.avatar + '"></img>'
+ + comment.user.name + '</a> at ' + timeToFraction( comment.start ) + ' '
+ + ago( comment.date )
+ + '<br />' + comment.text + '</span>';
+ }
+
+ 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
--- /dev/null
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Popcorn Base Player Plugin</title>
+ <link rel="stylesheet" href="../../test/qunit/qunit.css" type="text/css" media="screen">
+ <script src="../../test/qunit/qunit.js"></script>
+ <!--
+ do not move - this must be called immediately prior to
+ popcorn-api-draft.js
+ -->
+
+ <script src="../../popcorn.js"></script>
+
+ <script src="popcorn.soundcloud.unit.js"></script>
+ <script src="popcorn.soundcloud.js"></script>
+
+ <style>
+ .soundcloudPlayer {
+ left: 20px;
+ }
+
+ #player_1 {
+ width: 80%;
+ }
+
+ #player_2 {
+ width: 70%;
+ }
+ </style>
+</head>
+<body>
+ <h1 id="qunit-header">Popcorn Base Player Plugin</h1>
+ <h2 id="qunit-banner"></h2>
+ <div id="qunit-testrunner-toolbar"></div>
+ <h2 id="qunit-userAgent"></h2>
+ <ol id="qunit-tests"></ol>
+ <div id="qunit-fixture"> </div>
+
+ <div class="soundcloudPlayer" id="player_1" data-src="http://soundcloud.com/forss/flickermood" ></div>
+ <div class="soundcloudPlayer" id="player_2" data-src="http://soundcloud.com/forss/flickermood" data-width="790px" ></div>
+
+</body>
+</html>
--- /dev/null
+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 '<div><a href="Hyperlink">'
+ + '<img width="16px height="16px" src="Image"></img>'
+ + 'User 1</a> at 0.03 1 hour ago'
+ + '<br />Hi</span>';
+ },
+ 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();
+});