commit d338706cecded101bde969e70bfe516c81ae6f99 Author: Michael Deal Date: Wed Feb 15 20:46:03 2012 -0800 let there be midi diff --git a/MIDIPlayer.css b/MIDIPlayer.css new file mode 100644 index 0000000..4c4912e --- /dev/null +++ b/MIDIPlayer.css @@ -0,0 +1,164 @@ +body { + font-family: Andada; + font-size: 1.2em; + line-height: 2em; + background: #fcfae9; + color: #907d62; + margin: 0 50px; +} +div.player { + background-image: -webkit-gradient(linear,left top,left bottom,from(rgba(66,66,66,1)),to(rgba(22,22,22,1))); + background-image: -webkit-linear-gradient(top, rgba(66, 66, 66, 1) 0%, rgba(22, 22, 22, 1) 100%); + background-image: -moz-linear-gradient(top, rgba(66, 66, 66, 1) 0%, rgba(22, 22, 22, 1) 100%); + background-image: -ms-gradient(top, rgba(66, 66, 66, 1) 0%, rgba(22, 22, 22, 1) 100%); + background-image: -o-gradient(top, rgba(66, 66, 66, 1) 0%, rgba(22, 22, 22, 1) 100%); + background-image: linear-gradient(top, rgba(66, 66, 66, 1) 0%, rgba(22, 22, 22, 1) 100%); + padding: 15px 20px; + border: 1px solid #000; + box-shadow: 0 0 10px #fff; + -moz-box-shadow: 0 0 10px #fff; + -webkit-box-shadow: 0 0 10px #fff; + border-radius: 10px; + -moz-border-radius: 10px; + -webkit-border-radius: 10px; + color: #FFFFFF; + color: rgba(255, 255, 255, 0.8); + text-shadow: 1px 1px 2px #000; + -moz-text-shadow: 1px 1px 2px #000; + margin-bottom: 15px; +} +div.player #capsule { + border: 1px solid #000; + box-shadow: 0 0 10px #555; + -moz-box-shadow: 0 0 10px #555; + -webkit-box-shadow: 0 0 10px #555; + background: #000; + background-image: -webkit-gradient(linear, left top, left bottom, color-stop(1, rgba(0,0,0,0.5)), color-stop(0, #333)); + background-image: -webkit-linear-gradient(top, rgba(0, 0, 0, 0.5) 1, #333 0); + background-image: -moz-linear-gradient(top, rgba(0, 0, 0, 0.5) 1, #333 0); + background-image: -ms-gradient(top, rgba(0, 0, 0, 0.5) 1, #333 0); + background-image: -o-gradient(top, rgba(0, 0, 0, 0.5) 1, #333 0); + background-image: linear-gradient(top, rgba(0, 0, 0, 0.5) 1, #333 0); + overflow: hidden; + border-radius: 5px; + -moz-border-radius: 5px; + -webkit-border-radius: 5px; + width: 420px; + display: inline-block; + height: 30px; +} +div.player #capsule #cursor { + border-radius: 5px; + -moz-border-radius: 5px; + -webkit-border-radius: 5px; + border-top-right-radius: 0; + border-bottom-right-radius: 0; + background: #003b96; + background-image: -webkit-gradient(linear, left top, left bottom, color-stop(1, #003b96), color-stop(0, #0088e9)); + background-image: -webkit-linear-gradient(top, #003b96 1, #0088e9 0); + background-image: -moz-linear-gradient(top, #003b96 1, #0088e9 0); + background-image: -ms-gradient(top, #003b96 1, #0088e9 0); + background-image: -o-gradient(top, #003b96 1, #0088e9 0); + background-image: linear-gradient(top, #003b96 1, #0088e9 0); + width: 0; + display: inline-block; + height: 100%; +} +div.player span.time { + position: relative; + top: -9px; + padding: 0 10px; + width: 40px; + display: inline-block; + text-align: right; +} +div.player div.time-controls { + width: 560px; + margin: 10px auto 0; +} +input[type="image"]:hover { + opacity: 1; +} +input[type="image"]:active { + opacity: 0.85; +} +input[type="image"] { + opacity: 0.7; +} +p { + margin: 15px 0 0 15px; + color: #403522; +} + li { + color: #403522; +} +li { + margin-bottom: 20px; + color: #000; + background: rgba(255, 0, 0, 0); + border-radius: 10px; + -moz-border-radius: 10px; + -webkit-border-radius: 10px; + list-style-type: none; + padding: 2px 10px; +} +pre { + width: 90%; + overflow-x: scroll; + padding: 0; + margin: 0; +} +pre b { + color: #fff; + background: rgba(255, 0, 0, 0.5); + padding: 2px 5px; +} +li.indent { + color: #403522; + background: none; + position: relative; + left: 50px; + list-style-type: none; +} +li.indent.square { + background: none; + list-style-type: square; +} +h3 { + background-image: -webkit-gradient(linear, left top, left bottom, color-stop(1, rgba(0, 200, 255, 0.35)), color-stop(0, rgba(0,88,127,0.42))); + color: #fff; + text-shadow: 1px 1px #000; + padding: 2px 10px; + border-bottom: 1px solid rgba(0,0,0,0.3); + border-top: 1px solid rgba(0,0,0,0.6); +} +li a { + color: #000; +} +h3 a { + color: #fff; +} +a, li.indent.demos a { + color: #06f; +} +li a:hover, a:hover, li.indent.demos a:hover { + color: #c09; +} +h3 a:hover { + color: #ff0; +} +h3 { + font-family: Oswald; +} +h1 { + font-family: Oswald; font-size: 2em; font-weight: bold; z-index: 2; padding-left: 15px; position: relative; color: rgba(0,0,0,0.5); text-shadow: 0 0 7px rgba(255,255,0,0.50); +} + + +#colors div { + -webkit-transition-property: background, color; + -webkit-transition-duration: .25s; +padding: 1px 0 1px 5px; font-family: arial; font-size: 9px; line-height: 9px; color: #aaa; width: 30px; height: 9px; + background-image: -webkit-gradient(linear,left top,left bottom,from(rgba(66,66,66,0.75)),to(rgba(0,0,0,1))); +border-bottom: 1px solid rgba(5,5,5,0.7); +} \ No newline at end of file diff --git a/MIDIPlayer.html b/MIDIPlayer.html new file mode 100644 index 0000000..712bf76 --- /dev/null +++ b/MIDIPlayer.html @@ -0,0 +1,362 @@ + + + + + MIDI.js - Sequencing in Javascript. + + + + + + + + + + + + + + + + + + + + + + + + + +

MIDI.js - Sequencing in Javascript.

+
+
+
+
+ + + + +
+
+ 0:00 + + + + -0:00 +
+
+
Loading API...
+

What’s all this hubub?

+

MIDI.js (on github) ties together, and builds upon frameworks that bring MIDI generation to the browser. + Combine it with jasmid to create a web-radio MIDI stream similar to this demo... + or with Three.js, Sparks.js, or GLSL to create Audio/visual experiments. + Piano/guitar simulations, Drum machines, MIDI recording, and all kinds of certified funkitude is within your grasps! +

Google Chrome is recommended for best listening experience, it’s timing perfection! Firefox and Safari can both perform a bit more like the piano has been drinking, arrr.

+

Carpe beerum, and commandeer yer own copy!

+

Description of package;

+
  • MIDI.loadPlugin.js:  Decides which framework is best to use, and sends request.
  • +
  • +
    +// interface to download soundfont, then execute callback;
    +MIDI.loadPlugin(callback, soundfont);
    +// simple example to get started;
    +MIDI.loadPlugin(function() {
    +	MIDI.noteOn(0, 100, 127, 0); // plays note once loaded
    +}, "soundfont/soundfont-ogg-guitar.js");
    +
    +
  • +
  • MIDI.Soundfont.js:  Customizable base64 Soundfont.
  • +
  • Encode your own soundfonts, Drums, Guitars, and so on.
  • +
  • You are listening to Fluid (R3) General MIDI SoundFont (GM).
  • +
  • MIDI.Plugin.js:  Ties together the following frameworks;
  • +
  • +MIDI.noteOn(channel, note, velocity, delay);
    +MIDI.noteOff(channel, note, delay);
    +MIDI.chordOn(channel, chord, velocity, delay);
    +MIDI.chordOff(channel, chord, delay);
    +MIDI.keyToNote = object; // A0 => 21
    +MIDI.noteToKey = object; // 21 => A0
    +
  • +
  • MIDI.Player.js:  Streams the MIDI to the browser. +
  • +
    +MIDI.Player.currentTime = integer; // time we are at now within the song.
    +MIDI.Player.endTime = integer; // time when song ends.
    +MIDI.Player.playing = boolean; // are we playing? yes or no.
    +MIDI.Player.loadFile(file, callback); // load .MIDI from base64 or binary XML request.
    +MIDI.Player.start(); // start the MIDI track (you can put this in the loadFile callback)
    +MIDI.Player.resume(); // resume the MIDI track from pause.
    +MIDI.Player.pause(); // pause the MIDI track.
    +MIDI.Player.stop(); // stops all audio being played, and resets currentTime to 0.
    +Callback whenever a note is played;
    +MIDI.Player.removeListener(); // removes current listener.
    +MIDI.Player.addListener(function(data) { // set it to your own function!
    +	var now = data.now; // where we are now
    +	var end = data.end; // time when song ends
    +	var channel = data.channel; // channel note is playing on
    +	var message = data.message; // 128 is noteOff, 144 is noteOn
    +	var note = data.note; // the note
    +	var velocity = data.velocity; // the velocity of the note
    +	// then do whatever you want with the information!
    +});
    +Smooth animation, interpolates between onMidiEvent calls;
    +MIDI.Player.clearAnimation(); // clears current animation.
    +MIDI.Player.setAnimation(function(data) {
    +	var now = data.now; // where we are now
    +	var end = data.end; // time when song ends
    +	var events = data.events; // all the notes currently being processed
    +	// then do what you want with the information!
    +});
  • + +
  • Color.js:  Color conversions, music isn’t complete without!
  • +
  • Color.Space(0xff0000, "HEX>RGB>HSL");
  • +
  • DOMLoader.script.js:  Loads scripts in synchronously, or asynchronously.
  • +
  • DOMLoader.script.add(src, callback);
  • +
  • DOMLoader.XMLHttp.js:  Cross-browser XMLHttpd request.
  • +
  • DOMLoader.sendRequest(src, callback);
  • +
  • MusicTheory.Synesthesia.js:  Note-to-color mappings (from Isaac Newton onwards).
  • +

    Many thanks to the authors of these libraries;

    +
  • <audio>:  HTML5 specs
  • +
  • WebAudioAPI:  W3C proposal by Google
  • +
  • Java package:  MIDIBridge by Daniel van der Meer
  • +
  • Use this to hook up a MIDI keyboard to your browser!
  • +
  • Access to 128 General MIDI instruments.
  • +
  • Flash package:  SoundManager2 by Scott Schiller
  • +
  • jasmid:  Reads MIDI file byte-code, and translats into a Javascript array.
  • +
  • base642binary.js:  Cleans up XML base64-requests for Web Audio API.
  • +

    Example(s):  Tweet me your app to be included!

    +
  • + Color Piano
    Learn piano songs without reading sheet music. +
    Coded by mud.
  • +
    +
  • + Guitar Player
    Learn how to play chords on the guitar. +
    Coded by mud.
  • +
    +
  • + Whitney Music Box
    Beautiful HTML5 simulation of a Whitney Music Box. +
    Coded by KrazyDad.
  • +
    + + + \ No newline at end of file diff --git a/README.html b/README.html new file mode 100644 index 0000000..c43bd4e --- /dev/null +++ b/README.html @@ -0,0 +1,142 @@ + +

    Description of package;

    +
  • MIDI.loadPlugin.js:  Decides which framework is best to use, and sends request.
  • +
  • +
    +// interface to download soundfont, then execute callback;
    +MIDI.loadPlugin(callback, soundfont);
    +// simple example to get started;
    +MIDI.loadPlugin(function() {
    +	MIDI.noteOn(0, 100, 127, 0); // plays note once loaded
    +}, "soundfont/soundfont-ogg-guitar.js");
    +
    +
  • +
  • MIDI.Soundfont.js:  Customizable base64 Soundfont.
  • +
  • Encode your own soundfonts, Drums, Guitars, and so on.
  • +
  • Share them with the community!
  • +
  • MIDI.Plugin.js:  Ties together the following frameworks;
  • +
  • +MIDI.noteOn(channel, note, velocity, delay);
    +MIDI.noteOff(channel, note, delay);
    +MIDI.chordOn(channel, chord, velocity, delay);
    +MIDI.chordOff(channel, chord, delay);
    +MIDI.keyToNote = object; // A0 => 21
    +MIDI.noteToKey = object; // 21 => A0
    +
  • +
  • MIDI.Player.js:  Streams the MIDI to the browser. +
  • +
    +MIDI.Player.currentTime = integer; // time we are at now within the song.
    +MIDI.Player.endTime = integer; // time when song ends.
    +MIDI.Player.playing = boolean; // are we playing? yes or no.
    +MIDI.Player.loadFile(file, callback); // load .MIDI from base64 or binary XML request.
    +MIDI.Player.start(); // start the MIDI track (you can put this in the loadFile callback)
    +MIDI.Player.resume(); // resume the MIDI track from pause.
    +MIDI.Player.pause(); // pause the MIDI track.
    +MIDI.Player.stop(); // stops all audio being played, and resets currentTime to 0.
    +Callback whenever a note is played;
    +MIDI.Player.removeListener(); // removes current listener.
    +MIDI.Player.addListener(function(data) { // set it to your own function!
    +	var now = data.now; // where we are now
    +	var end = data.end; // time when song ends
    +	var channel = data.channel; // channel note is playing on
    +	var message = data.message; // 128 is noteOff, 144 is noteOn
    +	var note = data.note; // the note
    +	var velocity = data.velocity; // the velocity of the note
    +	// then do whatever you want with the information!
    +});
    +Smooth animation, interpolates between onMidiEvent calls;
    +MIDI.Player.clearAnimation(); // clears current animation.
    +MIDI.Player.setAnimation(function(data) {
    +	var now = data.now; // where we are now
    +	var end = data.end; // time when song ends
    +	var events = data.events; // all the notes currently being processed
    +	// then do what you want with the information!
    +});
  • + +
  • Color.js:  Color conversions, music isn’t complete without!
  • +
  • Color.Space(0xff0000, "HEX>RGB>HSL");
  • +
  • DOMLoader.script.js:  Loads scripts in synchronously, or asynchronously.
  • +
  • DOMLoader.script.add(src, callback);
  • +
  • DOMLoader.XMLHttp.js:  Cross-browser XMLHttpd request.
  • +
  • DOMLoader.sendRequest(src, callback);
  • +
  • MusicTheory.Synesthesia.js:  Note-to-color mappings (from Isaac Newton onwards).
  • +

    Many thanks to the authors of these libraries;

    +
  • <audio>:  HTML5 specs
  • +
  • WebAudioAPI:  W3C proposal by Google
  • +
  • Java package:  MIDIBridge by Daniel van der Meer
  • +
  • Use this to hook up a MIDI keyboard to your browser!
  • +
  • Access to 128 General MIDI instruments.
  • +
  • Flash package:  SoundManager2 by Scott Schiller
  • +
  • jasmid:  Reads MIDI file byte-code, and translats into a Javascript array.
  • +
  • base642binary.js:  Cleans up XML base64-requests for Web Audio API.
  • + diff --git a/WhitneyMusicBox.html b/WhitneyMusicBox.html new file mode 100644 index 0000000..f06ccad --- /dev/null +++ b/WhitneyMusicBox.html @@ -0,0 +1,112 @@ + + + +Whitney Music Box in HTML5 + + + + + + + + + + + + + + + + + + +Whitney Music Box animation in HTML5.
    +Graphics code by Jim Bumgardner.
    +Audio created with MIDI.js
    + + + + \ No newline at end of file diff --git a/images/backward.png b/images/backward.png new file mode 100644 index 0000000..e021903 Binary files /dev/null and b/images/backward.png differ diff --git a/images/forward.png b/images/forward.png new file mode 100644 index 0000000..3046db3 Binary files /dev/null and b/images/forward.png differ diff --git a/images/pause.png b/images/pause.png new file mode 100644 index 0000000..4bd7b58 Binary files /dev/null and b/images/pause.png differ diff --git a/images/play.png b/images/play.png new file mode 100644 index 0000000..d4cda72 Binary files /dev/null and b/images/play.png differ diff --git a/images/shiverMeTimbers.gif b/images/shiverMeTimbers.gif new file mode 100644 index 0000000..3b65c20 Binary files /dev/null and b/images/shiverMeTimbers.gif differ diff --git a/images/stop.png b/images/stop.png new file mode 100644 index 0000000..515ca60 Binary files /dev/null and b/images/stop.png differ diff --git a/images/tuna.png b/images/tuna.png new file mode 100644 index 0000000..3df32a8 Binary files /dev/null and b/images/tuna.png differ diff --git a/inc/SoundManager2/license.txt b/inc/SoundManager2/license.txt new file mode 100755 index 0000000..1a17182 --- /dev/null +++ b/inc/SoundManager2/license.txt @@ -0,0 +1,29 @@ +Software License Agreement (BSD License) + +Copyright (c) 2007, Scott Schiller (schillmania.com) +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + +* Neither the name of schillmania.com nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission from schillmania.com. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/inc/SoundManager2/script/soundmanager2-jsmin.js b/inc/SoundManager2/script/soundmanager2-jsmin.js new file mode 100755 index 0000000..e8b14ae --- /dev/null +++ b/inc/SoundManager2/script/soundmanager2-jsmin.js @@ -0,0 +1,104 @@ +/** @license + + + SoundManager 2: JavaScript Sound for the Web + ---------------------------------------------- + http://schillmania.com/projects/soundmanager2/ + + Copyright (c) 2007, Scott Schiller. All rights reserved. + Code provided under the BSD License: + http://schillmania.com/projects/soundmanager2/license.txt + + V2.97a.20111220 +*/ +(function(G){function W(W,la){function l(b){return function(a){var d=this._t;return!d||!d._a?(d&&d.sID?c._wD(k+"ignoring "+a.type+": "+d.sID):c._wD(k+"ignoring "+a.type),null):b.call(this,a)}}this.flashVersion=8;this.debugMode=!0;this.debugFlash=!1;this.consoleOnly=this.useConsole=!0;this.waitForWindowLoad=!1;this.bgColor="#ffffff";this.useHighPerformance=!1;this.html5PollingInterval=this.flashPollingInterval=null;this.flashLoadTimeout=1E3;this.wmode=null;this.allowScriptAccess="always";this.useFlashBlock= +!1;this.useHTML5Audio=!0;this.html5Test=/^(probably|maybe)$/i;this.preferFlash=!0;this.noSWFCache=!1;this.audioFormats={mp3:{type:['audio/mpeg; codecs="mp3"',"audio/mpeg","audio/mp3","audio/MPA","audio/mpa-robust"],required:!0},mp4:{related:["aac","m4a"],type:['audio/mp4; codecs="mp4a.40.2"',"audio/aac","audio/x-m4a","audio/MP4A-LATM","audio/mpeg4-generic"],required:!1},ogg:{type:["audio/ogg; codecs=vorbis"],required:!1},wav:{type:['audio/wav; codecs="1"',"audio/wav","audio/wave","audio/x-wav"],required:!1}}; +this.defaultOptions={autoLoad:!1,autoPlay:!1,from:null,loops:1,onid3:null,onload:null,whileloading:null,onplay:null,onpause:null,onresume:null,whileplaying:null,onposition:null,onstop:null,onfailure:null,onfinish:null,multiShot:!0,multiShotEvents:!1,position:null,pan:0,stream:!0,to:null,type:null,usePolicyFile:!1,volume:100};this.flash9Options={isMovieStar:null,usePeakData:!1,useWaveformData:!1,useEQData:!1,onbufferchange:null,ondataerror:null};this.movieStarOptions={bufferTime:3,serverURL:null,onconnect:null, +duration:null};this.movieID="sm2-container";this.id=la||"sm2movie";this.debugID="soundmanager-debug";this.debugURLParam=/([#?&])debug=1/i;this.versionNumber="V2.97a.20111220";this.movieURL=this.version=null;this.url=W||null;this.altURL=null;this.enabled=this.swfLoaded=!1;this.oMC=null;this.sounds={};this.soundIDs=[];this.didFlashBlock=this.muted=!1;this.filePattern=null;this.filePatterns={flash8:/\.mp3(\?.*)?$/i,flash9:/\.mp3(\?.*)?$/i};this.features={buffering:!1,peakData:!1,waveformData:!1,eqData:!1, +movieStar:!1};this.sandbox={type:null,types:{remote:"remote (domain-based) rules",localWithFile:"local with file access (no internet access)",localWithNetwork:"local with network (internet access only, no local access)",localTrusted:"local, trusted (local+internet access)"},description:null,noRemote:null,noLocal:null};var ma;try{ma="undefined"!==typeof Audio&&"undefined"!==typeof(new Audio).canPlayType}catch(fb){ma=!1}this.hasHTML5=ma;this.html5={usingFlash:null};this.flash={};this.ignoreFlash=this.html5Only= +!1;var Ea,c=this,i=null,k="HTML5::",u,p=navigator.userAgent,j=G,O=j.location.href.toString(),h=document,na,X,m,B=[],oa=!0,w,P=!1,Q=!1,n=!1,y=!1,Y=!1,o,Za=0,R,v,pa,H,I,Z,Fa,qa,E,$,aa,J,ra,sa,ba,ca,K,Ga,ta,$a=["log","info","warn","error"],Ha,da,Ia,S=null,ua=null,q,va,L,Ja,ea,fa,wa,s,ga=!1,xa=!1,Ka,La,Ma,ha=0,T=null,ia,z=null,Na,ja,U,C,ya,za,Oa,r,Pa=Array.prototype.slice,F=!1,t,ka,Qa,A,Ra,Aa=p.match(/(ipad|iphone|ipod)/i),ab=p.match(/firefox/i),bb=p.match(/droid/i),D=p.match(/msie/i),cb=p.match(/webkit/i), +V=p.match(/safari/i)&&!p.match(/chrome/i),db=p.match(/opera/i),Ba=p.match(/(mobile|pre\/|xoom)/i)||Aa,Ca=!O.match(/usehtml5audio/i)&&!O.match(/sm2\-ignorebadua/i)&&V&&!p.match(/silk/i)&&p.match(/OS X 10_6_([3-7])/i),Sa="undefined"!==typeof console&&"undefined"!==typeof console.log,Da="undefined"!==typeof h.hasFocus?h.hasFocus():null,M=V&&"undefined"===typeof h.hasFocus,Ta=!M,Ua=/(mp3|mp4|mpa)/i,N=h.location?h.location.protocol.match(/http/i):null,Va=!N?"http://":"",Wa=/^\s*audio\/(?:x-)?(?:mpeg4|aac|flv|mov|mp4||m4v|m4a|mp4v|3gp|3g2)\s*(?:$|;)/i, +Xa="mpeg4,aac,flv,mov,mp4,m4v,f4v,m4a,mp4v,3gp,3g2".split(","),eb=RegExp("\\.("+Xa.join("|")+")(\\?.*)?$","i");this.mimePattern=/^\s*audio\/(?:x-)?(?:mp(?:eg|3))\s*(?:$|;)/i;this.useAltURL=!N;this._global_a=null;if(Ba&&(c.useHTML5Audio=!0,c.preferFlash=!1,Aa))F=c.ignoreFlash=!0;this.supported=this.ok=function(){return z?n&&!y:c.useHTML5Audio&&c.hasHTML5};this.getMovie=function(c){return u(c)||h[c]||j[c]};this.createSound=function(b){function a(){f=ea(f);c.sounds[e.id]=new Ea(e);c.soundIDs.push(e.id); +return c.sounds[e.id]}var d,f=null,e=d=null;d="soundManager.createSound(): "+q(!n?"notReady":"notOK");if(!n||!c.ok())return wa(d),!1;2===arguments.length&&(b={id:arguments[0],url:arguments[1]});f=v(b);f.url=ia(f.url);e=f;e.id.toString().charAt(0).match(/^[0-9]$/)&&c._wD("soundManager.createSound(): "+q("badID",e.id),2);c._wD("soundManager.createSound(): "+e.id+" ("+e.url+")",1);if(s(e.id,!0))return c._wD("soundManager.createSound(): "+e.id+" exists",1),c.sounds[e.id];if(ja(e))d=a(),c._wD("Loading sound "+ +e.id+" via HTML5"),d._setup_html5(e);else{if(8=b)return!1;for(;b--;)if(c=x[b],!c.fired&&a.position>=c.position)c.fired=!0,l++,c.method.apply(c.scope,[c.position]);return!0};this._resetOnPosition=function(a){var b,c;b=x.length;if(!b)return!1;for(;b--;)if(c=x[b],c.fired&&a<=c.position)c.fired=!1,l--;return!0};r=function(){var b=a._iO,d=b.from,e=b.to,f,g;g=function(){c._wD(a.sID+': "to" time of '+e+" reached.");a.clearOnPosition(e,g);a.stop()};f=function(){c._wD(a.sID+ +': playing "from" '+d);if(null!==e&&!isNaN(e))a.onPosition(e,g)};if(null!==d&&!isNaN(d))b.position=d,b.multiShot=!1,f();return b};Ya=function(){var b=a._iO.onposition;if(b)for(var c in b)if(b.hasOwnProperty(c))a.onPosition(parseInt(c,10),b[c])};n=function(){var b=a._iO.onposition;if(b)for(var c in b)b.hasOwnProperty(c)&&a.clearOnPosition(parseInt(c,10))};g=function(){a.isHTML5&&Ka(a)};h=function(){a.isHTML5&&La(a)};d=function(){x=[];l=0;j=!1;a._hasTimer=null;a._a=null;a._html5_canplay=!1;a.bytesLoaded= +null;a.bytesTotal=null;a.duration=a._iO&&a._iO.duration?a._iO.duration:null;a.durationEstimate=null;a.eqData=[];a.eqData.left=[];a.eqData.right=[];a.failures=0;a.isBuffering=!1;a.instanceOptions={};a.instanceCount=0;a.loaded=!1;a.metadata={};a.readyState=0;a.muted=!1;a.paused=!1;a.peakData={left:0,right:0};a.waveformData={left:[],right:[]};a.playState=0;a.position=null};d();this._onTimer=function(b){var c,d=!1,e={};if(a._hasTimer||b){if(a._a&&(b||(0f.duration?a.duration:f.duration:parseInt(a.bytesTotal/a.bytesLoaded*a.duration,10),void 0===a.durationEstimate)a.durationEstimate=a.duration;3!==a.readyState&&f.whileloading&&f.whileloading.apply(a)};this._whileplaying=function(b,c,d,e,f){var g=a._iO;if(isNaN(b)|| +null===b)return!1;a.position=b;a._processOnPosition();if(!a.isHTML5&&8m)c._wD(q("needfl9")),c.flashVersion=m=9;c.version=c.versionNumber+(c.html5Only?" (HTML5-only mode)":9===m?" (AS3/Flash 9)":" (AS2/Flash 8)");8'}if(P&&Q)return!1;if(c.html5Only)return qa(),d(),c.oMC=u(c.movieID),X(),Q=P=!0,!1;var e=a||c.url,i=c.altURL||e,g;g=ba();var j,m,k=L(),l,n=null,n=(n=h.getElementsByTagName("html")[0])&&n.dir&&n.dir.match(/rtl/i),b="undefined"===typeof b?c.id:b;qa();c.url=Ia(N?e:i);a=c.url;c.wmode=!c.wmode&&c.useHighPerformance?"transparent":c.wmode;if(null!==c.wmode&&(p.match(/msie 8/i)||!D&&!c.useHighPerformance)&&navigator.platform.match(/win32|win64/i))o("spcWmode"), +c.wmode=null;g={name:b,id:b,src:a,width:"auto",height:"auto",quality:"high",allowScriptAccess:c.allowScriptAccess,bgcolor:c.bgColor,pluginspage:Va+"www.macromedia.com/go/getflashplayer",title:"JS/Flash audio component (SoundManager 2)",type:"application/x-shockwave-flash",wmode:c.wmode,hasPriority:"true"};if(c.debugFlash)g.FlashVars="debug=1";c.wmode||delete g.wmode;if(D)e=h.createElement("div"),m=['',f("movie",a),f("AllowScriptAccess",c.allowScriptAccess),f("quality",g.quality),c.wmode?f("wmode",c.wmode):"",f("bgcolor",c.bgColor),f("hasPriority","true"),c.debugFlash?f("FlashVars",g.FlashVars):"",""].join("");else for(j in e=h.createElement("embed"),g)g.hasOwnProperty(j)&&e.setAttribute(j,g[j]);ta();k=L();if(g=ba())if(c.oMC=u(c.movieID)||h.createElement("div"), +c.oMC.id){l=c.oMC.className;c.oMC.className=(l?l+" ":"movieContainer")+(k?" "+k:"");c.oMC.appendChild(e);if(D)j=c.oMC.appendChild(h.createElement("div")),j.className="sm2-object-box",j.innerHTML=m;Q=!0}else{c.oMC.id=c.movieID;c.oMC.className="movieContainer "+k;j=k=null;if(!c.useFlashBlock)if(c.useHighPerformance)k={position:"fixed",width:"8px",height:"8px",bottom:"0px",left:"0px",overflow:"hidden"};else if(k={position:"absolute",width:"6px",height:"6px",top:"-9999px",left:"-9999px"},n)k.left=Math.abs(parseInt(k.left, +10))+"px";if(cb)c.oMC.style.zIndex=1E4;if(!c.debugFlash)for(l in k)k.hasOwnProperty(l)&&(c.oMC.style[l]=k[l]);try{D||c.oMC.appendChild(e);g.appendChild(c.oMC);if(D)j=c.oMC.appendChild(h.createElement("div")),j.className="sm2-object-box",j.innerHTML=m;Q=!0}catch(r){throw Error(q("domError")+" \n"+r.toString());}}P=!0;d();c._wD("soundManager::createMovie(): Trying to load "+a+(!N&&c.altURL?" (alternate URL)":""),1);return!0};aa=function(){if(c.html5Only)return ca(),!1;if(i)return!1;i=c.getMovie(c.id); +if(!i)S?(D?c.oMC.innerHTML=ua:c.oMC.appendChild(S),S=null,P=!0):ca(c.id,c.url),i=c.getMovie(c.id);i&&o("waitEI");c.oninitmovie instanceof Function&&setTimeout(c.oninitmovie,1);return!0};Z=function(){setTimeout(Fa,1E3)};Fa=function(){if(ga)return!1;ga=!0;r.remove(j,"load",Z);if(M&&!Da)return o("waitFocus"),!1;var b;n||(b=c.getMoviePercent(),c._wD(q("waitImpatient",100===b?" (SWF loaded)":0=b)return!1;for(;b--;)if(c=t[b],!c.fired&&a.position>=c.position)c.fired=!0,l++,c.method.apply(c.scope,[c.position]);return!0};this._resetOnPosition=function(a){var b,c;b=t.length;if(!b)return!1;for(;b--;)if(c=t[b],c.fired&&a<=c.position)c.fired=!1,l--;return!0};p=function(){var b=a._iO,c=b.from,d=b.to,e,f;f=function(){a.clearOnPosition(d,f);a.stop()};e= +function(){if(null!==d&&!isNaN(d))a.onPosition(d,f)};if(null!==c&&!isNaN(c))b.position=c,b.multiShot=!1,e();return b};j=function(){var b=a._iO.onposition;if(b)for(var c in b)if(b.hasOwnProperty(c))a.onPosition(parseInt(c,10),b[c])};n=function(){var b=a._iO.onposition;if(b)for(var c in b)b.hasOwnProperty(c)&&a.clearOnPosition(parseInt(c,10))};z=function(){a.isHTML5&&Fa(a)};g=function(){a.isHTML5&&Ga(a)};e=function(){t=[];l=0;k=!1;a._hasTimer=null;a._a=null;a._html5_canplay=!1;a.bytesLoaded=null;a.bytesTotal= +null;a.duration=a._iO&&a._iO.duration?a._iO.duration:null;a.durationEstimate=null;a.eqData=[];a.eqData.left=[];a.eqData.right=[];a.failures=0;a.isBuffering=!1;a.instanceOptions={};a.instanceCount=0;a.loaded=!1;a.metadata={};a.readyState=0;a.muted=!1;a.paused=!1;a.peakData={left:0,right:0};a.waveformData={left:[],right:[]};a.playState=0;a.position=null};e();this._onTimer=function(b){var c,d=!1,e={};if(a._hasTimer||b){if(a._a&&(b||(0f.duration?a.duration:f.duration:parseInt(a.bytesTotal/a.bytesLoaded*a.duration,10),void 0===a.durationEstimate)a.durationEstimate=a.duration;3!==a.readyState&&f.whileloading&&f.whileloading.apply(a)};this._whileplaying=function(b,c,d,e,f){var g=a._iO;if(isNaN(b)||null===b)return!1;a.position=b;a._processOnPosition();if(!a.isHTML5&&8i)c.flashVersion=i=9;c.version=c.versionNumber+(c.html5Only?" (HTML5-only mode)":9===i?" (AS3/Flash 9)":" (AS2/Flash 8)");8'}if(K&&L)return!1;if(c.html5Only)return ka(),c.oMC=S(c.movieID),T(),L=K=!0,!1;var f=a||c.url,d=c.altURL||f,g;g=na();var h,j,i=H(),l,m=null,m=(m=k.getElementsByTagName("html")[0])&&m.dir&&m.dir.match(/rtl/i),b="undefined"===typeof b?c.id:b;ka();c.url=Ea(za?f:d);a=c.url;c.wmode=!c.wmode&&c.useHighPerformance?"transparent": +c.wmode;if(null!==c.wmode&&(p.match(/msie 8/i)||!y&&!c.useHighPerformance)&&navigator.platform.match(/win32|win64/i))c.wmode=null;g={name:b,id:b,src:a,width:"auto",height:"auto",quality:"high",allowScriptAccess:c.allowScriptAccess,bgcolor:c.bgColor,pluginspage:Oa+"www.macromedia.com/go/getflashplayer",title:"JS/Flash audio component (SoundManager 2)",type:"application/x-shockwave-flash",wmode:c.wmode,hasPriority:"true"};if(c.debugFlash)g.FlashVars="debug=1";c.wmode||delete g.wmode;if(y)f=k.createElement("div"), +j=['',e("movie",a),e("AllowScriptAccess",c.allowScriptAccess),e("quality",g.quality),c.wmode?e("wmode",c.wmode):"",e("bgcolor",c.bgColor),e("hasPriority","true"),c.debugFlash?e("FlashVars",g.FlashVars):"",""].join("");else for(h in f= +k.createElement("embed"),g)g.hasOwnProperty(h)&&f.setAttribute(h,g[h]);oa();i=H();if(g=na())if(c.oMC=S(c.movieID)||k.createElement("div"),c.oMC.id){l=c.oMC.className;c.oMC.className=(l?l+" ":"movieContainer")+(i?" "+i:"");c.oMC.appendChild(f);if(y)h=c.oMC.appendChild(k.createElement("div")),h.className="sm2-object-box",h.innerHTML=j;L=!0}else{c.oMC.id=c.movieID;c.oMC.className="movieContainer "+i;h=i=null;if(!c.useFlashBlock)if(c.useHighPerformance)i={position:"fixed",width:"8px",height:"8px",bottom:"0px", +left:"0px",overflow:"hidden"};else if(i={position:"absolute",width:"6px",height:"6px",top:"-9999px",left:"-9999px"},m)i.left=Math.abs(parseInt(i.left,10))+"px";if(Ua)c.oMC.style.zIndex=1E4;if(!c.debugFlash)for(l in i)i.hasOwnProperty(l)&&(c.oMC.style[l]=i[l]);try{y||c.oMC.appendChild(f);g.appendChild(c.oMC);if(y)h=c.oMC.appendChild(k.createElement("div")),h.className="sm2-object-box",h.innerHTML=j;L=!0}catch(n){throw Error(G("domError")+" \n"+n.toString());}}return K=!0};V=function(){if(c.html5Only)return W(), +!1;if(h)return!1;h=c.getMovie(c.id);if(!h)N?(y?c.oMC.innerHTML=pa:c.oMC.appendChild(N),N=null,K=!0):W(c.id,c.url),h=c.getMovie(c.id);c.oninitmovie instanceof Function&&setTimeout(c.oninitmovie,1);return!0};U=function(){setTimeout(Ba,1E3)};Ba=function(){if($)return!1;$=!0;n.remove(j,"load",U);if(I&&!ya)return!1;var b;m||(b=c.getMoviePercent());setTimeout(function(){b=c.getMoviePercent();!m&&Ma&&(null===b?c.useFlashBlock||0===c.flashLoadTimeout?c.useFlashBlock&&qa():X(!0):0!==c.flashLoadTimeout&&X(!0))}, +c.flashLoadTimeout)};A=function(){function b(){n.remove(j,"focus",A);n.remove(j,"load",A)}if(ya||!I)return b(),!0;ya=Ma=!0;Q&&I&&n.remove(j,"mousemove",A);$=!1;b();return!0};La=function(){var b,a=[];if(c.useHTML5Audio&&c.hasHTML5)for(b in c.audioFormats)c.audioFormats.hasOwnProperty(b)&&a.push(b+": "+c.html5[b]+(!c.html5[b]&&r&&c.flash[b]?" (using flash)":c.preferFlash&&c.flash[b]&&r?" (preferring flash)":!c.html5[b]?" ("+(c.audioFormats[b].required?"required, ":"")+"and no flash support)":""))}; +M=function(b){if(m)return!1;if(c.html5Only)return m=!0,D(),!0;var a;if(!c.useFlashBlock||!c.flashLoadTimeout||c.getMoviePercent())m=!0,w&&(a={type:!r&&s?"NO_FLASH":"INIT_TIMEOUT"});if(w||b){if(c.useFlashBlock&&c.oMC)c.oMC.className=H()+" "+(null===c.getMoviePercent()?"swf_timedout":"swf_error");C({type:"ontimeout",error:a});F(a);return!1}if(c.waitForWindowLoad&&!ia)return n.add(j,"load",D),!1;D();return!0};T=function(){if(m)return!1;if(c.html5Only){if(!m)n.remove(j,"load",c.beginDelayedInit),c.enabled= +!0,M();return!0}V();try{h._externalInterfaceTest(!1),Ca(!0,c.flashPollingInterval||(c.useHighPerformance?10:50)),c.debugMode||h._disableDebug(),c.enabled=!0,c.html5Only||n.add(j,"unload",ha)}catch(b){return F({type:"JS_TO_FLASH_EXCEPTION",fatal:!0}),X(!0),M(),!1}M();n.remove(j,"load",c.beginDelayedInit);return!0};E=function(){if(ma)return!1;ma=!0;oa();if(!r&&c.hasHTML5)c.useHTML5Audio=!0,c.preferFlash=!1;Ja();c.html5.usingFlash=Ia();s=c.html5.usingFlash;La();if(!r&&s)c.flashLoadTimeout=1;k.removeEventListener&& +k.removeEventListener("DOMContentLoaded",E,!1);V();return!0};ua=function(){"complete"===k.readyState&&(E(),k.detachEvent("onreadystatechange",ua));return!0};la=function(){ia=!0;n.remove(j,"load",la)};da();n.add(j,"focus",A);n.add(j,"load",A);n.add(j,"load",U);n.add(j,"load",la);Q&&I&&n.add(j,"mousemove",A);k.addEventListener?k.addEventListener("DOMContentLoaded",E,!1):k.attachEvent?k.attachEvent("onreadystatechange",ua):F({type:"NO_DOM2_EVENTS",fatal:!0});"complete"===k.readyState&&setTimeout(E,100)} +var ea=null;if("undefined"===typeof SM2_DEFER||!SM2_DEFER)ea=new R;J.SoundManager=R;J.soundManager=ea})(window); \ No newline at end of file diff --git a/inc/SoundManager2/script/soundmanager2-nodebug.js b/inc/SoundManager2/script/soundmanager2-nodebug.js new file mode 100755 index 0000000..ba81243 --- /dev/null +++ b/inc/SoundManager2/script/soundmanager2-nodebug.js @@ -0,0 +1,2377 @@ +/** @license + * + * SoundManager 2: JavaScript Sound for the Web + * ---------------------------------------------- + * http://schillmania.com/projects/soundmanager2/ + * + * Copyright (c) 2007, Scott Schiller. All rights reserved. + * Code provided under the BSD License: + * http://schillmania.com/projects/soundmanager2/license.txt + * + * V2.97a.20111220 + */ + +/*global window, SM2_DEFER, sm2Debugger, console, document, navigator, setTimeout, setInterval, clearInterval, Audio */ +/* jslint regexp: true, sloppy: true, white: true, nomen: true, plusplus: true */ + +(function(window) { +var soundManager = null; +function SoundManager(smURL, smID) { + this.flashVersion = 8; + this.debugMode = false; + this.debugFlash = false; + this.useConsole = true; + this.consoleOnly = true; + this.waitForWindowLoad = false; + this.bgColor = '#ffffff'; + this.useHighPerformance = false; + this.flashPollingInterval = null; + this.html5PollingInterval = null; + this.flashLoadTimeout = 1000; + this.wmode = null; + this.allowScriptAccess = 'always'; + this.useFlashBlock = false; + this.useHTML5Audio = true; + this.html5Test = /^(probably|maybe)$/i; + this.preferFlash = true; + this.noSWFCache = false; + this.audioFormats = { + 'mp3': { + 'type': ['audio/mpeg; codecs="mp3"', 'audio/mpeg', 'audio/mp3', 'audio/MPA', 'audio/mpa-robust'], + 'required': true + }, + 'mp4': { + 'related': ['aac','m4a'], + 'type': ['audio/mp4; codecs="mp4a.40.2"', 'audio/aac', 'audio/x-m4a', 'audio/MP4A-LATM', 'audio/mpeg4-generic'], + 'required': false + }, + 'ogg': { + 'type': ['audio/ogg; codecs=vorbis'], + 'required': false + }, + 'wav': { + 'type': ['audio/wav; codecs="1"', 'audio/wav', 'audio/wave', 'audio/x-wav'], + 'required': false + } + }; + this.defaultOptions = { + 'autoLoad': false, + 'autoPlay': false, + 'from': null, + 'loops': 1, + 'onid3': null, + 'onload': null, + 'whileloading': null, + 'onplay': null, + 'onpause': null, + 'onresume': null, + 'whileplaying': null, + 'onposition': null, + 'onstop': null, + 'onfailure': null, + 'onfinish': null, + 'multiShot': true, + 'multiShotEvents': false, + 'position': null, + 'pan': 0, + 'stream': true, + 'to': null, + 'type': null, + 'usePolicyFile': false, + 'volume': 100 + }; + this.flash9Options = { + 'isMovieStar': null, + 'usePeakData': false, + 'useWaveformData': false, + 'useEQData': false, + 'onbufferchange': null, + 'ondataerror': null + }; + this.movieStarOptions = { + 'bufferTime': 3, + 'serverURL': null, + 'onconnect': null, + 'duration': null + }; + this.movieID = 'sm2-container'; + this.id = (smID || 'sm2movie'); + this.debugID = 'soundmanager-debug'; + this.debugURLParam = /([#?&])debug=1/i; + this.versionNumber = 'V2.97a.20111220'; + this.version = null; + this.movieURL = null; + this.url = (smURL || null); + this.altURL = null; + this.swfLoaded = false; + this.enabled = false; + this.oMC = null; + this.sounds = {}; + this.soundIDs = []; + this.muted = false; + this.didFlashBlock = false; + this.filePattern = null; + this.filePatterns = { + 'flash8': /\.mp3(\?.*)?$/i, + 'flash9': /\.mp3(\?.*)?$/i + }; + this.features = { + 'buffering': false, + 'peakData': false, + 'waveformData': false, + 'eqData': false, + 'movieStar': false + }; + this.sandbox = { + }; + this.hasHTML5 = (function() { + try { + return (typeof Audio !== 'undefined' && typeof new Audio().canPlayType !== 'undefined'); + } catch(e) { + return false; + } + }()); + this.html5 = { + 'usingFlash': null + }; + this.flash = {}; + this.html5Only = false; + this.ignoreFlash = false; + var SMSound, + _s = this, _flash = null, _sm = 'soundManager', _smc = _sm+'::', _h5 = 'HTML5::', _id, _ua = navigator.userAgent, _win = window, _wl = _win.location.href.toString(), _doc = document, _doNothing, _init, _fV, _on_queue = [], _debugOpen = true, _debugTS, _didAppend = false, _appendSuccess = false, _didInit = false, _disabled = false, _windowLoaded = false, _wDS, _wdCount = 0, _initComplete, _mixin, _addOnEvent, _processOnEvents, _initUserOnload, _delayWaitForEI, _waitForEI, _setVersionInfo, _handleFocus, _strings, _initMovie, _domContentLoaded, _winOnLoad, _didDCLoaded, _getDocument, _createMovie, _catchError, _setPolling, _initDebug, _debugLevels = ['log', 'info', 'warn', 'error'], _defaultFlashVersion = 8, _disableObject, _failSafely, _normalizeMovieURL, _oRemoved = null, _oRemovedHTML = null, _str, _flashBlockHandler, _getSWFCSS, _swfCSS, _toggleDebug, _loopFix, _policyFix, _complain, _idCheck, _waitingForEI = false, _initPending = false, _smTimer, _onTimer, _startTimer, _stopTimer, _timerExecute, _h5TimerCount = 0, _h5IntervalTimer = null, _parseURL, + _needsFlash = null, _featureCheck, _html5OK, _html5CanPlay, _html5Ext, _html5Unload, _domContentLoadedIE, _testHTML5, _event, _slice = Array.prototype.slice, _useGlobalHTML5Audio = false, _hasFlash, _detectFlash, _badSafariFix, _html5_events, _showSupport, + _is_iDevice = _ua.match(/(ipad|iphone|ipod)/i), _is_firefox = _ua.match(/firefox/i), _is_android = _ua.match(/droid/i), _isIE = _ua.match(/msie/i), _isWebkit = _ua.match(/webkit/i), _isSafari = (_ua.match(/safari/i) && !_ua.match(/chrome/i)), _isOpera = (_ua.match(/opera/i)), + _likesHTML5 = (_ua.match(/(mobile|pre\/|xoom)/i) || _is_iDevice), + _isBadSafari = (!_wl.match(/usehtml5audio/i) && !_wl.match(/sm2\-ignorebadua/i) && _isSafari && !_ua.match(/silk/i) && _ua.match(/OS X 10_6_([3-7])/i)), + _hasConsole = (typeof console !== 'undefined' && typeof console.log !== 'undefined'), _isFocused = (typeof _doc.hasFocus !== 'undefined'?_doc.hasFocus():null), _tryInitOnFocus = (_isSafari && typeof _doc.hasFocus === 'undefined'), _okToDisable = !_tryInitOnFocus, _flashMIME = /(mp3|mp4|mpa)/i, + _emptyURL = 'about:blank', + _overHTTP = (_doc.location?_doc.location.protocol.match(/http/i):null), + _http = (!_overHTTP ? 'http:/'+'/' : ''), + _netStreamMimeTypes = /^\s*audio\/(?:x-)?(?:mpeg4|aac|flv|mov|mp4||m4v|m4a|mp4v|3gp|3g2)\s*(?:$|;)/i, + _netStreamTypes = ['mpeg4', 'aac', 'flv', 'mov', 'mp4', 'm4v', 'f4v', 'm4a', 'mp4v', '3gp', '3g2'], + _netStreamPattern = new RegExp('\\.(' + _netStreamTypes.join('|') + ')(\\?.*)?$', 'i'); + this.mimePattern = /^\s*audio\/(?:x-)?(?:mp(?:eg|3))\s*(?:$|;)/i; + this.useAltURL = !_overHTTP; + this._global_a = null; + _swfCSS = { + 'swfBox': 'sm2-object-box', + 'swfDefault': 'movieContainer', + 'swfError': 'swf_error', + 'swfTimedout': 'swf_timedout', + 'swfLoaded': 'swf_loaded', + 'swfUnblocked': 'swf_unblocked', + 'sm2Debug': 'sm2_debug', + 'highPerf': 'high_performance', + 'flashDebug': 'flash_debug' + }; + if (_likesHTML5) { + _s.useHTML5Audio = true; + _s.preferFlash = false; + if (_is_iDevice) { + _s.ignoreFlash = true; + _useGlobalHTML5Audio = true; + } + } + this.ok = function() { + return (_needsFlash?(_didInit && !_disabled):(_s.useHTML5Audio && _s.hasHTML5)); + }; + this.supported = this.ok; + this.getMovie = function(smID) { + return _id(smID) || _doc[smID] || _win[smID]; + }; + this.createSound = function(oOptions) { + var _cs, _cs_string, + thisOptions = null, oSound = null, _tO = null; + if (!_didInit || !_s.ok()) { + _complain(_cs_string); + return false; + } + if (arguments.length === 2) { + oOptions = { + 'id': arguments[0], + 'url': arguments[1] + }; + } + thisOptions = _mixin(oOptions); + thisOptions.url = _parseURL(thisOptions.url); + _tO = thisOptions; + if (_idCheck(_tO.id, true)) { + return _s.sounds[_tO.id]; + } + function make() { + thisOptions = _loopFix(thisOptions); + _s.sounds[_tO.id] = new SMSound(_tO); + _s.soundIDs.push(_tO.id); + return _s.sounds[_tO.id]; + } + if (_html5OK(_tO)) { + oSound = make(); + oSound._setup_html5(_tO); + } else { + if (_fV > 8) { + if (_tO.isMovieStar === null) { + _tO.isMovieStar = (_tO.serverURL || (_tO.type ? _tO.type.match(_netStreamMimeTypes) : false) || _tO.url.match(_netStreamPattern)); + } + if (_tO.isMovieStar) { + if (_tO.usePeakData) { + _tO.usePeakData = false; + } + } + } + _tO = _policyFix(_tO, _cs); + oSound = make(); + if (_fV === 8) { + _flash._createSound(_tO.id, _tO.loops||1, _tO.usePolicyFile); + } else { + _flash._createSound(_tO.id, _tO.url, _tO.usePeakData, _tO.useWaveformData, _tO.useEQData, _tO.isMovieStar, (_tO.isMovieStar?_tO.bufferTime:false), _tO.loops||1, _tO.serverURL, _tO.duration||null, _tO.autoPlay, true, _tO.autoLoad, _tO.usePolicyFile); + if (!_tO.serverURL) { + oSound.connected = true; + if (_tO.onconnect) { + _tO.onconnect.apply(oSound); + } + } + } + if (!_tO.serverURL && (_tO.autoLoad || _tO.autoPlay)) { + oSound.load(_tO); + } + } + if (!_tO.serverURL && _tO.autoPlay) { + oSound.play(); + } + return oSound; + }; + this.destroySound = function(sID, _bFromSound) { + if (!_idCheck(sID)) { + return false; + } + var oS = _s.sounds[sID], i; + oS._iO = {}; + oS.stop(); + oS.unload(); + for (i = 0; i < _s.soundIDs.length; i++) { + if (_s.soundIDs[i] === sID) { + _s.soundIDs.splice(i, 1); + break; + } + } + if (!_bFromSound) { + oS.destruct(true); + } + oS = null; + delete _s.sounds[sID]; + return true; + }; + this.load = function(sID, oOptions) { + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].load(oOptions); + }; + this.unload = function(sID) { + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].unload(); + }; + this.onPosition = function(sID, nPosition, oMethod, oScope) { + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].onposition(nPosition, oMethod, oScope); + }; + this.onposition = this.onPosition; + this.clearOnPosition = function(sID, nPosition, oMethod) { + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].clearOnPosition(nPosition, oMethod); + }; + this.play = function(sID, oOptions) { + if (!_didInit || !_s.ok()) { + _complain(_sm+'.play(): ' + _str(!_didInit?'notReady':'notOK')); + return false; + } + if (!_idCheck(sID)) { + if (!(oOptions instanceof Object)) { + oOptions = { + url: oOptions + }; + } + if (oOptions && oOptions.url) { + oOptions.id = sID; + return _s.createSound(oOptions).play(); + } else { + return false; + } + } + return _s.sounds[sID].play(oOptions); + }; + this.start = this.play; + this.setPosition = function(sID, nMsecOffset) { + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].setPosition(nMsecOffset); + }; + this.stop = function(sID) { + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].stop(); + }; + this.stopAll = function() { + var oSound; + for (oSound in _s.sounds) { + if (_s.sounds.hasOwnProperty(oSound)) { + _s.sounds[oSound].stop(); + } + } + }; + this.pause = function(sID) { + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].pause(); + }; + this.pauseAll = function() { + var i; + for (i = _s.soundIDs.length; i--;) { + _s.sounds[_s.soundIDs[i]].pause(); + } + }; + this.resume = function(sID) { + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].resume(); + }; + this.resumeAll = function() { + var i; + for (i = _s.soundIDs.length; i--;) { + _s.sounds[_s.soundIDs[i]].resume(); + } + }; + this.togglePause = function(sID) { + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].togglePause(); + }; + this.setPan = function(sID, nPan) { + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].setPan(nPan); + }; + this.setVolume = function(sID, nVol) { + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].setVolume(nVol); + }; + this.mute = function(sID) { + var i = 0; + if (typeof sID !== 'string') { + sID = null; + } + if (!sID) { + for (i = _s.soundIDs.length; i--;) { + _s.sounds[_s.soundIDs[i]].mute(); + } + _s.muted = true; + } else { + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].mute(); + } + return true; + }; + this.muteAll = function() { + _s.mute(); + }; + this.unmute = function(sID) { + var i; + if (typeof sID !== 'string') { + sID = null; + } + if (!sID) { + for (i = _s.soundIDs.length; i--;) { + _s.sounds[_s.soundIDs[i]].unmute(); + } + _s.muted = false; + } else { + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].unmute(); + } + return true; + }; + this.unmuteAll = function() { + _s.unmute(); + }; + this.toggleMute = function(sID) { + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].toggleMute(); + }; + this.getMemoryUse = function() { + var ram = 0; + if (_flash && _fV !== 8) { + ram = parseInt(_flash._getMemoryUse(), 10); + } + return ram; + }; + this.disable = function(bNoDisable) { + var i; + if (typeof bNoDisable === 'undefined') { + bNoDisable = false; + } + if (_disabled) { + return false; + } + _disabled = true; + for (i = _s.soundIDs.length; i--;) { + _disableObject(_s.sounds[_s.soundIDs[i]]); + } + _initComplete(bNoDisable); + _event.remove(_win, 'load', _initUserOnload); + return true; + }; + this.canPlayMIME = function(sMIME) { + var result; + if (_s.hasHTML5) { + result = _html5CanPlay({type:sMIME}); + } + if (!_needsFlash || result) { + return result; + } else { + return (sMIME ? !!((_fV > 8 ? sMIME.match(_netStreamMimeTypes) : null) || sMIME.match(_s.mimePattern)) : null); + } + }; + this.canPlayURL = function(sURL) { + var result; + if (_s.hasHTML5) { + result = _html5CanPlay({url: sURL}); + } + if (!_needsFlash || result) { + return result; + } else { + return (sURL ? !!(sURL.match(_s.filePattern)) : null); + } + }; + this.canPlayLink = function(oLink) { + if (typeof oLink.type !== 'undefined' && oLink.type) { + if (_s.canPlayMIME(oLink.type)) { + return true; + } + } + return _s.canPlayURL(oLink.href); + }; + this.getSoundById = function(sID, _suppressDebug) { + if (!sID) { + throw new Error(_sm+'.getSoundById(): sID is null/undefined'); + } + var result = _s.sounds[sID]; + return result; + }; + this.onready = function(oMethod, oScope) { + var sType = 'onready'; + if (oMethod && oMethod instanceof Function) { + if (!oScope) { + oScope = _win; + } + _addOnEvent(sType, oMethod, oScope); + _processOnEvents(); + return true; + } else { + throw _str('needFunction', sType); + } + }; + this.ontimeout = function(oMethod, oScope) { + var sType = 'ontimeout'; + if (oMethod && oMethod instanceof Function) { + if (!oScope) { + oScope = _win; + } + _addOnEvent(sType, oMethod, oScope); + _processOnEvents({type:sType}); + return true; + } else { + throw _str('needFunction', sType); + } + }; + this._writeDebug = function(sText, sType, _bTimestamp) { + return true; + }; + this._wD = this._writeDebug; + this._debug = function() { + }; + this.reboot = function() { + var i, j; + for (i = _s.soundIDs.length; i--;) { + _s.sounds[_s.soundIDs[i]].destruct(); + } + try { + if (_isIE) { + _oRemovedHTML = _flash.innerHTML; + } + _oRemoved = _flash.parentNode.removeChild(_flash); + } catch(e) { + } + _oRemovedHTML = _oRemoved = _needsFlash = null; + _s.enabled = _didDCLoaded = _didInit = _waitingForEI = _initPending = _didAppend = _appendSuccess = _disabled = _s.swfLoaded = false; + _s.soundIDs = _s.sounds = []; + _flash = null; + for (i in _on_queue) { + if (_on_queue.hasOwnProperty(i)) { + for (j = _on_queue[i].length; j--;) { + _on_queue[i][j].fired = false; + } + } + } + _win.setTimeout(_s.beginDelayedInit, 20); + }; + this.getMoviePercent = function() { + return (_flash && typeof _flash.PercentLoaded !== 'undefined' ? _flash.PercentLoaded() : null); + }; + this.beginDelayedInit = function() { + _windowLoaded = true; + _domContentLoaded(); + setTimeout(function() { + if (_initPending) { + return false; + } + _createMovie(); + _initMovie(); + _initPending = true; + return true; + }, 20); + _delayWaitForEI(); + }; + this.destruct = function() { + _s.disable(true); + }; + SMSound = function(oOptions) { + var _t = this, _resetProperties, _add_html5_events, _remove_html5_events, _stop_html5_timer, _start_html5_timer, _attachOnPosition, _onplay_called = false, _onPositionItems = [], _onPositionFired = 0, _detachOnPosition, _applyFromTo, _lastURL = null; + var _lastHTML5State = { + duration: null, + time: null + }; + this.sID = oOptions.id; + this.url = oOptions.url; + this.options = _mixin(oOptions); + this.instanceOptions = this.options; + this._iO = this.instanceOptions; + this.pan = this.options.pan; + this.volume = this.options.volume; + this.isHTML5 = false; + this._a = null; + this.id3 = {}; + this._debug = function() { + }; + this.load = function(oOptions) { + var oS = null, _iO; + if (typeof oOptions !== 'undefined') { + _t._iO = _mixin(oOptions, _t.options); + _t.instanceOptions = _t._iO; + } else { + oOptions = _t.options; + _t._iO = oOptions; + _t.instanceOptions = _t._iO; + if (_lastURL && _lastURL !== _t.url) { + _t._iO.url = _t.url; + _t.url = null; + } + } + if (!_t._iO.url) { + _t._iO.url = _t.url; + } + _t._iO.url = _parseURL(_t._iO.url); + if (_t._iO.url === _t.url && _t.readyState !== 0 && _t.readyState !== 2) { + if (_t.readyState === 3 && _t._iO.onload) { + _t._iO.onload.apply(_t, [(!!_t.duration)]); + } + return _t; + } + _iO = _t._iO; + _lastURL = _t.url; + _t.loaded = false; + _t.readyState = 1; + _t.playState = 0; + if (_html5OK(_iO)) { + oS = _t._setup_html5(_iO); + if (!oS._called_load) { + _t._html5_canplay = false; + _t._a.autobuffer = 'auto'; + _t._a.preload = 'auto'; + oS.load(); + oS._called_load = true; + if (_iO.autoPlay) { + _t.play(); + } + } else { + } + } else { + try { + _t.isHTML5 = false; + _t._iO = _policyFix(_loopFix(_iO)); + _iO = _t._iO; + if (_fV === 8) { + _flash._load(_t.sID, _iO.url, _iO.stream, _iO.autoPlay, (_iO.whileloading?1:0), _iO.loops||1, _iO.usePolicyFile); + } else { + _flash._load(_t.sID, _iO.url, !!(_iO.stream), !!(_iO.autoPlay), _iO.loops||1, !!(_iO.autoLoad), _iO.usePolicyFile); + } + } catch(e) { + _catchError({type:'SMSOUND_LOAD_JS_EXCEPTION', fatal:true}); + } + } + return _t; + }; + this.unload = function() { + if (_t.readyState !== 0) { + if (!_t.isHTML5) { + if (_fV === 8) { + _flash._unload(_t.sID, _emptyURL); + } else { + _flash._unload(_t.sID); + } + } else { + _stop_html5_timer(); + if (_t._a) { + _t._a.pause(); + _html5Unload(_t._a); + } + } + _resetProperties(); + } + return _t; + }; + this.destruct = function(_bFromSM) { + if (!_t.isHTML5) { + _t._iO.onfailure = null; + _flash._destroySound(_t.sID); + } else { + _stop_html5_timer(); + if (_t._a) { + _t._a.pause(); + _html5Unload(_t._a); + if (!_useGlobalHTML5Audio) { + _remove_html5_events(); + } + _t._a._t = null; + _t._a = null; + } + } + if (!_bFromSM) { + _s.destroySound(_t.sID, true); + } + }; + this.play = function(oOptions, _updatePlayState) { + var fN, allowMulti, a, onready; + _updatePlayState = _updatePlayState === undefined ? true : _updatePlayState; + if (!oOptions) { + oOptions = {}; + } + _t._iO = _mixin(oOptions, _t._iO); + _t._iO = _mixin(_t._iO, _t.options); + _t._iO.url = _parseURL(_t._iO.url); + _t.instanceOptions = _t._iO; + if (_t._iO.serverURL && !_t.connected) { + if (!_t.getAutoPlay()) { + _t.setAutoPlay(true); + } + return _t; + } + if (_html5OK(_t._iO)) { + _t._setup_html5(_t._iO); + _start_html5_timer(); + } + if (_t.playState === 1 && !_t.paused) { + allowMulti = _t._iO.multiShot; + if (!allowMulti) { + return _t; + } else { + } + } + if (!_t.loaded) { + if (_t.readyState === 0) { + if (!_t.isHTML5) { + _t._iO.autoPlay = true; + } + _t.load(_t._iO); + } else if (_t.readyState === 2) { + return _t; + } else { + } + } else { + } + if (!_t.isHTML5 && _fV === 9 && _t.position > 0 && _t.position === _t.duration) { + oOptions.position = 0; + } + if (_t.paused && _t.position && _t.position > 0) { + _t.resume(); + } else { + _t._iO = _mixin(oOptions, _t._iO); + if (_t._iO.from !== null && _t._iO.to !== null && _t.instanceCount === 0 && _t.playState === 0 && !_t._iO.serverURL) { + onready = function() { + _t._iO = _mixin(oOptions, _t._iO); + _t.play(_t._iO); + }; + if (_t.isHTML5 && !_t._html5_canplay) { + _t.load({ + _oncanplay: onready + }); + return false; + } else if (!_t.isHTML5 && !_t.loaded && (!_t.readyState || _t.readyState !== 2)) { + _t.load({ + onload: onready + }); + return false; + } + _t._iO = _applyFromTo(); + } + if (!_t.instanceCount || _t._iO.multiShotEvents || (!_t.isHTML5 && _fV > 8 && !_t.getAutoPlay())) { + _t.instanceCount++; + } + if (_t.playState === 0 && _t._iO.onposition) { + _attachOnPosition(_t); + } + _t.playState = 1; + _t.paused = false; + _t.position = (typeof _t._iO.position !== 'undefined' && !isNaN(_t._iO.position) ? _t._iO.position : 0); + if (!_t.isHTML5) { + _t._iO = _policyFix(_loopFix(_t._iO)); + } + if (_t._iO.onplay && _updatePlayState) { + _t._iO.onplay.apply(_t); + _onplay_called = true; + } + _t.setVolume(_t._iO.volume, true); + _t.setPan(_t._iO.pan, true); + if (!_t.isHTML5) { + _flash._start(_t.sID, _t._iO.loops || 1, (_fV === 9?_t._iO.position:_t._iO.position / 1000)); + } else { + _start_html5_timer(); + a = _t._setup_html5(); + _t.setPosition(_t._iO.position); + a.play(); + } + } + return _t; + }; + this.start = this.play; + this.stop = function(bAll) { + var _iO = _t._iO, _oP; + if (_t.playState === 1) { + _t._onbufferchange(0); + _t._resetOnPosition(0); + _t.paused = false; + if (!_t.isHTML5) { + _t.playState = 0; + } + _detachOnPosition(); + if (_iO.to) { + _t.clearOnPosition(_iO.to); + } + if (!_t.isHTML5) { + _flash._stop(_t.sID, bAll); + if (_iO.serverURL) { + _t.unload(); + } + } else { + if (_t._a) { + _oP = _t.position; + _t.setPosition(0); + _t.position = _oP; + _t._a.pause(); + _t.playState = 0; + _t._onTimer(); + _stop_html5_timer(); + } + } + _t.instanceCount = 0; + _t._iO = {}; + if (_iO.onstop) { + _iO.onstop.apply(_t); + } + } + return _t; + }; + this.setAutoPlay = function(autoPlay) { + _t._iO.autoPlay = autoPlay; + if (!_t.isHTML5) { + _flash._setAutoPlay(_t.sID, autoPlay); + if (autoPlay) { + if (!_t.instanceCount && _t.readyState === 1) { + _t.instanceCount++; + } + } + } + }; + this.getAutoPlay = function() { + return _t._iO.autoPlay; + }; + this.setPosition = function(nMsecOffset) { + if (nMsecOffset === undefined) { + nMsecOffset = 0; + } + var original_pos, + position, position1K, + offset = (_t.isHTML5 ? Math.max(nMsecOffset,0) : Math.min(_t.duration || _t._iO.duration, Math.max(nMsecOffset, 0))); + original_pos = _t.position; + _t.position = offset; + position1K = _t.position/1000; + _t._resetOnPosition(_t.position); + _t._iO.position = offset; + if (!_t.isHTML5) { + position = (_fV === 9 ? _t.position : position1K); + if (_t.readyState && _t.readyState !== 2) { + _flash._setPosition(_t.sID, position, (_t.paused || !_t.playState)); + } + } else if (_t._a) { + if (_t._html5_canplay) { + if (_t._a.currentTime !== position1K) { + try { + _t._a.currentTime = position1K; + if (_t.playState === 0 || _t.paused) { + _t._a.pause(); + } + } catch(e) { + } + } + } else { + } + } + if (_t.isHTML5) { + if (_t.paused) { + _t._onTimer(true); + } + } + return _t; + }; + this.pause = function(_bCallFlash) { + if (_t.paused || (_t.playState === 0 && _t.readyState !== 1)) { + return _t; + } + _t.paused = true; + if (!_t.isHTML5) { + if (_bCallFlash || _bCallFlash === undefined) { + _flash._pause(_t.sID); + } + } else { + _t._setup_html5().pause(); + _stop_html5_timer(); + } + if (_t._iO.onpause) { + _t._iO.onpause.apply(_t); + } + return _t; + }; + this.resume = function() { + var _iO = _t._iO; + if (!_t.paused) { + return _t; + } + _t.paused = false; + _t.playState = 1; + if (!_t.isHTML5) { + if (_iO.isMovieStar && !_iO.serverURL) { + _t.setPosition(_t.position); + } + _flash._pause(_t.sID); + } else { + _t._setup_html5().play(); + _start_html5_timer(); + } + if (_onplay_called && _iO.onplay) { + _iO.onplay.apply(_t); + _onplay_called = true; + } else if (_iO.onresume) { + _iO.onresume.apply(_t); + } + return _t; + }; + this.togglePause = function() { + if (_t.playState === 0) { + _t.play({ + position: (_fV === 9 && !_t.isHTML5 ? _t.position : _t.position / 1000) + }); + return _t; + } + if (_t.paused) { + _t.resume(); + } else { + _t.pause(); + } + return _t; + }; + this.setPan = function(nPan, bInstanceOnly) { + if (typeof nPan === 'undefined') { + nPan = 0; + } + if (typeof bInstanceOnly === 'undefined') { + bInstanceOnly = false; + } + if (!_t.isHTML5) { + _flash._setPan(_t.sID, nPan); + } + _t._iO.pan = nPan; + if (!bInstanceOnly) { + _t.pan = nPan; + _t.options.pan = nPan; + } + return _t; + }; + this.setVolume = function(nVol, _bInstanceOnly) { + if (typeof nVol === 'undefined') { + nVol = 100; + } + if (typeof _bInstanceOnly === 'undefined') { + _bInstanceOnly = false; + } + if (!_t.isHTML5) { + _flash._setVolume(_t.sID, (_s.muted && !_t.muted) || _t.muted?0:nVol); + } else if (_t._a) { + _t._a.volume = Math.max(0, Math.min(1, nVol/100)); + } + _t._iO.volume = nVol; + if (!_bInstanceOnly) { + _t.volume = nVol; + _t.options.volume = nVol; + } + return _t; + }; + this.mute = function() { + _t.muted = true; + if (!_t.isHTML5) { + _flash._setVolume(_t.sID, 0); + } else if (_t._a) { + _t._a.muted = true; + } + return _t; + }; + this.unmute = function() { + _t.muted = false; + var hasIO = typeof _t._iO.volume !== 'undefined'; + if (!_t.isHTML5) { + _flash._setVolume(_t.sID, hasIO?_t._iO.volume:_t.options.volume); + } else if (_t._a) { + _t._a.muted = false; + } + return _t; + }; + this.toggleMute = function() { + return (_t.muted?_t.unmute():_t.mute()); + }; + this.onPosition = function(nPosition, oMethod, oScope) { + _onPositionItems.push({ + position: nPosition, + method: oMethod, + scope: (typeof oScope !== 'undefined' ? oScope : _t), + fired: false + }); + return _t; + }; + this.onposition = this.onPosition; + this.clearOnPosition = function(nPosition, oMethod) { + var i; + nPosition = parseInt(nPosition, 10); + if (isNaN(nPosition)) { + return false; + } + for (i=0; i < _onPositionItems.length; i++) { + if (nPosition === _onPositionItems[i].position) { + if (!oMethod || (oMethod === _onPositionItems[i].method)) { + if (_onPositionItems[i].fired) { + _onPositionFired--; + } + _onPositionItems.splice(i, 1); + } + } + } + }; + this._processOnPosition = function() { + var i, item, j = _onPositionItems.length; + if (!j || !_t.playState || _onPositionFired >= j) { + return false; + } + for (i=j; i--;) { + item = _onPositionItems[i]; + if (!item.fired && _t.position >= item.position) { + item.fired = true; + _onPositionFired++; + item.method.apply(item.scope, [item.position]); + } + } + return true; + }; + this._resetOnPosition = function(nPosition) { + var i, item, j = _onPositionItems.length; + if (!j) { + return false; + } + for (i=j; i--;) { + item = _onPositionItems[i]; + if (item.fired && nPosition <= item.position) { + item.fired = false; + _onPositionFired--; + } + } + return true; + }; + _applyFromTo = function() { + var _iO = _t._iO, + f = _iO.from, + t = _iO.to, + start, end; + end = function() { + _t.clearOnPosition(t, end); + _t.stop(); + }; + start = function() { + if (t !== null && !isNaN(t)) { + _t.onPosition(t, end); + } + }; + if (f !== null && !isNaN(f)) { + _iO.position = f; + _iO.multiShot = false; + start(); + } + return _iO; + }; + _attachOnPosition = function() { + var op = _t._iO.onposition; + if (op) { + var item; + for (item in op) { + if (op.hasOwnProperty(item)) { + _t.onPosition(parseInt(item, 10), op[item]); + } + } + } + }; + _detachOnPosition = function() { + var op = _t._iO.onposition; + if (op) { + var item; + for (item in op) { + if (op.hasOwnProperty(item)) { + _t.clearOnPosition(parseInt(item, 10)); + } + } + } + }; + _start_html5_timer = function() { + if (_t.isHTML5) { + _startTimer(_t); + } + }; + _stop_html5_timer = function() { + if (_t.isHTML5) { + _stopTimer(_t); + } + }; + _resetProperties = function() { + _onPositionItems = []; + _onPositionFired = 0; + _onplay_called = false; + _t._hasTimer = null; + _t._a = null; + _t._html5_canplay = false; + _t.bytesLoaded = null; + _t.bytesTotal = null; + _t.duration = (_t._iO && _t._iO.duration ? _t._iO.duration : null); + _t.durationEstimate = null; + _t.eqData = []; + _t.eqData.left = []; + _t.eqData.right = []; + _t.failures = 0; + _t.isBuffering = false; + _t.instanceOptions = {}; + _t.instanceCount = 0; + _t.loaded = false; + _t.metadata = {}; + _t.readyState = 0; + _t.muted = false; + _t.paused = false; + _t.peakData = { + left: 0, + right: 0 + }; + _t.waveformData = { + left: [], + right: [] + }; + _t.playState = 0; + _t.position = null; + }; + _resetProperties(); + this._onTimer = function(bForce) { + var duration, isNew = false, time, x = {}; + if (_t._hasTimer || bForce) { + if (_t._a && (bForce || ((_t.playState > 0 || _t.readyState === 1) && !_t.paused))) { + duration = _t._get_html5_duration(); + if (duration !== _lastHTML5State.duration) { + _lastHTML5State.duration = duration; + _t.duration = duration; + isNew = true; + } + _t.durationEstimate = _t.duration; + time = (_t._a.currentTime * 1000 || 0); + if (time !== _lastHTML5State.time) { + _lastHTML5State.time = time; + isNew = true; + } + if (isNew || bForce) { + _t._whileplaying(time,x,x,x,x); + } + return isNew; + } else { + return false; + } + } + }; + this._get_html5_duration = function() { + var _iO = _t._iO, + d = (_t._a ? _t._a.duration*1000 : (_iO ? _iO.duration : undefined)), + result = (d && !isNaN(d) && d !== Infinity ? d : (_iO ? _iO.duration : null)); + return result; + }; + this._setup_html5 = function(oOptions) { + var _iO = _mixin(_t._iO, oOptions), d = decodeURI, + _a = _useGlobalHTML5Audio ? _s._global_a : _t._a, + _dURL = d(_iO.url), + _oldIO = (_a && _a._t ? _a._t.instanceOptions : null); + if (_a) { + if (_a._t) { + if (!_useGlobalHTML5Audio && _dURL === d(_lastURL)) { + return _a; + } else if (_useGlobalHTML5Audio && _oldIO.url === _iO.url && (!_lastURL || (_lastURL === _oldIO.url))) { + return _a; + } + } + if (_useGlobalHTML5Audio && _a._t && _a._t.playState && _iO.url !== _oldIO.url) { + _a._t.stop(); + } + _resetProperties(); + _a.src = _iO.url; + _t.url = _iO.url; + _lastURL = _iO.url; + _a._called_load = false; + } else { + _a = new Audio(_iO.url); + _a._called_load = false; + if (_is_android) { + _a._called_load = true; + } + if (_useGlobalHTML5Audio) { + _s._global_a = _a; + } + } + _t.isHTML5 = true; + _t._a = _a; + _a._t = _t; + _add_html5_events(); + _a.loop = (_iO.loops>1?'loop':''); + if (_iO.autoLoad || _iO.autoPlay) { + _t.load(); + } else { + _a.autobuffer = false; + _a.preload = 'none'; + } + _a.loop = (_iO.loops > 1 ? 'loop' : ''); + return _a; + }; + _add_html5_events = function() { + if (_t._a._added_events) { + return false; + } + var f; + function add(oEvt, oFn, bCapture) { + return _t._a ? _t._a.addEventListener(oEvt, oFn, bCapture||false) : null; + } + _t._a._added_events = true; + for (f in _html5_events) { + if (_html5_events.hasOwnProperty(f)) { + add(f, _html5_events[f]); + } + } + return true; + }; + _remove_html5_events = function() { + var f; + function remove(oEvt, oFn, bCapture) { + return (_t._a ? _t._a.removeEventListener(oEvt, oFn, bCapture||false) : null); + } + _t._a._added_events = false; + for (f in _html5_events) { + if (_html5_events.hasOwnProperty(f)) { + remove(f, _html5_events[f]); + } + } + }; + this._onload = function(nSuccess) { + var fN, loadOK = !!(nSuccess); + _t.loaded = loadOK; + _t.readyState = loadOK?3:2; + _t._onbufferchange(0); + if (_t._iO.onload) { + _t._iO.onload.apply(_t, [loadOK]); + } + return true; + }; + this._onbufferchange = function(nIsBuffering) { + if (_t.playState === 0) { + return false; + } + if ((nIsBuffering && _t.isBuffering) || (!nIsBuffering && !_t.isBuffering)) { + return false; + } + _t.isBuffering = (nIsBuffering === 1); + if (_t._iO.onbufferchange) { + _t._iO.onbufferchange.apply(_t); + } + return true; + }; + this._onsuspend = function() { + if (_t._iO.onsuspend) { + _t._iO.onsuspend.apply(_t); + } + return true; + }; + this._onfailure = function(msg, level, code) { + _t.failures++; + if (_t._iO.onfailure && _t.failures === 1) { + _t._iO.onfailure(_t, msg, level, code); + } else { + } + }; + this._onfinish = function() { + var _io_onfinish = _t._iO.onfinish; + _t._onbufferchange(0); + _t._resetOnPosition(0); + if (_t.instanceCount) { + _t.instanceCount--; + if (!_t.instanceCount) { + _detachOnPosition(); + _t.playState = 0; + _t.paused = false; + _t.instanceCount = 0; + _t.instanceOptions = {}; + _t._iO = {}; + _stop_html5_timer(); + } + if (!_t.instanceCount || _t._iO.multiShotEvents) { + if (_io_onfinish) { + _io_onfinish.apply(_t); + } + } + } + }; + this._whileloading = function(nBytesLoaded, nBytesTotal, nDuration, nBufferLength) { + var _iO = _t._iO; + _t.bytesLoaded = nBytesLoaded; + _t.bytesTotal = nBytesTotal; + _t.duration = Math.floor(nDuration); + _t.bufferLength = nBufferLength; + if (!_iO.isMovieStar) { + if (_iO.duration) { + _t.durationEstimate = (_t.duration > _iO.duration) ? _t.duration : _iO.duration; + } else { + _t.durationEstimate = parseInt((_t.bytesTotal / _t.bytesLoaded) * _t.duration, 10); + } + if (_t.durationEstimate === undefined) { + _t.durationEstimate = _t.duration; + } + if (_t.readyState !== 3 && _iO.whileloading) { + _iO.whileloading.apply(_t); + } + } else { + _t.durationEstimate = _t.duration; + if (_t.readyState !== 3 && _iO.whileloading) { + _iO.whileloading.apply(_t); + } + } + }; + this._whileplaying = function(nPosition, oPeakData, oWaveformDataLeft, oWaveformDataRight, oEQData) { + var _iO = _t._iO; + if (isNaN(nPosition) || nPosition === null) { + return false; + } + _t.position = nPosition; + _t._processOnPosition(); + if (!_t.isHTML5 && _fV > 8) { + if (_iO.usePeakData && typeof oPeakData !== 'undefined' && oPeakData) { + _t.peakData = { + left: oPeakData.leftPeak, + right: oPeakData.rightPeak + }; + } + if (_iO.useWaveformData && typeof oWaveformDataLeft !== 'undefined' && oWaveformDataLeft) { + _t.waveformData = { + left: oWaveformDataLeft.split(','), + right: oWaveformDataRight.split(',') + }; + } + if (_iO.useEQData) { + if (typeof oEQData !== 'undefined' && oEQData && oEQData.leftEQ) { + var eqLeft = oEQData.leftEQ.split(','); + _t.eqData = eqLeft; + _t.eqData.left = eqLeft; + if (typeof oEQData.rightEQ !== 'undefined' && oEQData.rightEQ) { + _t.eqData.right = oEQData.rightEQ.split(','); + } + } + } + } + if (_t.playState === 1) { + if (!_t.isHTML5 && _fV === 8 && !_t.position && _t.isBuffering) { + _t._onbufferchange(0); + } + if (_iO.whileplaying) { + _iO.whileplaying.apply(_t); + } + } + return true; + }; + this._onmetadata = function(oMDProps, oMDData) { + var oData = {}, i, j; + for (i = 0, j = oMDProps.length; i < j; i++) { + oData[oMDProps[i]] = oMDData[i]; + } + _t.metadata = oData; + if (_t._iO.onmetadata) { + _t._iO.onmetadata.apply(_t); + } + }; + this._onid3 = function(oID3Props, oID3Data) { + var oData = [], i, j; + for (i = 0, j = oID3Props.length; i < j; i++) { + oData[oID3Props[i]] = oID3Data[i]; + } + _t.id3 = _mixin(_t.id3, oData); + if (_t._iO.onid3) { + _t._iO.onid3.apply(_t); + } + }; + this._onconnect = function(bSuccess) { + bSuccess = (bSuccess === 1); + _t.connected = bSuccess; + if (bSuccess) { + _t.failures = 0; + if (_idCheck(_t.sID)) { + if (_t.getAutoPlay()) { + _t.play(undefined, _t.getAutoPlay()); + } else if (_t._iO.autoLoad) { + _t.load(); + } + } + if (_t._iO.onconnect) { + _t._iO.onconnect.apply(_t, [bSuccess]); + } + } + }; + this._ondataerror = function(sError) { + if (_t.playState > 0) { + if (_t._iO.ondataerror) { + _t._iO.ondataerror.apply(_t); + } + } + }; + }; + _getDocument = function() { + return (_doc.body || _doc._docElement || _doc.getElementsByTagName('div')[0]); + }; + _id = function(sID) { + return _doc.getElementById(sID); + }; + _mixin = function(oMain, oAdd) { + var o1 = {}, i, o2, o; + for (i in oMain) { + if (oMain.hasOwnProperty(i)) { + o1[i] = oMain[i]; + } + } + o2 = (typeof oAdd === 'undefined'?_s.defaultOptions:oAdd); + for (o in o2) { + if (o2.hasOwnProperty(o) && typeof o1[o] === 'undefined') { + o1[o] = o2[o]; + } + } + return o1; + }; + _event = (function() { + var old = (_win.attachEvent), + evt = { + add: (old?'attachEvent':'addEventListener'), + remove: (old?'detachEvent':'removeEventListener') + }; + function getArgs(oArgs) { + var args = _slice.call(oArgs), len = args.length; + if (old) { + args[1] = 'on' + args[1]; + if (len > 3) { + args.pop(); + } + } else if (len === 3) { + args.push(false); + } + return args; + } + function apply(args, sType) { + var element = args.shift(), + method = [evt[sType]]; + if (old) { + element[method](args[0], args[1]); + } else { + element[method].apply(element, args); + } + } + function add() { + apply(getArgs(arguments), 'add'); + } + function remove() { + apply(getArgs(arguments), 'remove'); + } + return { + 'add': add, + 'remove': remove + }; + }()); + function _html5_event(oFn) { + return function(e) { + var t = this._t; + if (!t || !t._a) { + return null; + } else { + return oFn.call(this, e); + } + }; + } + _html5_events = { + abort: _html5_event(function(e) { + }), + canplay: _html5_event(function(e) { + var t = this._t; + if (t._html5_canplay) { + return true; + } + t._html5_canplay = true; + t._onbufferchange(0); + var position1K = (!isNaN(t.position)?t.position/1000:null); + if (t.position && this.currentTime !== position1K) { + try { + this.currentTime = position1K; + } catch(ee) { + } + } + if (t._iO._oncanplay) { + t._iO._oncanplay(); + } + }), + load: _html5_event(function(e) { + var t = this._t; + if (!t.loaded) { + t._onbufferchange(0); + t._whileloading(t.bytesTotal, t.bytesTotal, t._get_html5_duration()); + t._onload(true); + } + }), + emptied: _html5_event(function(e) { + }), + ended: _html5_event(function(e) { + var t = this._t; + t._onfinish(); + }), + error: _html5_event(function(e) { + this._t._onload(false); + }), + loadeddata: _html5_event(function(e) { + var t = this._t, + bytesTotal = t.bytesTotal || 1; + if (!t._loaded && !_isSafari) { + t.duration = t._get_html5_duration(); + t._whileloading(bytesTotal, bytesTotal, t._get_html5_duration()); + t._onload(true); + } + }), + loadedmetadata: _html5_event(function(e) { + }), + loadstart: _html5_event(function(e) { + this._t._onbufferchange(1); + }), + play: _html5_event(function(e) { + this._t._onbufferchange(0); + }), + playing: _html5_event(function(e) { + this._t._onbufferchange(0); + }), + progress: _html5_event(function(e) { + var t = this._t; + if (t.loaded) { + return false; + } + var i, j, str, buffered = 0, + isProgress = (e.type === 'progress'), + ranges = e.target.buffered, + loaded = (e.loaded||0), + total = (e.total||1); + if (ranges && ranges.length) { + for (i=ranges.length; i--;) { + buffered = (ranges.end(i) - ranges.start(i)); + } + loaded = buffered/e.target.duration; + } + if (!isNaN(loaded)) { + t._onbufferchange(0); + t._whileloading(loaded, total, t._get_html5_duration()); + if (loaded && total && loaded === total) { + _html5_events.load.call(this, e); + } + } + }), + ratechange: _html5_event(function(e) { + }), + suspend: _html5_event(function(e) { + var t = this._t; + _html5_events.progress.call(this, e); + t._onsuspend(); + }), + stalled: _html5_event(function(e) { + }), + timeupdate: _html5_event(function(e) { + this._t._onTimer(); + }), + waiting: _html5_event(function(e) { + var t = this._t; + t._onbufferchange(1); + }) + }; + _html5OK = function(iO) { + return (!iO.serverURL && (iO.type?_html5CanPlay({type:iO.type}):_html5CanPlay({url:iO.url})||_s.html5Only)); + }; + _html5Unload = function(oAudio) { + if (oAudio) { + oAudio.src = (_is_firefox ? '' : _emptyURL); + } + }; + _html5CanPlay = function(o) { + if (!_s.useHTML5Audio || !_s.hasHTML5) { + return false; + } + var url = (o.url || null), + mime = (o.type || null), + aF = _s.audioFormats, + result, + offset, + fileExt, + item; + function preferFlashCheck(kind) { + return (_s.preferFlash && _hasFlash && !_s.ignoreFlash && (typeof _s.flash[kind] !== 'undefined' && _s.flash[kind])); + } + if (mime && _s.html5[mime] !== 'undefined') { + return (_s.html5[mime] && !preferFlashCheck(mime)); + } + if (!_html5Ext) { + _html5Ext = []; + for (item in aF) { + if (aF.hasOwnProperty(item)) { + _html5Ext.push(item); + if (aF[item].related) { + _html5Ext = _html5Ext.concat(aF[item].related); + } + } + } + _html5Ext = new RegExp('\\.('+_html5Ext.join('|')+')(\\?.*)?$','i'); + } + fileExt = (url ? url.toLowerCase().match(_html5Ext) : null); + if (!fileExt || !fileExt.length) { + if (!mime) { + return false; + } else { + offset = mime.indexOf(';'); + fileExt = (offset !== -1?mime.substr(0,offset):mime).substr(6); + } + } else { + fileExt = fileExt[1]; + } + if (fileExt && typeof _s.html5[fileExt] !== 'undefined') { + return (_s.html5[fileExt] && !preferFlashCheck(fileExt)); + } else { + mime = 'audio/'+fileExt; + result = _s.html5.canPlayType({type:mime}); + _s.html5[fileExt] = result; + return (result && _s.html5[mime] && !preferFlashCheck(mime)); + } + }; + _testHTML5 = function() { + if (!_s.useHTML5Audio || typeof Audio === 'undefined') { + return false; + } + var a = (typeof Audio !== 'undefined' ? (_isOpera ? new Audio(null) : new Audio()) : null), + item, support = {}, aF, i; + function _cp(m) { + var canPlay, i, j, isOK = false; + if (!a || typeof a.canPlayType !== 'function') { + return false; + } + if (m instanceof Array) { + for (i=0, j=m.length; i 1 && sOpt.stream) { + sOpt.stream = false; + } + return sOpt; + }; + _policyFix = function(sOpt, sPre) { + if (sOpt && !sOpt.usePolicyFile && (sOpt.onid3 || sOpt.usePeakData || sOpt.useWaveformData || sOpt.useEQData)) { + sOpt.usePolicyFile = true; + } + return sOpt; + }; + _complain = function(sMsg) { + }; + _doNothing = function() { + return false; + }; + _disableObject = function(o) { + var oProp; + for (oProp in o) { + if (o.hasOwnProperty(oProp) && typeof o[oProp] === 'function') { + o[oProp] = _doNothing; + } + } + oProp = null; + }; + _failSafely = function(bNoDisable) { + if (typeof bNoDisable === 'undefined') { + bNoDisable = false; + } + if (_disabled || bNoDisable) { + _s.disable(bNoDisable); + } + }; + _normalizeMovieURL = function(smURL) { + var urlParams = null, url; + if (smURL) { + if (smURL.match(/\.swf(\?.*)?$/i)) { + urlParams = smURL.substr(smURL.toLowerCase().lastIndexOf('.swf?') + 4); + if (urlParams) { + return smURL; + } + } else if (smURL.lastIndexOf('/') !== smURL.length - 1) { + smURL += '/'; + } + } + url = (smURL && smURL.lastIndexOf('/') !== - 1 ? smURL.substr(0, smURL.lastIndexOf('/') + 1) : './') + _s.movieURL; + if (_s.noSWFCache) { + url += ('?ts=' + new Date().getTime()); + } + return url; + }; + _setVersionInfo = function() { + _fV = parseInt(_s.flashVersion, 10); + if (_fV !== 8 && _fV !== 9) { + _s.flashVersion = _fV = _defaultFlashVersion; + } + var isDebug = (_s.debugMode || _s.debugFlash?'_debug.swf':'.swf'); + if (_s.useHTML5Audio && !_s.html5Only && _s.audioFormats.mp4.required && _fV < 9) { + _s.flashVersion = _fV = 9; + } + _s.version = _s.versionNumber + (_s.html5Only?' (HTML5-only mode)':(_fV === 9?' (AS3/Flash 9)':' (AS2/Flash 8)')); + if (_fV > 8) { + _s.defaultOptions = _mixin(_s.defaultOptions, _s.flash9Options); + _s.features.buffering = true; + _s.defaultOptions = _mixin(_s.defaultOptions, _s.movieStarOptions); + _s.filePatterns.flash9 = new RegExp('\\.(mp3|' + _netStreamTypes.join('|') + ')(\\?.*)?$', 'i'); + _s.features.movieStar = true; + } else { + _s.features.movieStar = false; + } + _s.filePattern = _s.filePatterns[(_fV !== 8?'flash9':'flash8')]; + _s.movieURL = (_fV === 8?'soundmanager2.swf':'soundmanager2_flash9.swf').replace('.swf', isDebug); + _s.features.peakData = _s.features.waveformData = _s.features.eqData = (_fV > 8); + }; + _setPolling = function(bPolling, bHighPerformance) { + if (!_flash) { + return false; + } + _flash._setPolling(bPolling, bHighPerformance); + }; + _initDebug = function() { + if (_s.debugURLParam.test(_wl)) { + _s.debugMode = true; + } + }; + _idCheck = this.getSoundById; + _getSWFCSS = function() { + var css = []; + if (_s.debugMode) { + css.push(_swfCSS.sm2Debug); + } + if (_s.debugFlash) { + css.push(_swfCSS.flashDebug); + } + if (_s.useHighPerformance) { + css.push(_swfCSS.highPerf); + } + return css.join(' '); + }; + _flashBlockHandler = function() { + var name = _str('fbHandler'), + p = _s.getMoviePercent(), + css = _swfCSS, + error = {type:'FLASHBLOCK'}; + if (_s.html5Only) { + return false; + } + if (!_s.ok()) { + if (_needsFlash) { + _s.oMC.className = _getSWFCSS() + ' ' + css.swfDefault + ' ' + (p === null?css.swfTimedout:css.swfError); + } + _s.didFlashBlock = true; + _processOnEvents({type:'ontimeout', ignoreInit:true, error:error}); + _catchError(error); + } else { + if (_s.oMC) { + _s.oMC.className = [_getSWFCSS(), css.swfDefault, css.swfLoaded + (_s.didFlashBlock?' '+css.swfUnblocked:'')].join(' '); + } + } + }; + _addOnEvent = function(sType, oMethod, oScope) { + if (typeof _on_queue[sType] === 'undefined') { + _on_queue[sType] = []; + } + _on_queue[sType].push({ + 'method': oMethod, + 'scope': (oScope || null), + 'fired': false + }); + }; + _processOnEvents = function(oOptions) { + if (!oOptions) { + oOptions = { + type: 'onready' + }; + } + if (!_didInit && oOptions && !oOptions.ignoreInit) { + return false; + } + if (oOptions.type === 'ontimeout' && _s.ok()) { + return false; + } + var status = { + success: (oOptions && oOptions.ignoreInit?_s.ok():!_disabled) + }, + srcQueue = (oOptions && oOptions.type?_on_queue[oOptions.type]||[]:[]), + queue = [], i, j, + args = [status], + canRetry = (_needsFlash && _s.useFlashBlock && !_s.ok()); + if (oOptions.error) { + args[0].error = oOptions.error; + } + for (i = 0, j = srcQueue.length; i < j; i++) { + if (srcQueue[i].fired !== true) { + queue.push(srcQueue[i]); + } + } + if (queue.length) { + for (i = 0, j = queue.length; i < j; i++) { + if (queue[i].scope) { + queue[i].method.apply(queue[i].scope, args); + } else { + queue[i].method.apply(this, args); + } + if (!canRetry) { + queue[i].fired = true; + } + } + } + return true; + }; + _initUserOnload = function() { + _win.setTimeout(function() { + if (_s.useFlashBlock) { + _flashBlockHandler(); + } + _processOnEvents(); + if (_s.onload instanceof Function) { + _s.onload.apply(_win); + } + if (_s.waitForWindowLoad) { + _event.add(_win, 'load', _initUserOnload); + } + },1); + }; + _detectFlash = function() { + if (_hasFlash !== undefined) { + return _hasFlash; + } + var hasPlugin = false, n = navigator, nP = n.plugins, obj, type, types, AX = _win.ActiveXObject; + if (nP && nP.length) { + type = 'application/x-shockwave-flash'; + types = n.mimeTypes; + if (types && types[type] && types[type].enabledPlugin && types[type].enabledPlugin.description) { + hasPlugin = true; + } + } else if (typeof AX !== 'undefined') { + try { + obj = new AX('ShockwaveFlash.ShockwaveFlash'); + } catch(e) { + } + hasPlugin = (!!obj); + } + _hasFlash = hasPlugin; + return hasPlugin; + }; + _featureCheck = function() { + var needsFlash, item, + isSpecial = (_is_iDevice && !!(_ua.match(/os (1|2|3_0|3_1)/i))); + if (isSpecial) { + _s.hasHTML5 = false; + _s.html5Only = true; + if (_s.oMC) { + _s.oMC.style.display = 'none'; + } + return false; + } + if (_s.useHTML5Audio) { + if (!_s.html5 || !_s.html5.canPlayType) { + _s.hasHTML5 = false; + return true; + } else { + _s.hasHTML5 = true; + } + if (_isBadSafari) { + if (_detectFlash()) { + return true; + } + } + } else { + return true; + } + for (item in _s.audioFormats) { + if (_s.audioFormats.hasOwnProperty(item)) { + if ((_s.audioFormats[item].required && !_s.html5.canPlayType(_s.audioFormats[item].type)) || _s.flash[item] || _s.flash[_s.audioFormats[item].type]) { + needsFlash = true; + } + } + } + if (_s.ignoreFlash) { + needsFlash = false; + } + _s.html5Only = (_s.hasHTML5 && _s.useHTML5Audio && !needsFlash); + return (!_s.html5Only); + }; + _parseURL = function(url) { + var i, j, result = 0; + if (url instanceof Array) { + for (i=0, j=url.length; i'; + } + _setVersionInfo(); + _s.url = _normalizeMovieURL(_overHTTP?remoteURL:localURL); + smURL = _s.url; + _s.wmode = (!_s.wmode && _s.useHighPerformance ? 'transparent' : _s.wmode); + if (_s.wmode !== null && (_ua.match(/msie 8/i) || (!_isIE && !_s.useHighPerformance)) && navigator.platform.match(/win32|win64/i)) { + _s.wmode = null; + } + oEmbed = { + 'name': smID, + 'id': smID, + 'src': smURL, + 'width': side, + 'height': side, + 'quality': 'high', + 'allowScriptAccess': _s.allowScriptAccess, + 'bgcolor': _s.bgColor, + 'pluginspage': _http+'www.macromedia.com/go/getflashplayer', + 'title': swfTitle, + 'type': 'application/x-shockwave-flash', + 'wmode': _s.wmode, + 'hasPriority': 'true' + }; + if (_s.debugFlash) { + oEmbed.FlashVars = 'debug=1'; + } + if (!_s.wmode) { + delete oEmbed.wmode; + } + if (_isIE) { + oMovie = _doc.createElement('div'); + movieHTML = [ + '', + param('movie', smURL), + param('AllowScriptAccess', _s.allowScriptAccess), + param('quality', oEmbed.quality), + (_s.wmode? param('wmode', _s.wmode): ''), + param('bgcolor', _s.bgColor), + param('hasPriority', 'true'), + (_s.debugFlash ? param('FlashVars', oEmbed.FlashVars) : ''), + '' + ].join(''); + } else { + oMovie = _doc.createElement('embed'); + for (tmp in oEmbed) { + if (oEmbed.hasOwnProperty(tmp)) { + oMovie.setAttribute(tmp, oEmbed[tmp]); + } + } + } + _initDebug(); + extraClass = _getSWFCSS(); + oTarget = _getDocument(); + if (oTarget) { + _s.oMC = (_id(_s.movieID) || _doc.createElement('div')); + if (!_s.oMC.id) { + _s.oMC.id = _s.movieID; + _s.oMC.className = _swfCSS.swfDefault + ' ' + extraClass; + s = null; + oEl = null; + if (!_s.useFlashBlock) { + if (_s.useHighPerformance) { + s = { + 'position': 'fixed', + 'width': '8px', + 'height': '8px', + 'bottom': '0px', + 'left': '0px', + 'overflow': 'hidden' + }; + } else { + s = { + 'position': 'absolute', + 'width': '6px', + 'height': '6px', + 'top': '-9999px', + 'left': '-9999px' + }; + if (isRTL) { + s.left = Math.abs(parseInt(s.left,10))+'px'; + } + } + } + if (_isWebkit) { + _s.oMC.style.zIndex = 10000; + } + if (!_s.debugFlash) { + for (x in s) { + if (s.hasOwnProperty(x)) { + _s.oMC.style[x] = s[x]; + } + } + } + try { + if (!_isIE) { + _s.oMC.appendChild(oMovie); + } + oTarget.appendChild(_s.oMC); + if (_isIE) { + oEl = _s.oMC.appendChild(_doc.createElement('div')); + oEl.className = _swfCSS.swfBox; + oEl.innerHTML = movieHTML; + } + _appendSuccess = true; + } catch(e) { + throw new Error(_str('domError')+' \n'+e.toString()); + } + } else { + sClass = _s.oMC.className; + _s.oMC.className = (sClass?sClass+' ':_swfCSS.swfDefault) + (extraClass?' '+extraClass:''); + _s.oMC.appendChild(oMovie); + if (_isIE) { + oEl = _s.oMC.appendChild(_doc.createElement('div')); + oEl.className = _swfCSS.swfBox; + oEl.innerHTML = movieHTML; + } + _appendSuccess = true; + } + } + _didAppend = true; + _initMsg(); + return true; + }; + _initMovie = function() { + if (_s.html5Only) { + _createMovie(); + return false; + } + if (_flash) { + return false; + } + _flash = _s.getMovie(_s.id); + if (!_flash) { + if (!_oRemoved) { + _createMovie(_s.id, _s.url); + } else { + if (!_isIE) { + _s.oMC.appendChild(_oRemoved); + } else { + _s.oMC.innerHTML = _oRemovedHTML; + } + _oRemoved = null; + _didAppend = true; + } + _flash = _s.getMovie(_s.id); + } + if (_s.oninitmovie instanceof Function) { + setTimeout(_s.oninitmovie, 1); + } + return true; + }; + _delayWaitForEI = function() { + setTimeout(_waitForEI, 1000); + }; + _waitForEI = function() { + if (_waitingForEI) { + return false; + } + _waitingForEI = true; + _event.remove(_win, 'load', _delayWaitForEI); + if (_tryInitOnFocus && !_isFocused) { + return false; + } + var p; + if (!_didInit) { + p = _s.getMoviePercent(); + } + setTimeout(function() { + p = _s.getMoviePercent(); + if (!_didInit && _okToDisable) { + if (p === null) { + if (_s.useFlashBlock || _s.flashLoadTimeout === 0) { + if (_s.useFlashBlock) { + _flashBlockHandler(); + } + } else { + _failSafely(true); + } + } else { + if (_s.flashLoadTimeout === 0) { + } else { + _failSafely(true); + } + } + } + }, _s.flashLoadTimeout); + }; + _handleFocus = function() { + function cleanup() { + _event.remove(_win, 'focus', _handleFocus); + _event.remove(_win, 'load', _handleFocus); + } + if (_isFocused || !_tryInitOnFocus) { + cleanup(); + return true; + } + _okToDisable = true; + _isFocused = true; + if (_isSafari && _tryInitOnFocus) { + _event.remove(_win, 'mousemove', _handleFocus); + } + _waitingForEI = false; + cleanup(); + return true; + }; + _showSupport = function() { + var item, tests = []; + if (_s.useHTML5Audio && _s.hasHTML5) { + for (item in _s.audioFormats) { + if (_s.audioFormats.hasOwnProperty(item)) { + tests.push(item + ': ' + _s.html5[item] + (!_s.html5[item] && _hasFlash && _s.flash[item] ? ' (using flash)' : (_s.preferFlash && _s.flash[item] && _hasFlash ? ' (preferring flash)': (!_s.html5[item] ? ' (' + (_s.audioFormats[item].required ? 'required, ':'') + 'and no flash support)' : '')))); + } + } + } + }; + _initComplete = function(bNoDisable) { + if (_didInit) { + return false; + } + if (_s.html5Only) { + _didInit = true; + _initUserOnload(); + return true; + } + var wasTimeout = (_s.useFlashBlock && _s.flashLoadTimeout && !_s.getMoviePercent()), + error; + if (!wasTimeout) { + _didInit = true; + if (_disabled) { + error = {type: (!_hasFlash && _needsFlash ? 'NO_FLASH' : 'INIT_TIMEOUT')}; + } + } + if (_disabled || bNoDisable) { + if (_s.useFlashBlock && _s.oMC) { + _s.oMC.className = _getSWFCSS() + ' ' + (_s.getMoviePercent() === null?_swfCSS.swfTimedout:_swfCSS.swfError); + } + _processOnEvents({type:'ontimeout', error:error}); + _catchError(error); + return false; + } else { + } + if (_s.waitForWindowLoad && !_windowLoaded) { + _event.add(_win, 'load', _initUserOnload); + return false; + } else { + _initUserOnload(); + } + return true; + }; + _init = function() { + if (_didInit) { + return false; + } + function _cleanup() { + _event.remove(_win, 'load', _s.beginDelayedInit); + } + if (_s.html5Only) { + if (!_didInit) { + _cleanup(); + _s.enabled = true; + _initComplete(); + } + return true; + } + _initMovie(); + try { + _flash._externalInterfaceTest(false); + _setPolling(true, (_s.flashPollingInterval || (_s.useHighPerformance ? 10 : 50))); + if (!_s.debugMode) { + _flash._disableDebug(); + } + _s.enabled = true; + if (!_s.html5Only) { + _event.add(_win, 'unload', _doNothing); + } + } catch(e) { + _catchError({type:'JS_TO_FLASH_EXCEPTION', fatal:true}); + _failSafely(true); + _initComplete(); + return false; + } + _initComplete(); + _cleanup(); + return true; + }; + _domContentLoaded = function() { + if (_didDCLoaded) { + return false; + } + _didDCLoaded = true; + _initDebug(); + if (!_hasFlash && _s.hasHTML5) { + _s.useHTML5Audio = true; + _s.preferFlash = false; + } + _testHTML5(); + _s.html5.usingFlash = _featureCheck(); + _needsFlash = _s.html5.usingFlash; + _showSupport(); + if (!_hasFlash && _needsFlash) { + _s.flashLoadTimeout = 1; + } + if (_doc.removeEventListener) { + _doc.removeEventListener('DOMContentLoaded', _domContentLoaded, false); + } + _initMovie(); + return true; + }; + _domContentLoadedIE = function() { + if (_doc.readyState === 'complete') { + _domContentLoaded(); + _doc.detachEvent('onreadystatechange', _domContentLoadedIE); + } + return true; + }; + _winOnLoad = function() { + _windowLoaded = true; + _event.remove(_win, 'load', _winOnLoad); + }; + _detectFlash(); + _event.add(_win, 'focus', _handleFocus); + _event.add(_win, 'load', _handleFocus); + _event.add(_win, 'load', _delayWaitForEI); + _event.add(_win, 'load', _winOnLoad); + if (_isSafari && _tryInitOnFocus) { + _event.add(_win, 'mousemove', _handleFocus); + } + if (_doc.addEventListener) { + _doc.addEventListener('DOMContentLoaded', _domContentLoaded, false); + } else if (_doc.attachEvent) { + _doc.attachEvent('onreadystatechange', _domContentLoadedIE); + } else { + _catchError({type:'NO_DOM2_EVENTS', fatal:true}); + } + if (_doc.readyState === 'complete') { + setTimeout(_domContentLoaded,100); + } +} +// SM2_DEFER details: http://www.schillmania.com/projects/soundmanager2/doc/getstarted/#lazy-loading +if (typeof SM2_DEFER === 'undefined' || !SM2_DEFER) { + soundManager = new SoundManager(); +} +window.SoundManager = SoundManager; +window.soundManager = soundManager; +}(window)); \ No newline at end of file diff --git a/inc/SoundManager2/script/soundmanager2.js b/inc/SoundManager2/script/soundmanager2.js new file mode 100755 index 0000000..4b115c3 --- /dev/null +++ b/inc/SoundManager2/script/soundmanager2.js @@ -0,0 +1,5019 @@ +/** @license + * + * SoundManager 2: JavaScript Sound for the Web + * ---------------------------------------------- + * http://schillmania.com/projects/soundmanager2/ + * + * Copyright (c) 2007, Scott Schiller. All rights reserved. + * Code provided under the BSD License: + * http://schillmania.com/projects/soundmanager2/license.txt + * + * V2.97a.20111220 + */ + +/*global window, SM2_DEFER, sm2Debugger, console, document, navigator, setTimeout, setInterval, clearInterval, Audio */ +/* jslint regexp: true, sloppy: true, white: true, nomen: true, plusplus: true */ + +/** + * About this file + * --------------- + * This is the fully-commented source version of the SoundManager 2 API, + * recommended for use during development and testing. + * + * See soundmanager2-nodebug-jsmin.js for an optimized build (~10KB with gzip.) + * http://schillmania.com/projects/soundmanager2/doc/getstarted/#basic-inclusion + * Alternately, serve this file with gzip for 75% compression savings (~30KB over HTTP.) + * + * You may notice and comments in this source; these are delimiters for + * debug blocks which are removed in the -nodebug builds, further optimizing code size. + * + * Also, as you may note: Whoa, reliable cross-platform/device audio support is hard! ;) + */ + +(function(window) { + +var soundManager = null; + +/** + * The SoundManager constructor. + * + * @constructor + * @param {string} smURL Optional: Path to SWF files + * @param {string} smID Optional: The ID to use for the SWF container element + * @this {SoundManager} + * @return {SoundManager} The new SoundManager instance + */ + +function SoundManager(smURL, smID) { + // Top-level configuration options + + this.flashVersion = 8; // flash build to use (8 or 9.) Some API features require 9. + this.debugMode = true; // enable debugging output (console.log() with HTML fallback) + this.debugFlash = false; // enable debugging output inside SWF, troubleshoot Flash/browser issues + this.useConsole = true; // use console.log() if available (otherwise, writes to #soundmanager-debug element) + this.consoleOnly = true; // if console is being used, do not create/write to #soundmanager-debug + this.waitForWindowLoad = false; // force SM2 to wait for window.onload() before trying to call soundManager.onload() + this.bgColor = '#ffffff'; // SWF background color. N/A when wmode = 'transparent' + this.useHighPerformance = false; // position:fixed flash movie can help increase js/flash speed, minimize lag + this.flashPollingInterval = null; // msec affecting whileplaying/loading callback frequency. If null, default of 50 msec is used. + this.html5PollingInterval = null; // msec affecting whileplaying() for HTML5 audio, excluding mobile devices. If null, native HTML5 update events are used. + this.flashLoadTimeout = 1000; // msec to wait for flash movie to load before failing (0 = infinity) + this.wmode = null; // flash rendering mode - null, 'transparent', or 'opaque' (last two allow z-index to work) + this.allowScriptAccess = 'always'; // for scripting the SWF (object/embed property), 'always' or 'sameDomain' + this.useFlashBlock = false; // *requires flashblock.css, see demos* - allow recovery from flash blockers. Wait indefinitely and apply timeout CSS to SWF, if applicable. + this.useHTML5Audio = true; // use HTML5 Audio() where API is supported (most Safari, Chrome versions), Firefox (no MP3/MP4.) Ideally, transparent vs. Flash API where possible. + this.html5Test = /^(probably|maybe)$/i; // HTML5 Audio() format support test. Use /^probably$/i; if you want to be more conservative. + this.preferFlash = true; // overrides useHTML5audio. if true and flash support present, will try to use flash for MP3/MP4 as needed since HTML5 audio support is still quirky in browsers. + this.noSWFCache = false; // if true, appends ?ts={date} to break aggressive SWF caching. + + this.audioFormats = { + + /** + * determines HTML5 support + flash requirements. + * if no support (via flash and/or HTML5) for a "required" format, SM2 will fail to start. + * flash fallback is used for MP3 or MP4 if HTML5 can't play it (or if preferFlash = true) + * multiple MIME types may be tested while trying to get a positive canPlayType() response. + */ + + 'mp3': { + 'type': ['audio/mpeg; codecs="mp3"', 'audio/mpeg', 'audio/mp3', 'audio/MPA', 'audio/mpa-robust'], + 'required': true + }, + + 'mp4': { + 'related': ['aac','m4a'], // additional formats under the MP4 container + 'type': ['audio/mp4; codecs="mp4a.40.2"', 'audio/aac', 'audio/x-m4a', 'audio/MP4A-LATM', 'audio/mpeg4-generic'], + 'required': false + }, + + 'ogg': { + 'type': ['audio/ogg; codecs=vorbis'], + 'required': false + }, + + 'wav': { + 'type': ['audio/wav; codecs="1"', 'audio/wav', 'audio/wave', 'audio/x-wav'], + 'required': false + } + + }; + + this.defaultOptions = { + + /** + * the default configuration for sound objects made with createSound() and related methods + * eg., volume, auto-load behaviour and so forth + */ + + 'autoLoad': false, // enable automatic loading (otherwise .load() will be called on demand with .play(), the latter being nicer on bandwidth - if you want to .load yourself, you also can) + 'autoPlay': false, // enable playing of file as soon as possible (much faster if "stream" is true) + 'from': null, // position to start playback within a sound (msec), default = beginning + 'loops': 1, // how many times to repeat the sound (position will wrap around to 0, setPosition() will break out of loop when >0) + 'onid3': null, // callback function for "ID3 data is added/available" + 'onload': null, // callback function for "load finished" + 'whileloading': null, // callback function for "download progress update" (X of Y bytes received) + 'onplay': null, // callback for "play" start + 'onpause': null, // callback for "pause" + 'onresume': null, // callback for "resume" (pause toggle) + 'whileplaying': null, // callback during play (position update) + 'onposition': null, // object containing times and function callbacks for positions of interest + 'onstop': null, // callback for "user stop" + 'onfailure': null, // callback function for when playing fails + 'onfinish': null, // callback function for "sound finished playing" + 'multiShot': true, // let sounds "restart" or layer on top of each other when played multiple times, rather than one-shot/one at a time + 'multiShotEvents': false, // fire multiple sound events (currently onfinish() only) when multiShot is enabled + 'position': null, // offset (milliseconds) to seek to within loaded sound data. + 'pan': 0, // "pan" settings, left-to-right, -100 to 100 + 'stream': true, // allows playing before entire file has loaded (recommended) + 'to': null, // position to end playback within a sound (msec), default = end + 'type': null, // MIME-like hint for file pattern / canPlay() tests, eg. audio/mp3 + 'usePolicyFile': false, // enable crossdomain.xml request for audio on remote domains (for ID3/waveform access) + 'volume': 100 // self-explanatory. 0-100, the latter being the max. + + }; + + this.flash9Options = { + + /** + * flash 9-only options, + * merged into defaultOptions if flash 9 is being used + */ + + 'isMovieStar': null, // "MovieStar" MPEG4 audio mode. Null (default) = auto detect MP4, AAC etc. based on URL. true = force on, ignore URL + 'usePeakData': false, // enable left/right channel peak (level) data + 'useWaveformData': false, // enable sound spectrum (raw waveform data) - NOTE: May increase CPU load. + 'useEQData': false, // enable sound EQ (frequency spectrum data) - NOTE: May increase CPU load. + 'onbufferchange': null, // callback for "isBuffering" property change + 'ondataerror': null // callback for waveform/eq data access error (flash playing audio in other tabs/domains) + + }; + + this.movieStarOptions = { + + /** + * flash 9.0r115+ MPEG4 audio options, + * merged into defaultOptions if flash 9+movieStar mode is enabled + */ + + 'bufferTime': 3, // seconds of data to buffer before playback begins (null = flash default of 0.1 seconds - if AAC playback is gappy, try increasing.) + 'serverURL': null, // rtmp: FMS or FMIS server to connect to, required when requesting media via RTMP or one of its variants + 'onconnect': null, // rtmp: callback for connection to flash media server + 'duration': null // rtmp: song duration (msec) + + }; + + // HTML attributes (id + class names) for the SWF container + + this.movieID = 'sm2-container'; + this.id = (smID || 'sm2movie'); + + this.debugID = 'soundmanager-debug'; + this.debugURLParam = /([#?&])debug=1/i; + + // dynamic attributes + + this.versionNumber = 'V2.97a.20111220'; + this.version = null; + this.movieURL = null; + this.url = (smURL || null); + this.altURL = null; + this.swfLoaded = false; + this.enabled = false; + this.oMC = null; + this.sounds = {}; + this.soundIDs = []; + this.muted = false; + this.didFlashBlock = false; + this.filePattern = null; + + this.filePatterns = { + + 'flash8': /\.mp3(\?.*)?$/i, + 'flash9': /\.mp3(\?.*)?$/i + + }; + + // support indicators, set at init + + this.features = { + + 'buffering': false, + 'peakData': false, + 'waveformData': false, + 'eqData': false, + 'movieStar': false + + }; + + // flash sandbox info, used primarily in troubleshooting + + this.sandbox = { + + // + 'type': null, + 'types': { + 'remote': 'remote (domain-based) rules', + 'localWithFile': 'local with file access (no internet access)', + 'localWithNetwork': 'local with network (internet access only, no local access)', + 'localTrusted': 'local, trusted (local+internet access)' + }, + 'description': null, + 'noRemote': null, + 'noLocal': null + // + + }; + + /** + * basic HTML5 Audio() support test + * try...catch because of IE 9 "not implemented" nonsense + * https://github.com/Modernizr/Modernizr/issues/224 + */ + + this.hasHTML5 = (function() { + try { + return (typeof Audio !== 'undefined' && typeof new Audio().canPlayType !== 'undefined'); + } catch(e) { + return false; + } + }()); + + /** + * format support (html5/flash) + * stores canPlayType() results based on audioFormats. + * eg. { mp3: boolean, mp4: boolean } + * treat as read-only. + */ + + this.html5 = { + 'usingFlash': null // set if/when flash fallback is needed + }; + + this.flash = {}; // file type support hash + + this.html5Only = false; // determined at init time + this.ignoreFlash = false; // used for special cases (eg. iPad/iPhone/palm OS?) + + /** + * a few private internals (OK, a lot. :D) + */ + + var SMSound, + _s = this, _flash = null, _sm = 'soundManager', _smc = _sm+'::', _h5 = 'HTML5::', _id, _ua = navigator.userAgent, _win = window, _wl = _win.location.href.toString(), _doc = document, _doNothing, _init, _fV, _on_queue = [], _debugOpen = true, _debugTS, _didAppend = false, _appendSuccess = false, _didInit = false, _disabled = false, _windowLoaded = false, _wDS, _wdCount = 0, _initComplete, _mixin, _addOnEvent, _processOnEvents, _initUserOnload, _delayWaitForEI, _waitForEI, _setVersionInfo, _handleFocus, _strings, _initMovie, _domContentLoaded, _winOnLoad, _didDCLoaded, _getDocument, _createMovie, _catchError, _setPolling, _initDebug, _debugLevels = ['log', 'info', 'warn', 'error'], _defaultFlashVersion = 8, _disableObject, _failSafely, _normalizeMovieURL, _oRemoved = null, _oRemovedHTML = null, _str, _flashBlockHandler, _getSWFCSS, _swfCSS, _toggleDebug, _loopFix, _policyFix, _complain, _idCheck, _waitingForEI = false, _initPending = false, _smTimer, _onTimer, _startTimer, _stopTimer, _timerExecute, _h5TimerCount = 0, _h5IntervalTimer = null, _parseURL, + _needsFlash = null, _featureCheck, _html5OK, _html5CanPlay, _html5Ext, _html5Unload, _domContentLoadedIE, _testHTML5, _event, _slice = Array.prototype.slice, _useGlobalHTML5Audio = false, _hasFlash, _detectFlash, _badSafariFix, _html5_events, _showSupport, + _is_iDevice = _ua.match(/(ipad|iphone|ipod)/i), _is_firefox = _ua.match(/firefox/i), _is_android = _ua.match(/droid/i), _isIE = _ua.match(/msie/i), _isWebkit = _ua.match(/webkit/i), _isSafari = (_ua.match(/safari/i) && !_ua.match(/chrome/i)), _isOpera = (_ua.match(/opera/i)), + _likesHTML5 = (_ua.match(/(mobile|pre\/|xoom)/i) || _is_iDevice), + _isBadSafari = (!_wl.match(/usehtml5audio/i) && !_wl.match(/sm2\-ignorebadua/i) && _isSafari && !_ua.match(/silk/i) && _ua.match(/OS X 10_6_([3-7])/i)), // Safari 4 and 5 (excluding Kindle Fire, "Silk") occasionally fail to load/play HTML5 audio on Snow Leopard 10.6.3 through 10.6.7 due to bug(s) in QuickTime X and/or other underlying frameworks. :/ Confirmed bug. https://bugs.webkit.org/show_bug.cgi?id=32159 + _hasConsole = (typeof console !== 'undefined' && typeof console.log !== 'undefined'), _isFocused = (typeof _doc.hasFocus !== 'undefined'?_doc.hasFocus():null), _tryInitOnFocus = (_isSafari && typeof _doc.hasFocus === 'undefined'), _okToDisable = !_tryInitOnFocus, _flashMIME = /(mp3|mp4|mpa)/i, + _emptyURL = 'about:blank', // safe URL to unload, or load nothing from (flash 8 + most HTML5 UAs) + _overHTTP = (_doc.location?_doc.location.protocol.match(/http/i):null), + _http = (!_overHTTP ? 'http:/'+'/' : ''), + // mp3, mp4, aac etc. + _netStreamMimeTypes = /^\s*audio\/(?:x-)?(?:mpeg4|aac|flv|mov|mp4||m4v|m4a|mp4v|3gp|3g2)\s*(?:$|;)/i, + // Flash v9.0r115+ "moviestar" formats + _netStreamTypes = ['mpeg4', 'aac', 'flv', 'mov', 'mp4', 'm4v', 'f4v', 'm4a', 'mp4v', '3gp', '3g2'], + _netStreamPattern = new RegExp('\\.(' + _netStreamTypes.join('|') + ')(\\?.*)?$', 'i'); + + this.mimePattern = /^\s*audio\/(?:x-)?(?:mp(?:eg|3))\s*(?:$|;)/i; // default mp3 set + + // use altURL if not "online" + this.useAltURL = !_overHTTP; + this._global_a = null; + + _swfCSS = { + + 'swfBox': 'sm2-object-box', + 'swfDefault': 'movieContainer', + 'swfError': 'swf_error', // SWF loaded, but SM2 couldn't start (other error) + 'swfTimedout': 'swf_timedout', + 'swfLoaded': 'swf_loaded', + 'swfUnblocked': 'swf_unblocked', // or loaded OK + 'sm2Debug': 'sm2_debug', + 'highPerf': 'high_performance', + 'flashDebug': 'flash_debug' + + }; + + if (_likesHTML5) { + + // prefer HTML5 for mobile + tablet-like devices, probably more reliable vs. flash at this point. + _s.useHTML5Audio = true; + _s.preferFlash = false; + + if (_is_iDevice) { + // by default, use global feature. iOS onfinish() -> next may fail otherwise. + _s.ignoreFlash = true; + _useGlobalHTML5Audio = true; + } + + } + + /** + * Public SoundManager API + * ----------------------- + */ + + this.ok = function() { + + return (_needsFlash?(_didInit && !_disabled):(_s.useHTML5Audio && _s.hasHTML5)); + + }; + + this.supported = this.ok; // legacy + + this.getMovie = function(smID) { + + // safety net: some old browsers differ on SWF references, possibly related to ExternalInterface / flash version + return _id(smID) || _doc[smID] || _win[smID]; + + }; + + /** + * Creates a SMSound sound object instance. + * + * @param {object} oOptions Sound options (at minimum, id and url are required.) + * @return {object} SMSound The new SMSound object. + */ + + this.createSound = function(oOptions) { + + var _cs, _cs_string, + thisOptions = null, oSound = null, _tO = null; + + // + _cs = _sm+'.createSound(): '; + _cs_string = _cs + _str(!_didInit?'notReady':'notOK'); + // + + if (!_didInit || !_s.ok()) { + _complain(_cs_string); + return false; + } + + if (arguments.length === 2) { + // function overloading in JS! :) ..assume simple createSound(id,url) use case + oOptions = { + 'id': arguments[0], + 'url': arguments[1] + }; + } + + // inherit from defaultOptions + thisOptions = _mixin(oOptions); + + thisOptions.url = _parseURL(thisOptions.url); + + // local shortcut + _tO = thisOptions; + + // + if (_tO.id.toString().charAt(0).match(/^[0-9]$/)) { + _s._wD(_cs + _str('badID', _tO.id), 2); + } + + _s._wD(_cs + _tO.id + ' (' + _tO.url + ')', 1); + // + + if (_idCheck(_tO.id, true)) { + _s._wD(_cs + _tO.id + ' exists', 1); + return _s.sounds[_tO.id]; + } + + function make() { + + thisOptions = _loopFix(thisOptions); + _s.sounds[_tO.id] = new SMSound(_tO); + _s.soundIDs.push(_tO.id); + return _s.sounds[_tO.id]; + + } + + if (_html5OK(_tO)) { + + oSound = make(); + _s._wD('Loading sound '+_tO.id+' via HTML5'); + oSound._setup_html5(_tO); + + } else { + + if (_fV > 8) { + if (_tO.isMovieStar === null) { + // attempt to detect MPEG-4 formats + _tO.isMovieStar = (_tO.serverURL || (_tO.type ? _tO.type.match(_netStreamMimeTypes) : false) || _tO.url.match(_netStreamPattern)); + } + // + if (_tO.isMovieStar) { + _s._wD(_cs + 'using MovieStar handling'); + } + // + if (_tO.isMovieStar) { + if (_tO.usePeakData) { + _wDS('noPeak'); + _tO.usePeakData = false; + } + // + if (_tO.loops > 1) { + _wDS('noNSLoop'); + } + // + } + } + + _tO = _policyFix(_tO, _cs); + oSound = make(); + + if (_fV === 8) { + _flash._createSound(_tO.id, _tO.loops||1, _tO.usePolicyFile); + } else { + _flash._createSound(_tO.id, _tO.url, _tO.usePeakData, _tO.useWaveformData, _tO.useEQData, _tO.isMovieStar, (_tO.isMovieStar?_tO.bufferTime:false), _tO.loops||1, _tO.serverURL, _tO.duration||null, _tO.autoPlay, true, _tO.autoLoad, _tO.usePolicyFile); + if (!_tO.serverURL) { + // We are connected immediately + oSound.connected = true; + if (_tO.onconnect) { + _tO.onconnect.apply(oSound); + } + } + } + + if (!_tO.serverURL && (_tO.autoLoad || _tO.autoPlay)) { + // call load for non-rtmp streams + oSound.load(_tO); + } + + } + + // rtmp will play in onconnect + if (!_tO.serverURL && _tO.autoPlay) { + oSound.play(); + } + + return oSound; + + }; + + /** + * Destroys a SMSound sound object instance. + * + * @param {string} sID The ID of the sound to destroy + */ + + this.destroySound = function(sID, _bFromSound) { + + // explicitly destroy a sound before normal page unload, etc. + + if (!_idCheck(sID)) { + return false; + } + + var oS = _s.sounds[sID], i; + + // Disable all callbacks while the sound is being destroyed + oS._iO = {}; + + oS.stop(); + oS.unload(); + + for (i = 0; i < _s.soundIDs.length; i++) { + if (_s.soundIDs[i] === sID) { + _s.soundIDs.splice(i, 1); + break; + } + } + + if (!_bFromSound) { + // ignore if being called from SMSound instance + oS.destruct(true); + } + + oS = null; + delete _s.sounds[sID]; + + return true; + + }; + + /** + * Calls the load() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @param {object} oOptions Optional: Sound options + */ + + this.load = function(sID, oOptions) { + + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].load(oOptions); + + }; + + /** + * Calls the unload() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + */ + + this.unload = function(sID) { + + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].unload(); + + }; + + /** + * Calls the onPosition() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @param {number} nPosition The position to watch for + * @param {function} oMethod The relevant callback to fire + * @param {object} oScope Optional: The scope to apply the callback to + * @return {SMSound} The SMSound object + */ + + this.onPosition = function(sID, nPosition, oMethod, oScope) { + + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].onposition(nPosition, oMethod, oScope); + + }; + + // legacy/backwards-compability: lower-case method name + this.onposition = this.onPosition; + + /** + * Calls the clearOnPosition() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @param {number} nPosition The position to watch for + * @param {function} oMethod Optional: The relevant callback to fire + * @return {SMSound} The SMSound object + */ + + this.clearOnPosition = function(sID, nPosition, oMethod) { + + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].clearOnPosition(nPosition, oMethod); + + }; + + /** + * Calls the play() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @param {object} oOptions Optional: Sound options + * @return {SMSound} The SMSound object + */ + + this.play = function(sID, oOptions) { + + if (!_didInit || !_s.ok()) { + _complain(_sm+'.play(): ' + _str(!_didInit?'notReady':'notOK')); + return false; + } + + if (!_idCheck(sID)) { + if (!(oOptions instanceof Object)) { + // overloading use case: play('mySound','/path/to/some.mp3'); + oOptions = { + url: oOptions + }; + } + if (oOptions && oOptions.url) { + // overloading use case, create+play: .play('someID',{url:'/path/to.mp3'}); + _s._wD(_sm+'.play(): attempting to create "' + sID + '"', 1); + oOptions.id = sID; + return _s.createSound(oOptions).play(); + } else { + return false; + } + } + + return _s.sounds[sID].play(oOptions); + + }; + + this.start = this.play; // just for convenience + + /** + * Calls the setPosition() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @param {number} nMsecOffset Position (milliseconds) + * @return {SMSound} The SMSound object + */ + + this.setPosition = function(sID, nMsecOffset) { + + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].setPosition(nMsecOffset); + + }; + + /** + * Calls the stop() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @return {SMSound} The SMSound object + */ + + this.stop = function(sID) { + + if (!_idCheck(sID)) { + return false; + } + + _s._wD(_sm+'.stop(' + sID + ')', 1); + return _s.sounds[sID].stop(); + + }; + + /** + * Stops all currently-playing sounds. + */ + + this.stopAll = function() { + + var oSound; + _s._wD(_sm+'.stopAll()', 1); + + for (oSound in _s.sounds) { + if (_s.sounds.hasOwnProperty(oSound)) { + // apply only to sound objects + _s.sounds[oSound].stop(); + } + } + + }; + + /** + * Calls the pause() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @return {SMSound} The SMSound object + */ + + this.pause = function(sID) { + + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].pause(); + + }; + + /** + * Pauses all currently-playing sounds. + */ + + this.pauseAll = function() { + + var i; + for (i = _s.soundIDs.length; i--;) { + _s.sounds[_s.soundIDs[i]].pause(); + } + + }; + + /** + * Calls the resume() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @return {SMSound} The SMSound object + */ + + this.resume = function(sID) { + + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].resume(); + + }; + + /** + * Resumes all currently-paused sounds. + */ + + this.resumeAll = function() { + + var i; + for (i = _s.soundIDs.length; i--;) { + _s.sounds[_s.soundIDs[i]].resume(); + } + + }; + + /** + * Calls the togglePause() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @return {SMSound} The SMSound object + */ + + this.togglePause = function(sID) { + + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].togglePause(); + + }; + + /** + * Calls the setPan() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @param {number} nPan The pan value (-100 to 100) + * @return {SMSound} The SMSound object + */ + + this.setPan = function(sID, nPan) { + + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].setPan(nPan); + + }; + + /** + * Calls the setVolume() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @param {number} nVol The volume value (0 to 100) + * @return {SMSound} The SMSound object + */ + + this.setVolume = function(sID, nVol) { + + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].setVolume(nVol); + + }; + + /** + * Calls the mute() method of either a single SMSound object by ID, or all sound objects. + * + * @param {string} sID Optional: The ID of the sound (if omitted, all sounds will be used.) + */ + + this.mute = function(sID) { + + var i = 0; + + if (typeof sID !== 'string') { + sID = null; + } + + if (!sID) { + _s._wD(_sm+'.mute(): Muting all sounds'); + for (i = _s.soundIDs.length; i--;) { + _s.sounds[_s.soundIDs[i]].mute(); + } + _s.muted = true; + } else { + if (!_idCheck(sID)) { + return false; + } + _s._wD(_sm+'.mute(): Muting "' + sID + '"'); + return _s.sounds[sID].mute(); + } + + return true; + + }; + + /** + * Mutes all sounds. + */ + + this.muteAll = function() { + + _s.mute(); + + }; + + /** + * Calls the unmute() method of either a single SMSound object by ID, or all sound objects. + * + * @param {string} sID Optional: The ID of the sound (if omitted, all sounds will be used.) + */ + + this.unmute = function(sID) { + + var i; + + if (typeof sID !== 'string') { + sID = null; + } + + if (!sID) { + + _s._wD(_sm+'.unmute(): Unmuting all sounds'); + for (i = _s.soundIDs.length; i--;) { + _s.sounds[_s.soundIDs[i]].unmute(); + } + _s.muted = false; + + } else { + + if (!_idCheck(sID)) { + return false; + } + _s._wD(_sm+'.unmute(): Unmuting "' + sID + '"'); + return _s.sounds[sID].unmute(); + + } + + return true; + + }; + + /** + * Unmutes all sounds. + */ + + this.unmuteAll = function() { + + _s.unmute(); + + }; + + /** + * Calls the toggleMute() method of a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @return {SMSound} The SMSound object + */ + + this.toggleMute = function(sID) { + + if (!_idCheck(sID)) { + return false; + } + return _s.sounds[sID].toggleMute(); + + }; + + /** + * Retrieves the memory used by the flash plugin. + * + * @return {number} The amount of memory in use + */ + + this.getMemoryUse = function() { + + // flash-only + var ram = 0; + + if (_flash && _fV !== 8) { + ram = parseInt(_flash._getMemoryUse(), 10); + } + + return ram; + + }; + + /** + * Undocumented: NOPs soundManager and all SMSound objects. + */ + + this.disable = function(bNoDisable) { + + // destroy all functions + var i; + + if (typeof bNoDisable === 'undefined') { + bNoDisable = false; + } + + if (_disabled) { + return false; + } + + _disabled = true; + _wDS('shutdown', 1); + + for (i = _s.soundIDs.length; i--;) { + _disableObject(_s.sounds[_s.soundIDs[i]]); + } + + // fire "complete", despite fail + _initComplete(bNoDisable); + _event.remove(_win, 'load', _initUserOnload); + + return true; + + }; + + /** + * Determines playability of a MIME type, eg. 'audio/mp3'. + */ + + this.canPlayMIME = function(sMIME) { + + var result; + + if (_s.hasHTML5) { + result = _html5CanPlay({type:sMIME}); + } + + if (!_needsFlash || result) { + // no flash, or OK + return result; + } else { + // if flash 9, test netStream (movieStar) types as well. + return (sMIME ? !!((_fV > 8 ? sMIME.match(_netStreamMimeTypes) : null) || sMIME.match(_s.mimePattern)) : null); + } + + }; + + /** + * Determines playability of a URL based on audio support. + * + * @param {string} sURL The URL to test + * @return {boolean} URL playability + */ + + this.canPlayURL = function(sURL) { + + var result; + + if (_s.hasHTML5) { + result = _html5CanPlay({url: sURL}); + } + + if (!_needsFlash || result) { + // no flash, or OK + return result; + } else { + return (sURL ? !!(sURL.match(_s.filePattern)) : null); + } + + }; + + /** + * Determines playability of an HTML DOM <a> object (or similar object literal) based on audio support. + * + * @param {object} oLink an HTML DOM <a> object or object literal including href and/or type attributes + * @return {boolean} URL playability + */ + + this.canPlayLink = function(oLink) { + + if (typeof oLink.type !== 'undefined' && oLink.type) { + if (_s.canPlayMIME(oLink.type)) { + return true; + } + } + + return _s.canPlayURL(oLink.href); + + }; + + /** + * Retrieves a SMSound object by ID. + * + * @param {string} sID The ID of the sound + * @return {SMSound} The SMSound object + */ + + this.getSoundById = function(sID, _suppressDebug) { + + if (!sID) { + throw new Error(_sm+'.getSoundById(): sID is null/undefined'); + } + + var result = _s.sounds[sID]; + + // + if (!result && !_suppressDebug) { + _s._wD('"' + sID + '" is an invalid sound ID.', 2); + } + // + + return result; + + }; + + /** + * Queues a callback for execution when SoundManager has successfully initialized. + * + * @param {function} oMethod The callback method to fire + * @param {object} oScope Optional: The scope to apply to the callback + */ + + this.onready = function(oMethod, oScope) { + + var sType = 'onready'; + + if (oMethod && oMethod instanceof Function) { + + // + if (_didInit) { + _s._wD(_str('queue', sType)); + } + // + + if (!oScope) { + oScope = _win; + } + + _addOnEvent(sType, oMethod, oScope); + _processOnEvents(); + + return true; + + } else { + + throw _str('needFunction', sType); + + } + + }; + + /** + * Queues a callback for execution when SoundManager has failed to initialize. + * + * @param {function} oMethod The callback method to fire + * @param {object} oScope Optional: The scope to apply to the callback + */ + + this.ontimeout = function(oMethod, oScope) { + + var sType = 'ontimeout'; + + if (oMethod && oMethod instanceof Function) { + + // + if (_didInit) { + _s._wD(_str('queue', sType)); + } + // + + if (!oScope) { + oScope = _win; + } + + _addOnEvent(sType, oMethod, oScope); + _processOnEvents({type:sType}); + + return true; + + } else { + + throw _str('needFunction', sType); + + } + + }; + + /** + * Writes console.log()-style debug output to a console or in-browser element. + * Applies when SoundManager.debugMode = true + * + * @param {string} sText The console message + * @param {string} sType Optional: Log type of 'info', 'warn' or 'error' + * @param {object} Optional: The scope to apply to the callback + */ + + this._writeDebug = function(sText, sType, _bTimestamp) { + + // pseudo-private console.log()-style output + // + + var sDID = 'soundmanager-debug', o, oItem, sMethod; + + if (!_s.debugMode) { + return false; + } + + if (typeof _bTimestamp !== 'undefined' && _bTimestamp) { + sText = sText + ' | ' + new Date().getTime(); + } + + if (_hasConsole && _s.useConsole) { + sMethod = _debugLevels[sType]; + if (typeof console[sMethod] !== 'undefined') { + console[sMethod](sText); + } else { + console.log(sText); + } + if (_s.consoleOnly) { + return true; + } + } + + try { + + o = _id(sDID); + + if (!o) { + return false; + } + + oItem = _doc.createElement('div'); + + if (++_wdCount % 2 === 0) { + oItem.className = 'sm2-alt'; + } + + if (typeof sType === 'undefined') { + sType = 0; + } else { + sType = parseInt(sType, 10); + } + + oItem.appendChild(_doc.createTextNode(sText)); + + if (sType) { + if (sType >= 2) { + oItem.style.fontWeight = 'bold'; + } + if (sType === 3) { + oItem.style.color = '#ff3333'; + } + } + + // top-to-bottom + // o.appendChild(oItem); + + // bottom-to-top + o.insertBefore(oItem, o.firstChild); + + } catch(e) { + // oh well + } + + o = null; + // + + return true; + + }; + + // alias + this._wD = this._writeDebug; + + /** + * Provides debug / state information on all SMSound objects. + */ + + this._debug = function() { + + // + var i, j; + _wDS('currentObj', 1); + + for (i = 0, j = _s.soundIDs.length; i < j; i++) { + _s.sounds[_s.soundIDs[i]]._debug(); + } + // + + }; + + /** + * Restarts and re-initializes the SoundManager instance. + */ + + this.reboot = function() { + + // attempt to reset and init SM2 + _s._wD(_sm+'.reboot()'); + + // + if (_s.soundIDs.length) { + _s._wD('Destroying ' + _s.soundIDs.length + ' SMSound objects...'); + } + // + + var i, j; + + for (i = _s.soundIDs.length; i--;) { + _s.sounds[_s.soundIDs[i]].destruct(); + } + + // trash ze flash + + try { + if (_isIE) { + _oRemovedHTML = _flash.innerHTML; + } + _oRemoved = _flash.parentNode.removeChild(_flash); + _s._wD('Flash movie removed.'); + } catch(e) { + // uh-oh. + _wDS('badRemove', 2); + } + + // actually, force recreate of movie. + _oRemovedHTML = _oRemoved = _needsFlash = null; + + _s.enabled = _didDCLoaded = _didInit = _waitingForEI = _initPending = _didAppend = _appendSuccess = _disabled = _s.swfLoaded = false; + _s.soundIDs = _s.sounds = []; + _flash = null; + + for (i in _on_queue) { + if (_on_queue.hasOwnProperty(i)) { + for (j = _on_queue[i].length; j--;) { + _on_queue[i][j].fired = false; + } + } + } + + _s._wD(_sm + ': Rebooting...'); + _win.setTimeout(_s.beginDelayedInit, 20); + + }; + + /** + * Undocumented: Determines the SM2 flash movie's load progress. + * + * @return {number or null} Percent loaded, or if invalid/unsupported, null. + */ + + this.getMoviePercent = function() { + + return (_flash && typeof _flash.PercentLoaded !== 'undefined' ? _flash.PercentLoaded() : null); + + }; + + /** + * Additional helper for manually invoking SM2's init process after DOM Ready / window.onload(). + */ + + this.beginDelayedInit = function() { + + _windowLoaded = true; + _domContentLoaded(); + + setTimeout(function() { + + if (_initPending) { + return false; + } + + _createMovie(); + _initMovie(); + _initPending = true; + + return true; + + }, 20); + + _delayWaitForEI(); + + }; + + /** + * Destroys the SoundManager instance and all SMSound instances. + */ + + this.destruct = function() { + + _s._wD(_sm+'.destruct()'); + _s.disable(true); + + }; + + /** + * SMSound() (sound object) constructor + * ------------------------------------ + * + * @param {object} oOptions Sound options (id and url are required attributes) + * @return {SMSound} The new SMSound object + */ + + SMSound = function(oOptions) { + + var _t = this, _resetProperties, _add_html5_events, _remove_html5_events, _stop_html5_timer, _start_html5_timer, _attachOnPosition, _onplay_called = false, _onPositionItems = [], _onPositionFired = 0, _detachOnPosition, _applyFromTo, _lastURL = null; + + var _lastHTML5State = { + // tracks duration + position (time) + duration: null, + time: null + }; + + this.sID = oOptions.id; + this.url = oOptions.url; + this.options = _mixin(oOptions); + + // per-play-instance-specific options + this.instanceOptions = this.options; + + // short alias + this._iO = this.instanceOptions; + + // assign property defaults + this.pan = this.options.pan; + this.volume = this.options.volume; + this.isHTML5 = false; + this._a = null; + + /** + * SMSound() public methods + * ------------------------ + */ + + this.id3 = {}; + + /** + * Writes SMSound object parameters to debug console + */ + + this._debug = function() { + + // + // pseudo-private console.log()-style output + + if (_s.debugMode) { + + var stuff = null, msg = [], sF, sfBracket, maxLength = 64; + + for (stuff in _t.options) { + if (_t.options[stuff] !== null) { + if (_t.options[stuff] instanceof Function) { + // handle functions specially + sF = _t.options[stuff].toString(); + // normalize spaces + sF = sF.replace(/\s\s+/g, ' '); + sfBracket = sF.indexOf('{'); + msg.push(' ' + stuff + ': {' + sF.substr(sfBracket + 1, (Math.min(Math.max(sF.indexOf('\n') - 1, maxLength), maxLength))).replace(/\n/g, '') + '... }'); + } else { + msg.push(' ' + stuff + ': ' + _t.options[stuff]); + } + } + } + + _s._wD('SMSound() merged options: {\n' + msg.join(', \n') + '\n}'); + + } + // + + }; + + // + this._debug(); + // + + /** + * Begins loading a sound per its *url*. + * + * @param {object} oOptions Optional: Sound options + * @return {SMSound} The SMSound object + */ + + this.load = function(oOptions) { + + var oS = null, _iO; + + if (typeof oOptions !== 'undefined') { + _t._iO = _mixin(oOptions, _t.options); + _t.instanceOptions = _t._iO; + } else { + oOptions = _t.options; + _t._iO = oOptions; + _t.instanceOptions = _t._iO; + if (_lastURL && _lastURL !== _t.url) { + _wDS('manURL'); + _t._iO.url = _t.url; + _t.url = null; + } + } + + if (!_t._iO.url) { + _t._iO.url = _t.url; + } + + _t._iO.url = _parseURL(_t._iO.url); + + _s._wD('SMSound.load(): ' + _t._iO.url, 1); + + if (_t._iO.url === _t.url && _t.readyState !== 0 && _t.readyState !== 2) { + _wDS('onURL', 1); + // if loaded and an onload() exists, fire immediately. + if (_t.readyState === 3 && _t._iO.onload) { + // assume success based on truthy duration. + _t._iO.onload.apply(_t, [(!!_t.duration)]); + } + return _t; + } + + // local shortcut + _iO = _t._iO; + + _lastURL = _t.url; + _t.loaded = false; + _t.readyState = 1; + _t.playState = 0; + + // TODO: If switching from HTML5 -> flash (or vice versa), stop currently-playing audio. + + if (_html5OK(_iO)) { + + oS = _t._setup_html5(_iO); + + if (!oS._called_load) { + + _s._wD(_h5+'load: '+_t.sID); + _t._html5_canplay = false; + + // given explicit load call, try to get whole file. + // early HTML5 implementation (non-standard) + _t._a.autobuffer = 'auto'; + // standard + _t._a.preload = 'auto'; + + oS.load(); + oS._called_load = true; + + if (_iO.autoPlay) { + _t.play(); + } + + } else { + _s._wD(_h5+'ignoring request to load again: '+_t.sID); + } + + } else { + + try { + _t.isHTML5 = false; + _t._iO = _policyFix(_loopFix(_iO)); + // re-assign local shortcut + _iO = _t._iO; + if (_fV === 8) { + _flash._load(_t.sID, _iO.url, _iO.stream, _iO.autoPlay, (_iO.whileloading?1:0), _iO.loops||1, _iO.usePolicyFile); + } else { + _flash._load(_t.sID, _iO.url, !!(_iO.stream), !!(_iO.autoPlay), _iO.loops||1, !!(_iO.autoLoad), _iO.usePolicyFile); + } + } catch(e) { + _wDS('smError', 2); + _debugTS('onload', false); + _catchError({type:'SMSOUND_LOAD_JS_EXCEPTION', fatal:true}); + + } + + } + + return _t; + + }; + + /** + * Unloads a sound, canceling any open HTTP requests. + * + * @return {SMSound} The SMSound object + */ + + this.unload = function() { + + // Flash 8/AS2 can't "close" a stream - fake it by loading an empty URL + // Flash 9/AS3: Close stream, preventing further load + // HTML5: Most UAs will use empty URL + + if (_t.readyState !== 0) { + + _s._wD('SMSound.unload(): "' + _t.sID + '"'); + + if (!_t.isHTML5) { + if (_fV === 8) { + _flash._unload(_t.sID, _emptyURL); + } else { + _flash._unload(_t.sID); + } + } else { + _stop_html5_timer(); + if (_t._a) { + _t._a.pause(); + _html5Unload(_t._a); + } + } + + // reset load/status flags + _resetProperties(); + + } + + return _t; + + }; + + /** + * Unloads and destroys a sound. + */ + + this.destruct = function(_bFromSM) { + + _s._wD('SMSound.destruct(): "' + _t.sID + '"'); + + if (!_t.isHTML5) { + + // kill sound within Flash + // Disable the onfailure handler + _t._iO.onfailure = null; + _flash._destroySound(_t.sID); + + } else { + + _stop_html5_timer(); + + if (_t._a) { + _t._a.pause(); + _html5Unload(_t._a); + if (!_useGlobalHTML5Audio) { + _remove_html5_events(); + } + // break obvious circular reference + _t._a._t = null; + _t._a = null; + } + + } + + if (!_bFromSM) { + // ensure deletion from controller + _s.destroySound(_t.sID, true); + + } + + }; + + /** + * Begins playing a sound. + * + * @param {object} oOptions Optional: Sound options + * @return {SMSound} The SMSound object + */ + + this.play = function(oOptions, _updatePlayState) { + + var fN, allowMulti, a, onready; + + // + fN = 'SMSound.play(): '; + // + + _updatePlayState = _updatePlayState === undefined ? true : _updatePlayState; // default to true + + if (!oOptions) { + oOptions = {}; + } + + _t._iO = _mixin(oOptions, _t._iO); + _t._iO = _mixin(_t._iO, _t.options); + _t._iO.url = _parseURL(_t._iO.url); + _t.instanceOptions = _t._iO; + + // RTMP-only + if (_t._iO.serverURL && !_t.connected) { + if (!_t.getAutoPlay()) { + _s._wD(fN+' Netstream not connected yet - setting autoPlay'); + _t.setAutoPlay(true); + } + // play will be called in _onconnect() + return _t; + } + + if (_html5OK(_t._iO)) { + _t._setup_html5(_t._iO); + _start_html5_timer(); + } + + if (_t.playState === 1 && !_t.paused) { + allowMulti = _t._iO.multiShot; + if (!allowMulti) { + _s._wD(fN + '"' + _t.sID + '" already playing (one-shot)', 1); + return _t; + } else { + _s._wD(fN + '"' + _t.sID + '" already playing (multi-shot)', 1); + } + } + + if (!_t.loaded) { + + if (_t.readyState === 0) { + + _s._wD(fN + 'Attempting to load "' + _t.sID + '"', 1); + + // try to get this sound playing ASAP + if (!_t.isHTML5) { + // assign directly because setAutoPlay() increments the instanceCount + _t._iO.autoPlay = true; + } + + _t.load(_t._iO); + + } else if (_t.readyState === 2) { + + _s._wD(fN + 'Could not load "' + _t.sID + '" - exiting', 2); + return _t; + + } else { + + _s._wD(fN + '"' + _t.sID + '" is loading - attempting to play..', 1); + + } + + } else { + + _s._wD(fN + '"' + _t.sID + '"'); + + } + + if (!_t.isHTML5 && _fV === 9 && _t.position > 0 && _t.position === _t.duration) { + // flash 9 needs a position reset if play() is called while at the end of a sound. + _s._wD(fN + '"' + _t.sID + '": Sound at end, resetting to position:0'); + oOptions.position = 0; + } + + /** + * Streams will pause when their buffer is full if they are being loaded. + * In this case paused is true, but the song hasn't started playing yet. + * If we just call resume() the onplay() callback will never be called. + * So only call resume() if the position is > 0. + * Another reason is because options like volume won't have been applied yet. + */ + + if (_t.paused && _t.position && _t.position > 0) { + + // https://gist.github.com/37b17df75cc4d7a90bf6 + _s._wD(fN + '"' + _t.sID + '" is resuming from paused state',1); + _t.resume(); + + } else { + + _t._iO = _mixin(oOptions, _t._iO); + + // apply from/to parameters, if they exist (and not using RTMP) + if (_t._iO.from !== null && _t._iO.to !== null && _t.instanceCount === 0 && _t.playState === 0 && !_t._iO.serverURL) { + + onready = function() { + // sound "canplay" or onload() + // re-apply from/to to instance options, and start playback + _t._iO = _mixin(oOptions, _t._iO); + _t.play(_t._iO); + }; + + // HTML5 needs to at least have "canplay" fired before seeking. + if (_t.isHTML5 && !_t._html5_canplay) { + + // this hasn't been loaded yet. load it first, and then do this again. + _s._wD(fN+'Beginning load of "'+ _t.sID+'" for from/to case'); + + _t.load({ + _oncanplay: onready + }); + + return false; + + } else if (!_t.isHTML5 && !_t.loaded && (!_t.readyState || _t.readyState !== 2)) { + + // to be safe, preload the whole thing in Flash. + + _s._wD(fN+'Preloading "'+ _t.sID+'" for from/to case'); + + _t.load({ + onload: onready + }); + + return false; + + } + + // otherwise, we're ready to go. re-apply local options, and continue + + _t._iO = _applyFromTo(); + + } + + _s._wD(fN+'"'+ _t.sID+'" is starting to play'); + + if (!_t.instanceCount || _t._iO.multiShotEvents || (!_t.isHTML5 && _fV > 8 && !_t.getAutoPlay())) { + _t.instanceCount++; + } + + // if first play and onposition parameters exist, apply them now + if (_t.playState === 0 && _t._iO.onposition) { + _attachOnPosition(_t); + } + + _t.playState = 1; + _t.paused = false; + + _t.position = (typeof _t._iO.position !== 'undefined' && !isNaN(_t._iO.position) ? _t._iO.position : 0); + + if (!_t.isHTML5) { + _t._iO = _policyFix(_loopFix(_t._iO)); + } + + if (_t._iO.onplay && _updatePlayState) { + _t._iO.onplay.apply(_t); + _onplay_called = true; + } + + _t.setVolume(_t._iO.volume, true); + _t.setPan(_t._iO.pan, true); + + if (!_t.isHTML5) { + + _flash._start(_t.sID, _t._iO.loops || 1, (_fV === 9?_t._iO.position:_t._iO.position / 1000)); + + } else { + + _start_html5_timer(); + a = _t._setup_html5(); + _t.setPosition(_t._iO.position); + a.play(); + + } + + } + + return _t; + + }; + + // just for convenience + this.start = this.play; + + /** + * Stops playing a sound (and optionally, all sounds) + * + * @param {boolean} bAll Optional: Whether to stop all sounds + * @return {SMSound} The SMSound object + */ + + this.stop = function(bAll) { + + var _iO = _t._iO, _oP; + + if (_t.playState === 1) { + + _t._onbufferchange(0); + _t._resetOnPosition(0); + _t.paused = false; + + if (!_t.isHTML5) { + _t.playState = 0; + } + + // remove onPosition listeners, if any + _detachOnPosition(); + + // and "to" position, if set + if (_iO.to) { + _t.clearOnPosition(_iO.to); + } + + if (!_t.isHTML5) { + + _flash._stop(_t.sID, bAll); + + // hack for netStream: just unload + if (_iO.serverURL) { + _t.unload(); + } + + } else { + + if (_t._a) { + + _oP = _t.position; + + // act like Flash, though + _t.setPosition(0); + + // hack: reflect old position for onstop() (also like Flash) + _t.position = _oP; + + // html5 has no stop() + // NOTE: pausing means iOS requires interaction to resume. + _t._a.pause(); + + _t.playState = 0; + + // and update UI + _t._onTimer(); + + _stop_html5_timer(); + + } + + } + + _t.instanceCount = 0; + _t._iO = {}; + + if (_iO.onstop) { + _iO.onstop.apply(_t); + } + + } + + return _t; + + }; + + /** + * Undocumented/internal: Sets autoPlay for RTMP. + * + * @param {boolean} autoPlay state + */ + + this.setAutoPlay = function(autoPlay) { + + _s._wD('sound '+_t.sID+' turned autoplay ' + (autoPlay ? 'on' : 'off')); + _t._iO.autoPlay = autoPlay; + + if (!_t.isHTML5) { + _flash._setAutoPlay(_t.sID, autoPlay); + if (autoPlay) { + // only increment the instanceCount if the sound isn't loaded (TODO: verify RTMP) + if (!_t.instanceCount && _t.readyState === 1) { + _t.instanceCount++; + _s._wD('sound '+_t.sID+' incremented instance count to '+_t.instanceCount); + } + } + } + + }; + + /** + * Undocumented/internal: Returns the autoPlay boolean. + * + * @return {boolean} The current autoPlay value + */ + + this.getAutoPlay = function() { + + return _t._iO.autoPlay; + + }; + + /** + * Sets the position of a sound. + * + * @param {number} nMsecOffset Position (milliseconds) + * @return {SMSound} The SMSound object + */ + + this.setPosition = function(nMsecOffset) { + + if (nMsecOffset === undefined) { + nMsecOffset = 0; + } + + var original_pos, + position, position1K, + // Use the duration from the instance options, if we don't have a track duration yet. + // position >= 0 and <= current available (loaded) duration + offset = (_t.isHTML5 ? Math.max(nMsecOffset,0) : Math.min(_t.duration || _t._iO.duration, Math.max(nMsecOffset, 0))); + + original_pos = _t.position; + _t.position = offset; + position1K = _t.position/1000; + _t._resetOnPosition(_t.position); + _t._iO.position = offset; + + if (!_t.isHTML5) { + + position = (_fV === 9 ? _t.position : position1K); + if (_t.readyState && _t.readyState !== 2) { + // if paused or not playing, will not resume (by playing) + _flash._setPosition(_t.sID, position, (_t.paused || !_t.playState)); + } + + } else if (_t._a) { + + // Set the position in the canplay handler if the sound is not ready yet + if (_t._html5_canplay) { + if (_t._a.currentTime !== position1K) { + /** + * DOM/JS errors/exceptions to watch out for: + * if seek is beyond (loaded?) position, "DOM exception 11" + * "INDEX_SIZE_ERR": DOM exception 1 + */ + _s._wD('setPosition('+position1K+'): setting position'); + try { + _t._a.currentTime = position1K; + if (_t.playState === 0 || _t.paused) { + // allow seek without auto-play/resume + _t._a.pause(); + } + } catch(e) { + _s._wD('setPosition('+position1K+'): setting position failed: '+e.message, 2); + } + } + } else { + _s._wD('setPosition('+position1K+'): delaying, sound not ready'); + } + + } + + if (_t.isHTML5) { + if (_t.paused) { + // if paused, refresh UI right away + // force update + _t._onTimer(true); + } + } + + return _t; + + }; + + /** + * Pauses sound playback. + * + * @return {SMSound} The SMSound object + */ + + this.pause = function(_bCallFlash) { + + if (_t.paused || (_t.playState === 0 && _t.readyState !== 1)) { + return _t; + } + + _s._wD('SMSound.pause()'); + _t.paused = true; + + if (!_t.isHTML5) { + if (_bCallFlash || _bCallFlash === undefined) { + _flash._pause(_t.sID); + } + } else { + _t._setup_html5().pause(); + _stop_html5_timer(); + } + + if (_t._iO.onpause) { + _t._iO.onpause.apply(_t); + } + + return _t; + + }; + + /** + * Resumes sound playback. + * + * @return {SMSound} The SMSound object + */ + + /** + * When auto-loaded streams pause on buffer full they have a playState of 0. + * We need to make sure that the playState is set to 1 when these streams "resume". + * When a paused stream is resumed, we need to trigger the onplay() callback if it + * hasn't been called already. In this case since the sound is being played for the + * first time, I think it's more appropriate to call onplay() rather than onresume(). + */ + + this.resume = function() { + + var _iO = _t._iO; + + if (!_t.paused) { + return _t; + } + + _s._wD('SMSound.resume()'); + _t.paused = false; + _t.playState = 1; + + if (!_t.isHTML5) { + if (_iO.isMovieStar && !_iO.serverURL) { + // Bizarre Webkit bug (Chrome reported via 8tracks.com dudes): AAC content paused for 30+ seconds(?) will not resume without a reposition. + _t.setPosition(_t.position); + } + // flash method is toggle-based (pause/resume) + _flash._pause(_t.sID); + } else { + _t._setup_html5().play(); + _start_html5_timer(); + } + + if (_onplay_called && _iO.onplay) { + _iO.onplay.apply(_t); + _onplay_called = true; + } else if (_iO.onresume) { + _iO.onresume.apply(_t); + } + + return _t; + + }; + + /** + * Toggles sound playback. + * + * @return {SMSound} The SMSound object + */ + + this.togglePause = function() { + + _s._wD('SMSound.togglePause()'); + + if (_t.playState === 0) { + _t.play({ + position: (_fV === 9 && !_t.isHTML5 ? _t.position : _t.position / 1000) + }); + return _t; + } + + if (_t.paused) { + _t.resume(); + } else { + _t.pause(); + } + + return _t; + + }; + + /** + * Sets the panning (L-R) effect. + * + * @param {number} nPan The pan value (-100 to 100) + * @return {SMSound} The SMSound object + */ + + this.setPan = function(nPan, bInstanceOnly) { + + if (typeof nPan === 'undefined') { + nPan = 0; + } + + if (typeof bInstanceOnly === 'undefined') { + bInstanceOnly = false; + } + + if (!_t.isHTML5) { + _flash._setPan(_t.sID, nPan); + } // else { no HTML5 pan? } + + _t._iO.pan = nPan; + + if (!bInstanceOnly) { + _t.pan = nPan; + _t.options.pan = nPan; + } + + return _t; + + }; + + /** + * Sets the volume. + * + * @param {number} nVol The volume value (0 to 100) + * @return {SMSound} The SMSound object + */ + + this.setVolume = function(nVol, _bInstanceOnly) { + + /** + * Note: Setting volume has no effect on iOS "special snowflake" devices. + * Hardware volume control overrides software, and volume + * will always return 1 per Apple docs. (iOS 4 + 5.) + * http://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/HTML-canvas-guide/AddingSoundtoCanvasAnimations/AddingSoundtoCanvasAnimations.html + */ + + if (typeof nVol === 'undefined') { + nVol = 100; + } + + if (typeof _bInstanceOnly === 'undefined') { + _bInstanceOnly = false; + } + + if (!_t.isHTML5) { + _flash._setVolume(_t.sID, (_s.muted && !_t.muted) || _t.muted?0:nVol); + } else if (_t._a) { + // valid range: 0-1 + _t._a.volume = Math.max(0, Math.min(1, nVol/100)); + } + + _t._iO.volume = nVol; + + if (!_bInstanceOnly) { + _t.volume = nVol; + _t.options.volume = nVol; + } + + return _t; + + }; + + /** + * Mutes the sound. + * + * @return {SMSound} The SMSound object + */ + + this.mute = function() { + + _t.muted = true; + + if (!_t.isHTML5) { + _flash._setVolume(_t.sID, 0); + } else if (_t._a) { + _t._a.muted = true; + } + + return _t; + + }; + + /** + * Unmutes the sound. + * + * @return {SMSound} The SMSound object + */ + + this.unmute = function() { + + _t.muted = false; + var hasIO = typeof _t._iO.volume !== 'undefined'; + + if (!_t.isHTML5) { + _flash._setVolume(_t.sID, hasIO?_t._iO.volume:_t.options.volume); + } else if (_t._a) { + _t._a.muted = false; + } + + return _t; + + }; + + /** + * Toggles the muted state of a sound. + * + * @return {SMSound} The SMSound object + */ + + this.toggleMute = function() { + + return (_t.muted?_t.unmute():_t.mute()); + + }; + + /** + * Registers a callback to be fired when a sound reaches a given position during playback. + * + * @param {number} nPosition The position to watch for + * @param {function} oMethod The relevant callback to fire + * @param {object} oScope Optional: The scope to apply the callback to + * @return {SMSound} The SMSound object + */ + + this.onPosition = function(nPosition, oMethod, oScope) { + + // TODO: basic dupe checking? + + _onPositionItems.push({ + position: nPosition, + method: oMethod, + scope: (typeof oScope !== 'undefined' ? oScope : _t), + fired: false + }); + + return _t; + + }; + + // legacy/backwards-compability: lower-case method name + this.onposition = this.onPosition; + + /** + * Removes registered callback(s) from a sound, by position and/or callback. + * + * @param {number} nPosition The position to clear callback(s) for + * @param {function} oMethod Optional: Identify one callback to be removed when multiple listeners exist for one position + * @return {SMSound} The SMSound object + */ + + this.clearOnPosition = function(nPosition, oMethod) { + + var i; + + nPosition = parseInt(nPosition, 10); + + if (isNaN(nPosition)) { + // safety check + return false; + } + + for (i=0; i < _onPositionItems.length; i++) { + + if (nPosition === _onPositionItems[i].position) { + // remove this item if no method was specified, or, if the method matches + if (!oMethod || (oMethod === _onPositionItems[i].method)) { + if (_onPositionItems[i].fired) { + // decrement "fired" counter, too + _onPositionFired--; + } + _onPositionItems.splice(i, 1); + } + } + + } + + }; + + this._processOnPosition = function() { + + var i, item, j = _onPositionItems.length; + + if (!j || !_t.playState || _onPositionFired >= j) { + return false; + } + + for (i=j; i--;) { + item = _onPositionItems[i]; + if (!item.fired && _t.position >= item.position) { + item.fired = true; + _onPositionFired++; + item.method.apply(item.scope, [item.position]); + } + } + + return true; + + }; + + this._resetOnPosition = function(nPosition) { + + // reset "fired" for items interested in this position + var i, item, j = _onPositionItems.length; + + if (!j) { + return false; + } + + for (i=j; i--;) { + item = _onPositionItems[i]; + if (item.fired && nPosition <= item.position) { + item.fired = false; + _onPositionFired--; + } + } + + return true; + + }; + + /** + * SMSound() private internals + * -------------------------------- + */ + + _applyFromTo = function() { + + var _iO = _t._iO, + f = _iO.from, + t = _iO.to, + start, end; + + end = function() { + + // end has been reached. + _s._wD(_t.sID + ': "to" time of ' + t + ' reached.'); + + // detach listener + _t.clearOnPosition(t, end); + + // stop should clear this, too + _t.stop(); + + }; + + start = function() { + + _s._wD(_t.sID + ': playing "from" ' + f); + + // add listener for end + if (t !== null && !isNaN(t)) { + _t.onPosition(t, end); + } + + }; + + if (f !== null && !isNaN(f)) { + + // apply to instance options, guaranteeing correct start position. + _iO.position = f; + + // multiShot timing can't be tracked, so prevent that. + _iO.multiShot = false; + + start(); + + } + + // return updated instanceOptions including starting position + return _iO; + + }; + + _attachOnPosition = function() { + + var op = _t._iO.onposition; + + // attach onposition things, if any, now. + + if (op) { + + var item; + + for (item in op) { + if (op.hasOwnProperty(item)) { + _t.onPosition(parseInt(item, 10), op[item]); + } + } + + } + + }; + + _detachOnPosition = function() { + + var op = _t._iO.onposition; + + // detach any onposition()-style listeners. + + if (op) { + + var item; + + for (item in op) { + if (op.hasOwnProperty(item)) { + _t.clearOnPosition(parseInt(item, 10)); + } + } + + } + + }; + + _start_html5_timer = function() { + + if (_t.isHTML5) { + _startTimer(_t); + } + + }; + + _stop_html5_timer = function() { + + if (_t.isHTML5) { + _stopTimer(_t); + } + + }; + + _resetProperties = function() { + + _onPositionItems = []; + _onPositionFired = 0; + _onplay_called = false; + + _t._hasTimer = null; + _t._a = null; + _t._html5_canplay = false; + _t.bytesLoaded = null; + _t.bytesTotal = null; + _t.duration = (_t._iO && _t._iO.duration ? _t._iO.duration : null); + _t.durationEstimate = null; + + // legacy: 1D array + _t.eqData = []; + + _t.eqData.left = []; + _t.eqData.right = []; + + _t.failures = 0; + _t.isBuffering = false; + _t.instanceOptions = {}; + _t.instanceCount = 0; + _t.loaded = false; + _t.metadata = {}; + + // 0 = uninitialised, 1 = loading, 2 = failed/error, 3 = loaded/success + _t.readyState = 0; + + _t.muted = false; + _t.paused = false; + + _t.peakData = { + left: 0, + right: 0 + }; + + _t.waveformData = { + left: [], + right: [] + }; + + _t.playState = 0; + _t.position = null; + + }; + + _resetProperties(); + + /** + * Pseudo-private SMSound internals + * -------------------------------- + */ + + this._onTimer = function(bForce) { + + /** + * HTML5-only _whileplaying() etc. + * called from both HTML5 native events, and polling/interval-based timers + * mimics flash and fires only when time/duration change, so as to be polling-friendly + */ + + var duration, isNew = false, time, x = {}; + + if (_t._hasTimer || bForce) { + + // TODO: May not need to track readyState (1 = loading) + + if (_t._a && (bForce || ((_t.playState > 0 || _t.readyState === 1) && !_t.paused))) { + + duration = _t._get_html5_duration(); + + if (duration !== _lastHTML5State.duration) { + + _lastHTML5State.duration = duration; + _t.duration = duration; + isNew = true; + + } + + // TODO: investigate why this goes wack if not set/re-set each time. + _t.durationEstimate = _t.duration; + + time = (_t._a.currentTime * 1000 || 0); + + if (time !== _lastHTML5State.time) { + + _lastHTML5State.time = time; + isNew = true; + + } + + if (isNew || bForce) { + + _t._whileplaying(time,x,x,x,x); + + } + + return isNew; + + } else { + + // _s._wD('_onTimer: Warn for "'+_t.sID+'": '+(!_t._a?'Could not find element. ':'')+(_t.playState === 0?'playState bad, 0?':'playState = '+_t.playState+', OK')); + + return false; + + } + + } + + }; + + this._get_html5_duration = function() { + + var _iO = _t._iO, + d = (_t._a ? _t._a.duration*1000 : (_iO ? _iO.duration : undefined)), + result = (d && !isNaN(d) && d !== Infinity ? d : (_iO ? _iO.duration : null)); + + return result; + + }; + + this._setup_html5 = function(oOptions) { + + var _iO = _mixin(_t._iO, oOptions), d = decodeURI, + _a = _useGlobalHTML5Audio ? _s._global_a : _t._a, + _dURL = d(_iO.url), + _oldIO = (_a && _a._t ? _a._t.instanceOptions : null); + + if (_a) { + + if (_a._t) { + + if (!_useGlobalHTML5Audio && _dURL === d(_lastURL)) { + // same url, ignore request + return _a; + } else if (_useGlobalHTML5Audio && _oldIO.url === _iO.url && (!_lastURL || (_lastURL === _oldIO.url))) { + // iOS-type reuse case + return _a; + } + + } + + _s._wD('setting new URL on existing object: ' + _dURL + (_lastURL ? ', old URL: ' + _lastURL : '')); + + /** + * "First things first, I, Poppa.." (reset the previous state of the old sound, if playing) + * Fixes case with devices that can only play one sound at a time + * Otherwise, other sounds in mid-play will be terminated without warning and in a stuck state + */ + + if (_useGlobalHTML5Audio && _a._t && _a._t.playState && _iO.url !== _oldIO.url) { + _a._t.stop(); + } + + // new URL, so reset load/playstate and so on + _resetProperties(); + + _a.src = _iO.url; + _t.url = _iO.url; + _lastURL = _iO.url; + _a._called_load = false; + + } else { + + _s._wD('creating HTML5 Audio() element with URL: '+_dURL); + _a = new Audio(_iO.url); + + _a._called_load = false; + + // android (seen in 2.3/Honeycomb) sometimes fails first .load() -> .play(), results in playback failure and ended() events? + if (_is_android) { + _a._called_load = true; + } + + if (_useGlobalHTML5Audio) { + _s._global_a = _a; + } + + } + + _t.isHTML5 = true; + + // store a ref on the track + _t._a = _a; + + // store a ref on the audio + _a._t = _t; + + _add_html5_events(); + _a.loop = (_iO.loops>1?'loop':''); + + if (_iO.autoLoad || _iO.autoPlay) { + + _t.load(); + + } else { + + // early HTML5 implementation (non-standard) + _a.autobuffer = false; + + // standard + _a.preload = 'none'; + + } + + // boolean instead of "loop", for webkit? - spec says string. http://www.w3.org/TR/html-markup/audio.html#audio.attrs.loop + _a.loop = (_iO.loops > 1 ? 'loop' : ''); + + return _a; + + }; + + _add_html5_events = function() { + + if (_t._a._added_events) { + return false; + } + + var f; + + function add(oEvt, oFn, bCapture) { + return _t._a ? _t._a.addEventListener(oEvt, oFn, bCapture||false) : null; + } + + _s._wD(_h5+'adding event listeners: '+_t.sID); + _t._a._added_events = true; + + for (f in _html5_events) { + if (_html5_events.hasOwnProperty(f)) { + add(f, _html5_events[f]); + } + } + + return true; + + }; + + _remove_html5_events = function() { + + // Remove event listeners + + var f; + + function remove(oEvt, oFn, bCapture) { + return (_t._a ? _t._a.removeEventListener(oEvt, oFn, bCapture||false) : null); + } + + _s._wD(_h5+'removing event listeners: '+_t.sID); + _t._a._added_events = false; + + for (f in _html5_events) { + if (_html5_events.hasOwnProperty(f)) { + remove(f, _html5_events[f]); + } + } + + }; + + /** + * Pseudo-private event internals + * ------------------------------ + */ + + this._onload = function(nSuccess) { + + + var fN, loadOK = !!(nSuccess); + _s._wD(fN + '"' + _t.sID + '"' + (loadOK?' loaded.':' failed to load? - ' + _t.url), (loadOK?1:2)); + + // + fN = 'SMSound._onload(): '; + if (!loadOK && !_t.isHTML5) { + if (_s.sandbox.noRemote === true) { + _s._wD(fN + _str('noNet'), 1); + } + if (_s.sandbox.noLocal === true) { + _s._wD(fN + _str('noLocal'), 1); + } + } + // + + _t.loaded = loadOK; + _t.readyState = loadOK?3:2; + _t._onbufferchange(0); + + if (_t._iO.onload) { + _t._iO.onload.apply(_t, [loadOK]); + } + + return true; + + }; + + this._onbufferchange = function(nIsBuffering) { + + if (_t.playState === 0) { + // ignore if not playing + return false; + } + + if ((nIsBuffering && _t.isBuffering) || (!nIsBuffering && !_t.isBuffering)) { + return false; + } + + _t.isBuffering = (nIsBuffering === 1); + if (_t._iO.onbufferchange) { + _s._wD('SMSound._onbufferchange(): ' + nIsBuffering); + _t._iO.onbufferchange.apply(_t); + } + + return true; + + }; + + /** + * Notify Mobile Safari that user action is required + * to continue playing / loading the audio file. + */ + + this._onsuspend = function() { + + if (_t._iO.onsuspend) { + _s._wD('SMSound._onsuspend()'); + _t._iO.onsuspend.apply(_t); + } + + return true; + + }; + + /** + * flash 9/movieStar + RTMP-only method, should fire only once at most + * at this point we just recreate failed sounds rather than trying to reconnect + */ + + this._onfailure = function(msg, level, code) { + + _t.failures++; + _s._wD('SMSound._onfailure(): "'+_t.sID+'" count '+_t.failures); + + if (_t._iO.onfailure && _t.failures === 1) { + _t._iO.onfailure(_t, msg, level, code); + } else { + _s._wD('SMSound._onfailure(): ignoring'); + } + + }; + + this._onfinish = function() { + + // store local copy before it gets trashed.. + var _io_onfinish = _t._iO.onfinish; + + _t._onbufferchange(0); + _t._resetOnPosition(0); + + // reset some state items + if (_t.instanceCount) { + + _t.instanceCount--; + + if (!_t.instanceCount) { + + // remove onPosition listeners, if any + _detachOnPosition(); + + // reset instance options + _t.playState = 0; + _t.paused = false; + _t.instanceCount = 0; + _t.instanceOptions = {}; + _t._iO = {}; + _stop_html5_timer(); + + } + + if (!_t.instanceCount || _t._iO.multiShotEvents) { + // fire onfinish for last, or every instance + if (_io_onfinish) { + _s._wD('SMSound._onfinish(): "' + _t.sID + '"'); + _io_onfinish.apply(_t); + } + } + + } + + }; + + this._whileloading = function(nBytesLoaded, nBytesTotal, nDuration, nBufferLength) { + + var _iO = _t._iO; + + _t.bytesLoaded = nBytesLoaded; + _t.bytesTotal = nBytesTotal; + _t.duration = Math.floor(nDuration); + _t.bufferLength = nBufferLength; + + if (!_iO.isMovieStar) { + + if (_iO.duration) { + // use options, if specified and larger + _t.durationEstimate = (_t.duration > _iO.duration) ? _t.duration : _iO.duration; + } else { + _t.durationEstimate = parseInt((_t.bytesTotal / _t.bytesLoaded) * _t.duration, 10); + + } + + if (_t.durationEstimate === undefined) { + _t.durationEstimate = _t.duration; + } + + if (_t.readyState !== 3 && _iO.whileloading) { + _iO.whileloading.apply(_t); + } + + } else { + + _t.durationEstimate = _t.duration; + if (_t.readyState !== 3 && _iO.whileloading) { + _iO.whileloading.apply(_t); + } + + } + + }; + + this._whileplaying = function(nPosition, oPeakData, oWaveformDataLeft, oWaveformDataRight, oEQData) { + + var _iO = _t._iO; + + if (isNaN(nPosition) || nPosition === null) { + // flash safety net + return false; + } + + _t.position = nPosition; + _t._processOnPosition(); + + if (!_t.isHTML5 && _fV > 8) { + + if (_iO.usePeakData && typeof oPeakData !== 'undefined' && oPeakData) { + _t.peakData = { + left: oPeakData.leftPeak, + right: oPeakData.rightPeak + }; + } + + if (_iO.useWaveformData && typeof oWaveformDataLeft !== 'undefined' && oWaveformDataLeft) { + _t.waveformData = { + left: oWaveformDataLeft.split(','), + right: oWaveformDataRight.split(',') + }; + } + + if (_iO.useEQData) { + if (typeof oEQData !== 'undefined' && oEQData && oEQData.leftEQ) { + var eqLeft = oEQData.leftEQ.split(','); + _t.eqData = eqLeft; + _t.eqData.left = eqLeft; + if (typeof oEQData.rightEQ !== 'undefined' && oEQData.rightEQ) { + _t.eqData.right = oEQData.rightEQ.split(','); + } + } + } + + } + + if (_t.playState === 1) { + + // special case/hack: ensure buffering is false if loading from cache (and not yet started) + if (!_t.isHTML5 && _fV === 8 && !_t.position && _t.isBuffering) { + _t._onbufferchange(0); + } + + if (_iO.whileplaying) { + // flash may call after actual finish + _iO.whileplaying.apply(_t); + } + + } + + return true; + + }; + + this._onmetadata = function(oMDProps, oMDData) { + + /** + * internal: flash 9 + NetStream (MovieStar/RTMP-only) feature + * RTMP may include song title, MovieStar content may include encoding info + * + * @param {array} oMDProps (names) + * @param {array} oMDData (values) + */ + + _s._wD('SMSound._onmetadata(): "' + this.sID + '" metadata received.'); + + var oData = {}, i, j; + + for (i = 0, j = oMDProps.length; i < j; i++) { + oData[oMDProps[i]] = oMDData[i]; + } + _t.metadata = oData; + + if (_t._iO.onmetadata) { + _t._iO.onmetadata.apply(_t); + } + + }; + + this._onid3 = function(oID3Props, oID3Data) { + + /** + * internal: flash 8 + flash 9 ID3 feature + * may include artist, song title etc. + * + * @param {array} oID3Props (names) + * @param {array} oID3Data (values) + */ + + _s._wD('SMSound._onid3(): "' + this.sID + '" ID3 data received.'); + + var oData = [], i, j; + + for (i = 0, j = oID3Props.length; i < j; i++) { + oData[oID3Props[i]] = oID3Data[i]; + } + _t.id3 = _mixin(_t.id3, oData); + + if (_t._iO.onid3) { + _t._iO.onid3.apply(_t); + } + + }; + + // flash/RTMP-only + + this._onconnect = function(bSuccess) { + + bSuccess = (bSuccess === 1); + _s._wD('SMSound._onconnect(): "'+_t.sID+'"'+(bSuccess?' connected.':' failed to connect? - '+_t.url), (bSuccess?1:2)); + _t.connected = bSuccess; + + if (bSuccess) { + + _t.failures = 0; + + if (_idCheck(_t.sID)) { + if (_t.getAutoPlay()) { + // only update the play state if auto playing + _t.play(undefined, _t.getAutoPlay()); + } else if (_t._iO.autoLoad) { + _t.load(); + } + } + + if (_t._iO.onconnect) { + _t._iO.onconnect.apply(_t, [bSuccess]); + } + + } + + }; + + this._ondataerror = function(sError) { + + // flash 9 wave/eq data handler + // hack: called at start, and end from flash at/after onfinish() + if (_t.playState > 0) { + _s._wD('SMSound._ondataerror(): ' + sError); + if (_t._iO.ondataerror) { + _t._iO.ondataerror.apply(_t); + } + } + + }; + + }; // SMSound() + + /** + * Private SoundManager internals + * ------------------------------ + */ + + _getDocument = function() { + + return (_doc.body || _doc._docElement || _doc.getElementsByTagName('div')[0]); + + }; + + _id = function(sID) { + + return _doc.getElementById(sID); + + }; + + _mixin = function(oMain, oAdd) { + + // non-destructive merge + var o1 = {}, i, o2, o; + + // clone c1 + for (i in oMain) { + if (oMain.hasOwnProperty(i)) { + o1[i] = oMain[i]; + } + } + + o2 = (typeof oAdd === 'undefined'?_s.defaultOptions:oAdd); + for (o in o2) { + if (o2.hasOwnProperty(o) && typeof o1[o] === 'undefined') { + o1[o] = o2[o]; + } + } + return o1; + + }; + + _event = (function() { + + var old = (_win.attachEvent), + evt = { + add: (old?'attachEvent':'addEventListener'), + remove: (old?'detachEvent':'removeEventListener') + }; + + function getArgs(oArgs) { + + var args = _slice.call(oArgs), len = args.length; + + if (old) { + // prefix + args[1] = 'on' + args[1]; + if (len > 3) { + // no capture + args.pop(); + } + } else if (len === 3) { + args.push(false); + } + + return args; + + } + + function apply(args, sType) { + + var element = args.shift(), + method = [evt[sType]]; + + if (old) { + element[method](args[0], args[1]); + } else { + element[method].apply(element, args); + } + + } + + function add() { + + apply(getArgs(arguments), 'add'); + + } + + function remove() { + + apply(getArgs(arguments), 'remove'); + + } + + return { + 'add': add, + 'remove': remove + }; + + }()); + + /** + * Internal HTML5 event handling + * ----------------------------- + */ + + function _html5_event(oFn) { + + // wrap html5 event handlers so we don't call them on destroyed sounds + + return function(e) { + + var t = this._t; + + if (!t || !t._a) { + // + if (t && t.sID) { + _s._wD(_h5+'ignoring '+e.type+': '+t.sID); + } else { + _s._wD(_h5+'ignoring '+e.type); + } + // + return null; + } else { + return oFn.call(this, e); + } + + }; + + } + + _html5_events = { + + // HTML5 event-name-to-handler map + + abort: _html5_event(function(e) { + + _s._wD(_h5+'abort: '+this._t.sID); + + }), + + // enough has loaded to play + + canplay: _html5_event(function(e) { + + var t = this._t; + + if (t._html5_canplay) { + // this event has already fired. ignore. + return true; + } + + t._html5_canplay = true; + _s._wD(_h5+'canplay: '+t.sID+', '+t.url); + t._onbufferchange(0); + var position1K = (!isNaN(t.position)?t.position/1000:null); + + // set the position if position was set before the sound loaded + if (t.position && this.currentTime !== position1K) { + _s._wD(_h5+'canplay: setting position to '+position1K); + try { + this.currentTime = position1K; + } catch(ee) { + _s._wD(_h5+'setting position failed: '+ee.message, 2); + } + } + + // hack for HTML5 from/to case + if (t._iO._oncanplay) { + t._iO._oncanplay(); + } + + }), + + load: _html5_event(function(e) { + + var t = this._t; + + if (!t.loaded) { + t._onbufferchange(0); + // should be 1, and the same + t._whileloading(t.bytesTotal, t.bytesTotal, t._get_html5_duration()); + t._onload(true); + } + + }), + + emptied: _html5_event(function(e) { + + _s._wD(_h5+'emptied: '+this._t.sID); + + }), + + ended: _html5_event(function(e) { + + var t = this._t; + + _s._wD(_h5+'ended: '+t.sID); + t._onfinish(); + + }), + + error: _html5_event(function(e) { + + _s._wD(_h5+'error: '+this.error.code); + // call load with error state? + this._t._onload(false); + + }), + + loadeddata: _html5_event(function(e) { + + var t = this._t, + // at least 1 byte, so math works + bytesTotal = t.bytesTotal || 1; + + _s._wD(_h5+'loadeddata: '+this._t.sID); + + // safari seems to nicely report progress events, eventually totalling 100% + if (!t._loaded && !_isSafari) { + t.duration = t._get_html5_duration(); + // fire whileloading() with 100% values + t._whileloading(bytesTotal, bytesTotal, t._get_html5_duration()); + t._onload(true); + } + + }), + + loadedmetadata: _html5_event(function(e) { + + _s._wD(_h5+'loadedmetadata: '+this._t.sID); + + }), + + loadstart: _html5_event(function(e) { + + _s._wD(_h5+'loadstart: '+this._t.sID); + // assume buffering at first + this._t._onbufferchange(1); + + }), + + play: _html5_event(function(e) { + + _s._wD(_h5+'play: '+this._t.sID+', '+this._t.url); + // once play starts, no buffering + this._t._onbufferchange(0); + + }), + + playing: _html5_event(function(e) { + + _s._wD(_h5+'playing: '+this._t.sID); + + // once play starts, no buffering + this._t._onbufferchange(0); + + }), + + progress: _html5_event(function(e) { + + var t = this._t; + + if (t.loaded) { + return false; + } + + var i, j, str, buffered = 0, + isProgress = (e.type === 'progress'), + ranges = e.target.buffered, + + // firefox 3.6 implements e.loaded/total (bytes) + loaded = (e.loaded||0), + + total = (e.total||1); + + if (ranges && ranges.length) { + + // if loaded is 0, try TimeRanges implementation as % of load + // https://developer.mozilla.org/en/DOM/TimeRanges + + for (i=ranges.length; i--;) { + buffered = (ranges.end(i) - ranges.start(i)); + } + + // linear case, buffer sum; does not account for seeking and HTTP partials / byte ranges + loaded = buffered/e.target.duration; + + // + if (isProgress && ranges.length > 1) { + str = []; + j = ranges.length; + for (i=0; i + + } + + if (!isNaN(loaded)) { + + // if progress, likely not buffering + t._onbufferchange(0); + t._whileloading(loaded, total, t._get_html5_duration()); + if (loaded && total && loaded === total) { + // in case "onload" doesn't fire (eg. gecko 1.9.2) + _html5_events.load.call(this, e); + } + + } + + }), + + ratechange: _html5_event(function(e) { + + _s._wD(_h5+'ratechange: '+this._t.sID); + + }), + + suspend: _html5_event(function(e) { + + // download paused/stopped, may have finished (eg. onload) + var t = this._t; + + _s._wD(_h5+'suspend: '+t.sID); + _html5_events.progress.call(this, e); + t._onsuspend(); + + }), + + stalled: _html5_event(function(e) { + + _s._wD(_h5+'stalled: '+this._t.sID); + + }), + + timeupdate: _html5_event(function(e) { + + this._t._onTimer(); + + }), + + waiting: _html5_event(function(e) { + + var t = this._t; + + // see also: seeking + _s._wD(_h5+'waiting: '+t.sID); + + // playback faster than download rate, etc. + t._onbufferchange(1); + + }) + + }; + + _html5OK = function(iO) { + + // Use type, if specified. If HTML5-only mode, no other options, so just give 'er + return (!iO.serverURL && (iO.type?_html5CanPlay({type:iO.type}):_html5CanPlay({url:iO.url})||_s.html5Only)); + + }; + + _html5Unload = function(oAudio) { + + /** + * Internal method: Unload media, and cancel any current/pending network requests. + * Firefox can load an empty URL, which allegedly destroys the decoder and stops the download. + * https://developer.mozilla.org/En/Using_audio_and_video_in_Firefox#Stopping_the_download_of_media + * Other UA behaviour is unclear, so everyone else gets an about:blank-style URL. + */ + + if (oAudio) { + // Firefox likes '' for unload, most other UAs don't and fail to unload. + oAudio.src = (_is_firefox ? '' : _emptyURL); + } + + }; + + _html5CanPlay = function(o) { + + /** + * Try to find MIME, test and return truthiness + * o = { + * url: '/path/to/an.mp3', + * type: 'audio/mp3' + * } + */ + + if (!_s.useHTML5Audio || !_s.hasHTML5) { + return false; + } + + var url = (o.url || null), + mime = (o.type || null), + aF = _s.audioFormats, + result, + offset, + fileExt, + item; + + function preferFlashCheck(kind) { + + // whether flash should play a given type + return (_s.preferFlash && _hasFlash && !_s.ignoreFlash && (typeof _s.flash[kind] !== 'undefined' && _s.flash[kind])); + + } + + // account for known cases like audio/mp3 + + if (mime && _s.html5[mime] !== 'undefined') { + return (_s.html5[mime] && !preferFlashCheck(mime)); + } + + if (!_html5Ext) { + _html5Ext = []; + for (item in aF) { + if (aF.hasOwnProperty(item)) { + _html5Ext.push(item); + if (aF[item].related) { + _html5Ext = _html5Ext.concat(aF[item].related); + } + } + } + _html5Ext = new RegExp('\\.('+_html5Ext.join('|')+')(\\?.*)?$','i'); + } + + // TODO: Strip URL queries, etc. + fileExt = (url ? url.toLowerCase().match(_html5Ext) : null); + + if (!fileExt || !fileExt.length) { + if (!mime) { + return false; + } else { + // audio/mp3 -> mp3, result should be known + offset = mime.indexOf(';'); + // strip "audio/X; codecs.." + fileExt = (offset !== -1?mime.substr(0,offset):mime).substr(6); + } + } else { + // match the raw extension name - "mp3", for example + fileExt = fileExt[1]; + } + + if (fileExt && typeof _s.html5[fileExt] !== 'undefined') { + // result known + return (_s.html5[fileExt] && !preferFlashCheck(fileExt)); + } else { + mime = 'audio/'+fileExt; + result = _s.html5.canPlayType({type:mime}); + _s.html5[fileExt] = result; + // _s._wD('canPlayType, found result: '+result); + return (result && _s.html5[mime] && !preferFlashCheck(mime)); + } + + }; + + _testHTML5 = function() { + + if (!_s.useHTML5Audio || typeof Audio === 'undefined') { + return false; + } + + // double-whammy: Opera 9.64 throws WRONG_ARGUMENTS_ERR if no parameter passed to Audio(), and Webkit + iOS happily tries to load "null" as a URL. :/ + var a = (typeof Audio !== 'undefined' ? (_isOpera ? new Audio(null) : new Audio()) : null), + item, support = {}, aF, i; + + function _cp(m) { + + var canPlay, i, j, isOK = false; + + if (!a || typeof a.canPlayType !== 'function') { + return false; + } + + if (m instanceof Array) { + // iterate through all mime types, return any successes + for (i=0, j=m.length; i + notReady: 'Not loaded yet - wait for soundManager.onload()/onready()', + notOK: 'Audio support is not available.', + domError: _smc + 'createMovie(): appendChild/innerHTML call failed. DOM not ready or other error.', + spcWmode: _smc + 'createMovie(): Removing wmode, preventing known SWF loading issue(s)', + swf404: _sm + ': Verify that %s is a valid path.', + tryDebug: 'Try ' + _sm + '.debugFlash = true for more security details (output goes to SWF.)', + checkSWF: 'See SWF output for more debug info.', + localFail: _sm + ': Non-HTTP page (' + _doc.location.protocol + ' URL?) Review Flash player security settings for this special case:\nhttp://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html\nMay need to add/allow path, eg. c:/sm2/ or /users/me/sm2/', + waitFocus: _sm + ': Special case: Waiting for focus-related event..', + waitImpatient: _sm + ': Getting impatient, still waiting for Flash%s...', + waitForever: _sm + ': Waiting indefinitely for Flash (will recover if unblocked)...', + needFunction: _sm + ': Function object expected for %s', + badID: 'Warning: Sound ID "%s" should be a string, starting with a non-numeric character', + currentObj: '--- ' + _sm + '._debug(): Current sound objects ---', + waitEI: _smc + 'initMovie(): Waiting for ExternalInterface call from Flash..', + waitOnload: _sm + ': Waiting for window.onload()', + docLoaded: _sm + ': Document already loaded', + onload: _smc + 'initComplete(): calling soundManager.onload()', + onloadOK: _sm + '.onload() complete', + init: _smc + 'init()', + didInit: _smc + 'init(): Already called?', + flashJS: _sm + ': Attempting to call Flash from JS..', + secNote: 'Flash security note: Network/internet URLs will not load due to security restrictions. Access can be configured via Flash Player Global Security Settings Page: http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html', + badRemove: 'Warning: Failed to remove flash movie.', + noPeak: 'Warning: peakData features unsupported for movieStar formats', + shutdown: _sm + '.disable(): Shutting down', + queue: _sm + ': Queueing %s handler', + smFail: _sm + ': Failed to initialise.', + smError: 'SMSound.load(): Exception: JS-Flash communication failed, or JS error.', + fbTimeout: 'No flash response, applying .'+_swfCSS.swfTimedout+' CSS..', + fbLoaded: 'Flash loaded', + fbHandler: _smc+'flashBlockHandler()', + manURL: 'SMSound.load(): Using manually-assigned URL', + onURL: _sm + '.load(): current URL already assigned.', + badFV: _sm + '.flashVersion must be 8 or 9. "%s" is invalid. Reverting to %s.', + as2loop: 'Note: Setting stream:false so looping can work (flash 8 limitation)', + noNSLoop: 'Note: Looping not implemented for MovieStar formats', + needfl9: 'Note: Switching to flash 9, required for MP4 formats.', + mfTimeout: 'Setting flashLoadTimeout = 0 (infinite) for off-screen, mobile flash case', + mfOn: 'mobileFlash::enabling on-screen flash repositioning', + policy: 'Enabling usePolicyFile for data access' + // + + }; + + _str = function() { + + // internal string replace helper. + // arguments: o [,items to replace] + // + + // real array, please + var args = _slice.call(arguments), + + // first arg + o = args.shift(), + + str = (_strings && _strings[o]?_strings[o]:''), i, j; + if (str && args && args.length) { + for (i = 0, j = args.length; i < j; i++) { + str = str.replace('%s', args[i]); + } + } + + return str; + // + + }; + + _loopFix = function(sOpt) { + + // flash 8 requires stream = false for looping to work + if (_fV === 8 && sOpt.loops > 1 && sOpt.stream) { + _wDS('as2loop'); + sOpt.stream = false; + } + + return sOpt; + + }; + + _policyFix = function(sOpt, sPre) { + + if (sOpt && !sOpt.usePolicyFile && (sOpt.onid3 || sOpt.usePeakData || sOpt.useWaveformData || sOpt.useEQData)) { + _s._wD((sPre || '') + _str('policy')); + sOpt.usePolicyFile = true; + } + + return sOpt; + + }; + + _complain = function(sMsg) { + + // + if (typeof console !== 'undefined' && typeof console.warn !== 'undefined') { + console.warn(sMsg); + } else { + _s._wD(sMsg); + } + // + + }; + + _doNothing = function() { + + return false; + + }; + + _disableObject = function(o) { + + var oProp; + + for (oProp in o) { + if (o.hasOwnProperty(oProp) && typeof o[oProp] === 'function') { + o[oProp] = _doNothing; + } + } + + oProp = null; + + }; + + _failSafely = function(bNoDisable) { + + // general failure exception handler + + if (typeof bNoDisable === 'undefined') { + bNoDisable = false; + } + + if (_disabled || bNoDisable) { + _wDS('smFail', 2); + _s.disable(bNoDisable); + } + + }; + + _normalizeMovieURL = function(smURL) { + + var urlParams = null, url; + + if (smURL) { + if (smURL.match(/\.swf(\?.*)?$/i)) { + urlParams = smURL.substr(smURL.toLowerCase().lastIndexOf('.swf?') + 4); + if (urlParams) { + // assume user knows what they're doing + return smURL; + } + } else if (smURL.lastIndexOf('/') !== smURL.length - 1) { + // append trailing slash, if needed + smURL += '/'; + } + } + + url = (smURL && smURL.lastIndexOf('/') !== - 1 ? smURL.substr(0, smURL.lastIndexOf('/') + 1) : './') + _s.movieURL; + + if (_s.noSWFCache) { + url += ('?ts=' + new Date().getTime()); + } + + return url; + + }; + + _setVersionInfo = function() { + + // short-hand for internal use + + _fV = parseInt(_s.flashVersion, 10); + + if (_fV !== 8 && _fV !== 9) { + _s._wD(_str('badFV', _fV, _defaultFlashVersion)); + _s.flashVersion = _fV = _defaultFlashVersion; + } + + // debug flash movie, if applicable + + var isDebug = (_s.debugMode || _s.debugFlash?'_debug.swf':'.swf'); + + if (_s.useHTML5Audio && !_s.html5Only && _s.audioFormats.mp4.required && _fV < 9) { + _s._wD(_str('needfl9')); + _s.flashVersion = _fV = 9; + } + + _s.version = _s.versionNumber + (_s.html5Only?' (HTML5-only mode)':(_fV === 9?' (AS3/Flash 9)':' (AS2/Flash 8)')); + + // set up default options + if (_fV > 8) { + // +flash 9 base options + _s.defaultOptions = _mixin(_s.defaultOptions, _s.flash9Options); + _s.features.buffering = true; + // +moviestar support + _s.defaultOptions = _mixin(_s.defaultOptions, _s.movieStarOptions); + _s.filePatterns.flash9 = new RegExp('\\.(mp3|' + _netStreamTypes.join('|') + ')(\\?.*)?$', 'i'); + _s.features.movieStar = true; + } else { + _s.features.movieStar = false; + } + + // regExp for flash canPlay(), etc. + _s.filePattern = _s.filePatterns[(_fV !== 8?'flash9':'flash8')]; + + // if applicable, use _debug versions of SWFs + _s.movieURL = (_fV === 8?'soundmanager2.swf':'soundmanager2_flash9.swf').replace('.swf', isDebug); + + _s.features.peakData = _s.features.waveformData = _s.features.eqData = (_fV > 8); + + }; + + _setPolling = function(bPolling, bHighPerformance) { + + if (!_flash) { + return false; + } + + _flash._setPolling(bPolling, bHighPerformance); + + }; + + _initDebug = function() { + + // starts debug mode, creating output
    for UAs without console object + + // allow force of debug mode via URL + if (_s.debugURLParam.test(_wl)) { + _s.debugMode = true; + } + + // + if (_id(_s.debugID)) { + return false; + } + + var oD, oDebug, oTarget, oToggle, tmp; + + if (_s.debugMode && !_id(_s.debugID) && (!_hasConsole || !_s.useConsole || !_s.consoleOnly)) { + + oD = _doc.createElement('div'); + oD.id = _s.debugID + '-toggle'; + + oToggle = { + 'position': 'fixed', + 'bottom': '0px', + 'right': '0px', + 'width': '1.2em', + 'height': '1.2em', + 'lineHeight': '1.2em', + 'margin': '2px', + 'textAlign': 'center', + 'border': '1px solid #999', + 'cursor': 'pointer', + 'background': '#fff', + 'color': '#333', + 'zIndex': 10001 + }; + + oD.appendChild(_doc.createTextNode('-')); + oD.onclick = _toggleDebug; + oD.title = 'Toggle SM2 debug console'; + + if (_ua.match(/msie 6/i)) { + oD.style.position = 'absolute'; + oD.style.cursor = 'hand'; + } + + for (tmp in oToggle) { + if (oToggle.hasOwnProperty(tmp)) { + oD.style[tmp] = oToggle[tmp]; + } + } + + oDebug = _doc.createElement('div'); + oDebug.id = _s.debugID; + oDebug.style.display = (_s.debugMode?'block':'none'); + + if (_s.debugMode && !_id(oD.id)) { + try { + oTarget = _getDocument(); + oTarget.appendChild(oD); + } catch(e2) { + throw new Error(_str('domError')+' \n'+e2.toString()); + } + oTarget.appendChild(oDebug); + } + + } + + oTarget = null; + // + + }; + + _idCheck = this.getSoundById; + + // + _wDS = function(o, errorLevel) { + + if (!o) { + return ''; + } else { + return _s._wD(_str(o), errorLevel); + } + + }; + + // last-resort debugging option + + if (_wl.indexOf('sm2-debug=alert') + 1 && _s.debugMode) { + _s._wD = function(sText) {window.alert(sText);}; + } + + _toggleDebug = function() { + + var o = _id(_s.debugID), + oT = _id(_s.debugID + '-toggle'); + + if (!o) { + return false; + } + + if (_debugOpen) { + // minimize + oT.innerHTML = '+'; + o.style.display = 'none'; + } else { + oT.innerHTML = '-'; + o.style.display = 'block'; + } + + _debugOpen = !_debugOpen; + + }; + + _debugTS = function(sEventType, bSuccess, sMessage) { + + // troubleshooter debug hooks + + if (typeof sm2Debugger !== 'undefined') { + try { + sm2Debugger.handleEvent(sEventType, bSuccess, sMessage); + } catch(e) { + // oh well + } + } + + return true; + + }; + // + + _getSWFCSS = function() { + + var css = []; + + if (_s.debugMode) { + css.push(_swfCSS.sm2Debug); + } + + if (_s.debugFlash) { + css.push(_swfCSS.flashDebug); + } + + if (_s.useHighPerformance) { + css.push(_swfCSS.highPerf); + } + + return css.join(' '); + + }; + + _flashBlockHandler = function() { + + // *possible* flash block situation. + + var name = _str('fbHandler'), + p = _s.getMoviePercent(), + css = _swfCSS, + error = {type:'FLASHBLOCK'}; + + if (_s.html5Only) { + return false; + } + + if (!_s.ok()) { + + if (_needsFlash) { + // make the movie more visible, so user can fix + _s.oMC.className = _getSWFCSS() + ' ' + css.swfDefault + ' ' + (p === null?css.swfTimedout:css.swfError); + _s._wD(name+': '+_str('fbTimeout')+(p?' ('+_str('fbLoaded')+')':'')); + } + + _s.didFlashBlock = true; + + // fire onready(), complain lightly + _processOnEvents({type:'ontimeout', ignoreInit:true, error:error}); + _catchError(error); + + } else { + + // SM2 loaded OK (or recovered) + + // + if (_s.didFlashBlock) { + _s._wD(name+': Unblocked'); + } + // + + if (_s.oMC) { + _s.oMC.className = [_getSWFCSS(), css.swfDefault, css.swfLoaded + (_s.didFlashBlock?' '+css.swfUnblocked:'')].join(' '); + } + + } + + }; + + _addOnEvent = function(sType, oMethod, oScope) { + + if (typeof _on_queue[sType] === 'undefined') { + _on_queue[sType] = []; + } + + _on_queue[sType].push({ + 'method': oMethod, + 'scope': (oScope || null), + 'fired': false + }); + + }; + + _processOnEvents = function(oOptions) { + + // assume onready, if unspecified + + if (!oOptions) { + oOptions = { + type: 'onready' + }; + } + + if (!_didInit && oOptions && !oOptions.ignoreInit) { + // not ready yet. + return false; + } + + if (oOptions.type === 'ontimeout' && _s.ok()) { + // invalid case + return false; + } + + var status = { + success: (oOptions && oOptions.ignoreInit?_s.ok():!_disabled) + }, + + // queue specified by type, or none + srcQueue = (oOptions && oOptions.type?_on_queue[oOptions.type]||[]:[]), + + queue = [], i, j, + args = [status], + canRetry = (_needsFlash && _s.useFlashBlock && !_s.ok()); + + if (oOptions.error) { + args[0].error = oOptions.error; + } + + for (i = 0, j = srcQueue.length; i < j; i++) { + if (srcQueue[i].fired !== true) { + queue.push(srcQueue[i]); + } + } + + if (queue.length) { + _s._wD(_sm + ': Firing ' + queue.length + ' '+oOptions.type+'() item' + (queue.length === 1?'':'s')); + for (i = 0, j = queue.length; i < j; i++) { + if (queue[i].scope) { + queue[i].method.apply(queue[i].scope, args); + } else { + queue[i].method.apply(this, args); + } + if (!canRetry) { + // flashblock case doesn't count here + queue[i].fired = true; + } + } + } + + return true; + + }; + + _initUserOnload = function() { + + _win.setTimeout(function() { + + if (_s.useFlashBlock) { + _flashBlockHandler(); + } + + _processOnEvents(); + + // call user-defined "onload", scoped to window + + if (_s.onload instanceof Function) { + _wDS('onload', 1); + _s.onload.apply(_win); + _wDS('onloadOK', 1); + } + + if (_s.waitForWindowLoad) { + _event.add(_win, 'load', _initUserOnload); + } + + },1); + + }; + + _detectFlash = function() { + + // hat tip: Flash Detect library (BSD, (C) 2007) by Carl "DocYes" S. Yestrau - http://featureblend.com/javascript-flash-detection-library.html / http://featureblend.com/license.txt + + if (_hasFlash !== undefined) { + // this work has already been done. + return _hasFlash; + } + + var hasPlugin = false, n = navigator, nP = n.plugins, obj, type, types, AX = _win.ActiveXObject; + + if (nP && nP.length) { + type = 'application/x-shockwave-flash'; + types = n.mimeTypes; + if (types && types[type] && types[type].enabledPlugin && types[type].enabledPlugin.description) { + hasPlugin = true; + } + } else if (typeof AX !== 'undefined') { + try { + obj = new AX('ShockwaveFlash.ShockwaveFlash'); + } catch(e) { + // oh well + } + hasPlugin = (!!obj); + } + + _hasFlash = hasPlugin; + + return hasPlugin; + + }; + + _featureCheck = function() { + + var needsFlash, item, + + // iPhone <= 3.1 has broken HTML5 audio(), but firmware 3.2 (iPad) + iOS4 works. + isSpecial = (_is_iDevice && !!(_ua.match(/os (1|2|3_0|3_1)/i))); + + if (isSpecial) { + + // has Audio(), but is broken; let it load links directly. + _s.hasHTML5 = false; + + // ignore flash case, however + _s.html5Only = true; + + if (_s.oMC) { + _s.oMC.style.display = 'none'; + } + + return false; + + } + + if (_s.useHTML5Audio) { + + if (!_s.html5 || !_s.html5.canPlayType) { + _s._wD('SoundManager: No HTML5 Audio() support detected.'); + _s.hasHTML5 = false; + return true; + } else { + _s.hasHTML5 = true; + } + if (_isBadSafari) { + _s._wD(_smc+'Note: Buggy HTML5 Audio in Safari on this OS X release, see https://bugs.webkit.org/show_bug.cgi?id=32159 - '+(!_hasFlash?' would use flash fallback for MP3/MP4, but none detected.':'will use flash fallback for MP3/MP4, if available'),1); + if (_detectFlash()) { + return true; + } + } + } else { + + // flash needed (or, HTML5 needs enabling.) + return true; + + } + + for (item in _s.audioFormats) { + if (_s.audioFormats.hasOwnProperty(item)) { + if ((_s.audioFormats[item].required && !_s.html5.canPlayType(_s.audioFormats[item].type)) || _s.flash[item] || _s.flash[_s.audioFormats[item].type]) { + // flash may be required, or preferred for this format + needsFlash = true; + } + } + } + + // sanity check.. + if (_s.ignoreFlash) { + needsFlash = false; + } + + _s.html5Only = (_s.hasHTML5 && _s.useHTML5Audio && !needsFlash); + + return (!_s.html5Only); + + }; + + _parseURL = function(url) { + + /** + * Internal: Finds and returns the first playable URL (or failing that, the first URL.) + * @param {string or array} url A single URL string, OR, an array of URL strings or {url:'/path/to/resource', type:'audio/mp3'} objects. + */ + + var i, j, result = 0; + + if (url instanceof Array) { + + // find the first good one + for (i=0, j=url.length; i + var sb = _s.sandbox; + + sb.type = sandboxType; + sb.description = sb.types[(typeof sb.types[sandboxType] !== 'undefined'?sandboxType:'unknown')]; + + _s._wD('Flash security sandbox type: ' + sb.type); + + if (sb.type === 'localWithFile') { + + sb.noRemote = true; + sb.noLocal = false; + _wDS('secNote', 2); + + } else if (sb.type === 'localWithNetwork') { + + sb.noRemote = false; + sb.noLocal = true; + + } else if (sb.type === 'localTrusted') { + + sb.noRemote = false; + sb.noLocal = false; + + } + // + + }; + + this._externalInterfaceOK = function(flashDate, swfVersion) { + + // flash callback confirming flash loaded, EI working etc. + // flashDate = approx. timing/delay info for JS/flash bridge + // swfVersion: SWF build string + + if (_s.swfLoaded) { + return false; + } + + var e, eiTime = new Date().getTime(); + + _s._wD(_smc+'externalInterfaceOK()' + (flashDate?' (~' + (eiTime - flashDate) + ' ms)':'')); + _debugTS('swf', true); + _debugTS('flashtojs', true); + _s.swfLoaded = true; + _tryInitOnFocus = false; + + if (_isBadSafari) { + _badSafariFix(); + } + + // complain if JS + SWF build/version strings don't match, excluding +DEV builds + // + if (!swfVersion || swfVersion.replace(/\+dev/i,'') !== _s.versionNumber.replace(/\+dev/i, '')) { + + e = _sm + ': Fatal: JavaScript file build "' + _s.versionNumber + '" does not match Flash SWF build "' + swfVersion + '" at ' + _s.url + '. Ensure both are up-to-date.'; + + // escape flash -> JS stack so this error fires in window. + setTimeout(function versionMismatch() { + throw new Error(e); + }, 0); + + // exit, init will fail with timeout + return false; + + } + // + + if (_isIE) { + // IE needs a timeout OR delay until window.onload - may need TODO: investigating + setTimeout(_init, 100); + } else { + _init(); + } + + }; + + /** + * Private initialization helpers + * ------------------------------ + */ + + _createMovie = function(smID, smURL) { + + if (_didAppend && _appendSuccess) { + // ignore if already succeeded + return false; + } + + function _initMsg() { + _s._wD('-- SoundManager 2 ' + _s.version + (!_s.html5Only && _s.useHTML5Audio?(_s.hasHTML5?' + HTML5 audio':', no HTML5 audio support'):'') + (!_s.html5Only ? (_s.useHighPerformance?', high performance mode, ':', ') + (( _s.flashPollingInterval ? 'custom (' + _s.flashPollingInterval + 'ms)' : 'normal') + ' polling') + (_s.wmode?', wmode: ' + _s.wmode:'') + (_s.debugFlash?', flash debug mode':'') + (_s.useFlashBlock?', flashBlock mode':'') : '') + ' --', 1); + } + + if (_s.html5Only) { + + // 100% HTML5 mode + _setVersionInfo(); + + _initMsg(); + _s.oMC = _id(_s.movieID); + _init(); + + // prevent multiple init attempts + _didAppend = true; + + _appendSuccess = true; + + return false; + + } + + // flash path + var remoteURL = (smURL || _s.url), + localURL = (_s.altURL || remoteURL), + swfTitle = 'JS/Flash audio component (SoundManager 2)', + oEmbed, oMovie, oTarget = _getDocument(), tmp, movieHTML, oEl, extraClass = _getSWFCSS(), + s, x, sClass, side = 'auto', isRTL = null, + html = _doc.getElementsByTagName('html')[0]; + + isRTL = (html && html.dir && html.dir.match(/rtl/i)); + smID = (typeof smID === 'undefined'?_s.id:smID); + + function param(name, value) { + return ''; + } + + // safety check for legacy (change to Flash 9 URL) + _setVersionInfo(); + _s.url = _normalizeMovieURL("inc/SoundManager2/swf/"); + smURL = _s.url; + + _s.wmode = (!_s.wmode && _s.useHighPerformance ? 'transparent' : _s.wmode); + + if (_s.wmode !== null && (_ua.match(/msie 8/i) || (!_isIE && !_s.useHighPerformance)) && navigator.platform.match(/win32|win64/i)) { + /** + * extra-special case: movie doesn't load until scrolled into view when using wmode = anything but 'window' here + * does not apply when using high performance (position:fixed means on-screen), OR infinite flash load timeout + * wmode breaks IE 8 on Vista + Win7 too in some cases, as of January 2011 (?) + */ + _wDS('spcWmode'); + _s.wmode = null; + } + + oEmbed = { + 'name': smID, + 'id': smID, + 'src': smURL, + 'width': side, + 'height': side, + 'quality': 'high', + 'allowScriptAccess': _s.allowScriptAccess, + 'bgcolor': _s.bgColor, + 'pluginspage': _http+'www.macromedia.com/go/getflashplayer', + 'title': swfTitle, + 'type': 'application/x-shockwave-flash', + 'wmode': _s.wmode, + // http://help.adobe.com/en_US/as3/mobile/WS4bebcd66a74275c36cfb8137124318eebc6-7ffd.html + 'hasPriority': 'true' + }; + + if (_s.debugFlash) { + oEmbed.FlashVars = 'debug=1'; + } + + if (!_s.wmode) { + // don't write empty attribute + delete oEmbed.wmode; + } + + if (_isIE) { + + // IE is "special". + oMovie = _doc.createElement('div'); + movieHTML = [ + '', + param('movie', smURL), + param('AllowScriptAccess', _s.allowScriptAccess), + param('quality', oEmbed.quality), + (_s.wmode? param('wmode', _s.wmode): ''), + param('bgcolor', _s.bgColor), + param('hasPriority', 'true'), + (_s.debugFlash ? param('FlashVars', oEmbed.FlashVars) : ''), + '' + ].join(''); + + } else { + + oMovie = _doc.createElement('embed'); + for (tmp in oEmbed) { + if (oEmbed.hasOwnProperty(tmp)) { + oMovie.setAttribute(tmp, oEmbed[tmp]); + } + } + + } + + _initDebug(); + extraClass = _getSWFCSS(); + oTarget = _getDocument(); + + if (oTarget) { + + _s.oMC = (_id(_s.movieID) || _doc.createElement('div')); + + if (!_s.oMC.id) { + + _s.oMC.id = _s.movieID; + _s.oMC.className = _swfCSS.swfDefault + ' ' + extraClass; + s = null; + oEl = null; + + if (!_s.useFlashBlock) { + if (_s.useHighPerformance) { + // on-screen at all times + s = { + 'position': 'fixed', + 'width': '8px', + 'height': '8px', + // >= 6px for flash to run fast, >= 8px to start up under Firefox/win32 in some cases. odd? yes. + 'bottom': '0px', + 'left': '0px', + 'overflow': 'hidden' + }; + } else { + // hide off-screen, lower priority + s = { + 'position': 'absolute', + 'width': '6px', + 'height': '6px', + 'top': '-9999px', + 'left': '-9999px' + }; + if (isRTL) { + s.left = Math.abs(parseInt(s.left,10))+'px'; + } + } + } + + if (_isWebkit) { + // soundcloud-reported render/crash fix, safari 5 + _s.oMC.style.zIndex = 10000; + } + + if (!_s.debugFlash) { + for (x in s) { + if (s.hasOwnProperty(x)) { + _s.oMC.style[x] = s[x]; + } + } + } + + try { + if (!_isIE) { + _s.oMC.appendChild(oMovie); + } + oTarget.appendChild(_s.oMC); + if (_isIE) { + oEl = _s.oMC.appendChild(_doc.createElement('div')); + oEl.className = _swfCSS.swfBox; + oEl.innerHTML = movieHTML; + } + _appendSuccess = true; + } catch(e) { + throw new Error(_str('domError')+' \n'+e.toString()); + } + + } else { + + // SM2 container is already in the document (eg. flashblock use case) + sClass = _s.oMC.className; + _s.oMC.className = (sClass?sClass+' ':_swfCSS.swfDefault) + (extraClass?' '+extraClass:''); + _s.oMC.appendChild(oMovie); + if (_isIE) { + oEl = _s.oMC.appendChild(_doc.createElement('div')); + oEl.className = _swfCSS.swfBox; + oEl.innerHTML = movieHTML; + } + _appendSuccess = true; + + } + + } + + _didAppend = true; + _initMsg(); + _s._wD(_smc+'createMovie(): Trying to load ' + smURL + (!_overHTTP && _s.altURL?' (alternate URL)':''), 1); + + return true; + + }; + + _initMovie = function() { + + if (_s.html5Only) { + _createMovie(); + return false; + } + + // attempt to get, or create, movie + // may already exist + if (_flash) { + return false; + } + + // inline markup case + _flash = _s.getMovie(_s.id); + + if (!_flash) { + if (!_oRemoved) { + // try to create + _createMovie(_s.id, _s.url); + } else { + // try to re-append removed movie after reboot() + if (!_isIE) { + _s.oMC.appendChild(_oRemoved); + } else { + _s.oMC.innerHTML = _oRemovedHTML; + } + _oRemoved = null; + _didAppend = true; + } + _flash = _s.getMovie(_s.id); + } + + // + if (_flash) { + _wDS('waitEI'); + } + // + + if (_s.oninitmovie instanceof Function) { + setTimeout(_s.oninitmovie, 1); + } + + return true; + + }; + + _delayWaitForEI = function() { + + setTimeout(_waitForEI, 1000); + + }; + + _waitForEI = function() { + + if (_waitingForEI) { + return false; + } + + _waitingForEI = true; + _event.remove(_win, 'load', _delayWaitForEI); + + if (_tryInitOnFocus && !_isFocused) { + // giant Safari 3.1 hack - assume mousemove = focus given lack of focus event + _wDS('waitFocus'); + return false; + } + + var p; + if (!_didInit) { + p = _s.getMoviePercent(); + _s._wD(_str('waitImpatient', (p === 100?' (SWF loaded)':(p > 0?' (SWF ' + p + '% loaded)':'')))); + } + + setTimeout(function() { + + p = _s.getMoviePercent(); + + // + if (!_didInit) { + _s._wD(_sm + ': No Flash response within expected time.\nLikely causes: ' + (p === 0?'Loading ' + _s.movieURL + ' may have failed (and/or Flash ' + _fV + '+ not present?), ':'') + 'Flash blocked or JS-Flash security error.' + (_s.debugFlash?' ' + _str('checkSWF'):''), 2); + if (!_overHTTP && p) { + _wDS('localFail', 2); + if (!_s.debugFlash) { + _wDS('tryDebug', 2); + } + } + if (p === 0) { + // if 0 (not null), probably a 404. + _s._wD(_str('swf404', _s.url)); + } + _debugTS('flashtojs', false, ': Timed out' + _overHTTP?' (Check flash security or flash blockers)':' (No plugin/missing SWF?)'); + } + // + + // give up / time-out, depending + + if (!_didInit && _okToDisable) { + if (p === null) { + // SWF failed. Maybe blocked. + if (_s.useFlashBlock || _s.flashLoadTimeout === 0) { + if (_s.useFlashBlock) { + _flashBlockHandler(); + } + _wDS('waitForever'); + } else { + // old SM2 behaviour, simply fail + _failSafely(true); + } + } else { + // flash loaded? Shouldn't be a blocking issue, then. + if (_s.flashLoadTimeout === 0) { + _wDS('waitForever'); + } else { + _failSafely(true); + } + } + } + + }, _s.flashLoadTimeout); + + }; + + _handleFocus = function() { + + function cleanup() { + _event.remove(_win, 'focus', _handleFocus); + _event.remove(_win, 'load', _handleFocus); + } + + if (_isFocused || !_tryInitOnFocus) { + cleanup(); + return true; + } + + _okToDisable = true; + _isFocused = true; + _s._wD(_smc+'handleFocus()'); + + if (_isSafari && _tryInitOnFocus) { + _event.remove(_win, 'mousemove', _handleFocus); + } + + // allow init to restart + _waitingForEI = false; + + cleanup(); + return true; + + }; + + _showSupport = function() { + + var item, tests = []; + + if (_s.useHTML5Audio && _s.hasHTML5) { + for (item in _s.audioFormats) { + if (_s.audioFormats.hasOwnProperty(item)) { + tests.push(item + ': ' + _s.html5[item] + (!_s.html5[item] && _hasFlash && _s.flash[item] ? ' (using flash)' : (_s.preferFlash && _s.flash[item] && _hasFlash ? ' (preferring flash)': (!_s.html5[item] ? ' (' + (_s.audioFormats[item].required ? 'required, ':'') + 'and no flash support)' : '')))); + } + } + _s._wD('-- SoundManager 2: HTML5 support tests ('+_s.html5Test+'): '+tests.join(', ')+' --',1); + } + + }; + + _initComplete = function(bNoDisable) { + + if (_didInit) { + return false; + } + + if (_s.html5Only) { + // all good. + _s._wD('-- SoundManager 2: loaded --'); + _didInit = true; + _initUserOnload(); + _debugTS('onload', true); + return true; + } + + var wasTimeout = (_s.useFlashBlock && _s.flashLoadTimeout && !_s.getMoviePercent()), + error; + + if (!wasTimeout) { + _didInit = true; + if (_disabled) { + error = {type: (!_hasFlash && _needsFlash ? 'NO_FLASH' : 'INIT_TIMEOUT')}; + } + } + + _s._wD('-- SoundManager 2 ' + (_disabled?'failed to load':'loaded') + ' (' + (_disabled?'security/load error':'OK') + ') --', 1); + + if (_disabled || bNoDisable) { + if (_s.useFlashBlock && _s.oMC) { + _s.oMC.className = _getSWFCSS() + ' ' + (_s.getMoviePercent() === null?_swfCSS.swfTimedout:_swfCSS.swfError); + } + _processOnEvents({type:'ontimeout', error:error}); + _debugTS('onload', false); + _catchError(error); + return false; + } else { + _debugTS('onload', true); + } + + if (_s.waitForWindowLoad && !_windowLoaded) { + _wDS('waitOnload'); + _event.add(_win, 'load', _initUserOnload); + return false; + } else { + // + if (_s.waitForWindowLoad && _windowLoaded) { + _wDS('docLoaded'); + } + // + _initUserOnload(); + } + + return true; + + }; + + _init = function() { + + _wDS('init'); + + // called after onload() + + if (_didInit) { + _wDS('didInit'); + return false; + } + + function _cleanup() { + _event.remove(_win, 'load', _s.beginDelayedInit); + } + + if (_s.html5Only) { + if (!_didInit) { + // we don't need no steenking flash! + _cleanup(); + _s.enabled = true; + _initComplete(); + } + return true; + } + + // flash path + _initMovie(); + + try { + + _wDS('flashJS'); + + // attempt to talk to Flash + _flash._externalInterfaceTest(false); + + // apply user-specified polling interval, OR, if "high performance" set, faster vs. default polling + // (determines frequency of whileloading/whileplaying callbacks, effectively driving UI framerates) + _setPolling(true, (_s.flashPollingInterval || (_s.useHighPerformance ? 10 : 50))); + + if (!_s.debugMode) { + // stop the SWF from making debug output calls to JS + _flash._disableDebug(); + } + + _s.enabled = true; + _debugTS('jstoflash', true); + + if (!_s.html5Only) { + // prevent browser from showing cached page state (or rather, restoring "suspended" page state) via back button, because flash may be dead + // http://www.webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/ + _event.add(_win, 'unload', _doNothing); + } + + } catch(e) { + + _s._wD('js/flash exception: ' + e.toString()); + _debugTS('jstoflash', false); + _catchError({type:'JS_TO_FLASH_EXCEPTION', fatal:true}); + // don't disable, for reboot() + _failSafely(true); + _initComplete(); + + return false; + + } + + _initComplete(); + + // disconnect events + _cleanup(); + + return true; + + }; + + _domContentLoaded = function() { + + if (_didDCLoaded) { + return false; + } + + _didDCLoaded = true; + _initDebug(); + + /** + * Temporary feature: allow force of HTML5 via URL params: sm2-usehtml5audio=0 or 1 + * Ditto for sm2-preferFlash, too. + */ + // + (function(){ + + var a = 'sm2-usehtml5audio=', l = _wl.toLowerCase(), b = null, + a2 = 'sm2-preferflash=', b2 = null, hasCon = (typeof console !== 'undefined' && typeof console.log !== 'undefined'); + + if (l.indexOf(a) !== -1) { + b = (l.charAt(l.indexOf(a)+a.length) === '1'); + if (hasCon) { + console.log((b?'Enabling ':'Disabling ')+'useHTML5Audio via URL parameter'); + } + _s.useHTML5Audio = b; + } + + if (l.indexOf(a2) !== -1) { + b2 = (l.charAt(l.indexOf(a2)+a2.length) === '1'); + if (hasCon) { + console.log((b2?'Enabling ':'Disabling ')+'preferFlash via URL parameter'); + } + _s.preferFlash = b2; + } + + }()); + // + + if (!_hasFlash && _s.hasHTML5) { + _s._wD('SoundManager: No Flash detected'+(!_s.useHTML5Audio?', enabling HTML5.':'. Trying HTML5-only mode.')); + _s.useHTML5Audio = true; + // make sure we aren't preferring flash, either + // TODO: preferFlash should not matter if flash is not installed. Currently, stuff breaks without the below tweak. + _s.preferFlash = false; + } + + _testHTML5(); + _s.html5.usingFlash = _featureCheck(); + _needsFlash = _s.html5.usingFlash; + _showSupport(); + + if (!_hasFlash && _needsFlash) { + _s._wD('SoundManager: Fatal error: Flash is needed to play some required formats, but is not available.'); + // TODO: Fatal here vs. timeout approach, etc. + // hack: fail sooner. + _s.flashLoadTimeout = 1; + } + + if (_doc.removeEventListener) { + _doc.removeEventListener('DOMContentLoaded', _domContentLoaded, false); + } + + _initMovie(); + return true; + + }; + + _domContentLoadedIE = function() { + + if (_doc.readyState === 'complete') { + _domContentLoaded(); + _doc.detachEvent('onreadystatechange', _domContentLoadedIE); + } + + return true; + + }; + + _winOnLoad = function() { + // catch edge case of _initComplete() firing after window.load() + _windowLoaded = true; + _event.remove(_win, 'load', _winOnLoad); + }; + + // sniff up-front + _detectFlash(); + + // focus and window load, init (primarily flash-driven) + _event.add(_win, 'focus', _handleFocus); + _event.add(_win, 'load', _handleFocus); + _event.add(_win, 'load', _delayWaitForEI); + _event.add(_win, 'load', _winOnLoad); + + + if (_isSafari && _tryInitOnFocus) { + // massive Safari 3.1 focus detection hack + _event.add(_win, 'mousemove', _handleFocus); + } + + if (_doc.addEventListener) { + + _doc.addEventListener('DOMContentLoaded', _domContentLoaded, false); + + } else if (_doc.attachEvent) { + + _doc.attachEvent('onreadystatechange', _domContentLoadedIE); + + } else { + + // no add/attachevent support - safe to assume no JS -> Flash either + _debugTS('onload', false); + _catchError({type:'NO_DOM2_EVENTS', fatal:true}); + + } + + if (_doc.readyState === 'complete') { + // DOMReady has already happened. + setTimeout(_domContentLoaded,100); + } + +} // SoundManager() + +// SM2_DEFER details: http://www.schillmania.com/projects/soundmanager2/doc/getstarted/#lazy-loading + +if (typeof SM2_DEFER === 'undefined' || !SM2_DEFER) { + soundManager = new SoundManager(); +} + +/** + * SoundManager public interfaces + * ------------------------------ + */ + +window.SoundManager = SoundManager; // constructor +window.soundManager = soundManager; // public API, flash callbacks etc. + +}(window)); \ No newline at end of file diff --git a/inc/SoundManager2/swf/soundmanager2.swf b/inc/SoundManager2/swf/soundmanager2.swf new file mode 100755 index 0000000..14850f2 Binary files /dev/null and b/inc/SoundManager2/swf/soundmanager2.swf differ diff --git a/inc/SoundManager2/swf/soundmanager2_debug.swf b/inc/SoundManager2/swf/soundmanager2_debug.swf new file mode 100755 index 0000000..aa4750a Binary files /dev/null and b/inc/SoundManager2/swf/soundmanager2_debug.swf differ diff --git a/inc/SoundManager2/swf/soundmanager2_flash9.swf b/inc/SoundManager2/swf/soundmanager2_flash9.swf new file mode 100755 index 0000000..2705986 Binary files /dev/null and b/inc/SoundManager2/swf/soundmanager2_flash9.swf differ diff --git a/inc/SoundManager2/swf/soundmanager2_flash9_debug.swf b/inc/SoundManager2/swf/soundmanager2_flash9_debug.swf new file mode 100755 index 0000000..243d649 Binary files /dev/null and b/inc/SoundManager2/swf/soundmanager2_flash9_debug.swf differ diff --git a/inc/SoundManager2/swf/soundmanager2_flash_xdomain.zip b/inc/SoundManager2/swf/soundmanager2_flash_xdomain.zip new file mode 100755 index 0000000..29737aa Binary files /dev/null and b/inc/SoundManager2/swf/soundmanager2_flash_xdomain.zip differ diff --git a/inc/midibridge/README b/inc/midibridge/README new file mode 100644 index 0000000..7a71651 --- /dev/null +++ b/inc/midibridge/README @@ -0,0 +1,39 @@ +The midibridge is a Javascript API for interacting with the midi devices on your computer. + +It provides methods for detecting the midi devices and for connecting these devices with each other. + +The midibridge itself is considered a midi device as well, so it can be connected to the detected devices. + +The midibridge can generate and send midi events to midi output devices, and receive midi events from midi input devices. + +The midibridge can also filter and alter midi events. + +Recording and playing back midi events with a sequencer will be added in later versions. + +A midi output device is a physical output port on your computer, a virtual output port or a software synthesizer. It can also be a sequencer, a file or a function. + +A midi input device is a physical or virtual input port, a sequencer, a file or a function. + +A midi device can be both in- and output. The midibridge itself for instance is both in- and output because it can send and receive midi events. + +The actual interaction with the midi devices on your computer is done by a Java applet. The midibridge automatically adds the applet to your webpage. + +The midibridge has no visual parts, it is 'headless' code. You could say the midibridge enables you to write a 'front-end' on top of the applet. + +Midi Devices -> Java Applet -> Javascript Midibridge API -> a GUI in Javascript, Flash, SVG, C# (Silverlight) + +Because the midibridge is written in native Javascript, you can use it conflict-free with any Javascript framework. + + +The only files you need to get started are: + +/lib/midibridge-0.5.1.min.js +/java/midiapplet.jar + + +/lib/MidiBridge.js is the non-minified version of /lib/midibridge-0.5.1.min.js + +The other files and notably the files in the /js folder are code snippets that i have used in the quick start guide and the documentation on my blogpost, see: + +http://www.abumarkub.net/abublog/?p=399 + diff --git a/inc/midibridge/index.html b/inc/midibridge/index.html new file mode 100644 index 0000000..0808ae1 --- /dev/null +++ b/inc/midibridge/index.html @@ -0,0 +1,83 @@ + + + + + + + + + + \ No newline at end of file diff --git a/inc/midibridge/java/midiapplet.jar b/inc/midibridge/java/midiapplet.jar new file mode 100644 index 0000000..ea4e6e9 Binary files /dev/null and b/inc/midibridge/java/midiapplet.jar differ diff --git a/inc/midibridge/lib/MidiBridge.js b/inc/midibridge/lib/MidiBridge.js new file mode 100644 index 0000000..fe9f8e2 --- /dev/null +++ b/inc/midibridge/lib/MidiBridge.js @@ -0,0 +1,502 @@ +/** + * This version is supported by all browsers that support native JSON parsing: + * - Firefox 3.5+ + * - Chrome 4.0+ + * - Safari 4.0+ + * - Opera 10.5+ + * - Internet Explorer 8.0+ + * + * If you want this version to work with other browsers, you can use the JSON parsing methods of your favorite Javascript + * framework (e.g. jQuery, Dojo, YUI, Mootools, etc.) + * + * Note for IE8 users: if you include MidiBridge.js (or preferably the minified version of it: midibridge-0.5.min.js) in your html, + * the method addEventListener will be added to the window object. In fact this method is just a wrapper around the attachEvent method, + * see code at the bottom of this file. + */ + +(function() { + var midiBridge = { + NOTE_OFF : 0x80, //128 + NOTE_ON : 0x90, //144 + POLY_PRESSURE : 0xA0, //160 + CONTROL_CHANGE : 0xB0, //176 + PROGRAM_CHANGE : 0xC0, //192 + CHANNEL_PRESSURE : 0xD0, //208 + PITCH_BEND : 0xE0, //224 + SYSTEM_EXCLUSIVE : 0xF0, //240 + NOTE_NAMES_SHARP : "sharp", + NOTE_NAMES_FLAT : "flat", + NOTE_NAMES_SOUNDFONT : "soundfont", + NOTE_NAMES_ENHARMONIC_SHARP : "enh-sharp", + NOTE_NAMES_ENHARMONIC_FLAT : "enh-flat" + + }; + //human readable representation of status byte midi data + var status = []; + status[0x80] = "NOTE OFF"; + status[0x90] = "NOTE ON"; + status[0xA0] = "POLY PRESSURE"; + status[0xB0] = "CONTROL CHANGE"; + status[0xC0] = "PROGRAM CHANGE"; + status[0xD0] = "CHANNEL PRESSURE"; + status[0xE0] = "PITCH BEND"; + status[0xF0] = "SYSTEM EXCLUSIVE"; + //notenames in different modi + var noteNames = { + "sharp" : ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"], + "flat" : ["C", "Dâ™­", "D", "Eâ™­", "E", "F", "Gâ™­", "G", "Aâ™­", "A", "Bâ™­", "B"], + "soundfont" : ["C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B"], + "enh-sharp" : ["B#", "C#", "C##", "D#", "D##", "E#", "F#", "F##", "G#", "G##", "A#", "A##"], + "enh-flat" : ["Dâ™­â™­", "Dâ™­", "Eâ™­â™­", "Eâ™­", "Fâ™­", "Gâ™­â™­", "Gâ™­", "Aâ™­â™­", "Aâ™­", "Bâ™­", "Bâ™­", "Câ™­"] + } + //variable that holds a reference to the JSON parser method of your liking, defaults to native JSON parsing + var parseJSON = JSON.parse; + //method that gets called when midi note events arrive from the applet + var ondata = null; + var onerror = null; + var onready = null; + //the applet object + var applet = null; + var connectAllInputs = false; + var connectFirstInput = false; + var connectFirstOutput = false; + var connectAllInputsToFirstOutput = true; + var javaDir = "java"; + var devices = {}; + midiBridge.version = "0.5.1"; + midiBridge.ready = false; + midiBridge.noteNameModus = midiBridge.NOTE_NAMES_SHARP; + + /** + * static method called to initialize the MidiBridge + * possible arguments: + * 1) callback [function] callback when midi data has arrived + * 2) config object + * - ready : [function] callback when midibridge is ready/initialized + * - error : [function] callback in case of an error + * - data : [function] callback when midi data has arrived + * - connectAllInputs : [true,false] all found midi input devices get connected automatically + * - connectFirstInput : [true,false] the first found midi input device gets connected automatically + * - connectFirstOutput : [true,false] the first found midi output device gets connected automatically + * - connectAllInputsToFirstOutput : [true,false] all found midi input devices will be automatically connected to the first found midi output device + * - javaDir : [string] the folder where you store the midiapplet.jar on your webserver, defaults to "java" + */ + midiBridge.init = function(arg) { + + //var args = Array.prototype.slice.call(arguments); + if( typeof arg === "function") { + ondata = arg; + } else if( typeof arg === "object") { + var config = arg; + connectAllInputs = config.connectAllInputs; + connectFirstInput = config.connectFirstInput; + connectFirstOutput = config.connectFirstOutput; + connectAllInputsToFirstOutput = config.connectAllInputsToFirstOutput; + ondata = config.data; + onready = config.ready; + onerror = config.error; + switch(true) { + case connectAllInputs && connectFirstOutput: + connectAllInputs = false; + connectFirstInput = false; + connectFirstOutput = false; + connectAllInputsToFirstOutput = true; + break; + case connectAllInputsToFirstOutput: + connectAllInputs = false; + connectFirstInput = false; + connectFirstInput = false; + connectFirstOutput = false; + break; + case connectFirstInput: + connectAllInputs = false; + connectAllInputsToFirstOutput = false; + break; + case connectFirstOutput: + connectAllInputs = false; + connectAllInputsToFirstOutput = false; + break; + case connectAllInputs: + connectFirstInput = false; + connectFirstOutput = false; + connectAllInputsToFirstOutput = false; + break; + } + } + + /** + * Very simple java plugin detection + */ + if(!navigator.javaEnabled()) { + if(onerror) { + onerror("no java plugin found; install or enable the java plugin") + } else { + console.log("no java plugin found; install or enable the java plugin"); + } + return; + } + + /** + * If you are using the JSON parse method of your favorite Javascript framework replace the followingn lines by onlu: + * + * loadJava(); + */ + + loadJava(); + + }; + + /** + * static method called by the applet + */ + midiBridge.msgFromJava = function(jsonString) { + var data = parseJSON(jsonString); + var msgId = data.msgId; + //console.log(jsonString); + //console.log(msgId); + switch(msgId) { + case "upgrade-java": + if(onerror) { + onerror("please upgrade your java plugin!") + } else { + console.log("please upgrade your java plugin!"); + } + break; + case "midi-started": + getApplet(); + if(applet) { + devices = data.devices; + midiBridge.ready = true; + if(connectAllInputs) { + midiBridge.connectAllInputs(); + } + if(connectFirstInput) { + midiBridge.connectFirstInput(); + } + if(connectFirstOutput) { + midiBridge.connectFirstOutput(); + } + if(connectAllInputsToFirstOutput) { + midiBridge.connectAllInputsToFirstOutput(); + } + if(onready) { + onready("midibridge started"); + } + } + //console.log("applet:",applet); + break; + case "midi-data": + if(ondata) { + ondata(new MidiMessage(data)); + } + break; + case "error": + if(onerror) { + onerror(data.code); + } + break; + } + }; + + /** + * Send a midi event from javascript to java + * @param status : the midi status byte, e.g. NOTE ON, NOTE OFF, PITCH BEND and so on + * @param channel : the midi channel that this event will be sent to 0 - 15 + * @param data1 : the midi note number + * @param data2 : the second data byte, when the status byte is NOTE ON or NOTE OFF, data2 is the velocity + */ + midiBridge.sendMidiEvent = function(status, channel, data1, data2) { + if(checkIfReady()) { + return parseJSON(applet.processMidiEvent(status, channel, data1, data2)); + } + }; + + /** + * Get the list of all currently connected midi devices + */ + midiBridge.getDevices = function() { + return devices; + }; + + /** + * Refresh the list of all currently connected midi devices + */ + midiBridge.refreshDevices = function() { + if(checkIfReady()) { + return parseJSON(applet.getDevices()); + } + }; + + /** + * Connect all found midi inputs to the midibridge right after the midibridge has been initialized + */ + midiBridge.connectAllInputs = function() { + if(checkIfReady()) { + return parseJSON(applet.connectAllInputs()); + } + }; + + /** + * Connect the first found midi input to the midibridge right after the midibridge has been initialized + */ + midiBridge.connectFirstInput = function() { + if(checkIfReady()) { + return parseJSON(applet.connectFirstInput()); + } + }; + + /** + * Connect the first found midi output to the midibridge right after the midibridge has been initialized + */ + midiBridge.connectFirstOutput = function() { + if(checkIfReady()) { + return parseJSON(applet.connectFirstOutput()); + } + }; + + /** + * Connect the first found midi output to all connected midi inputs right after the midibridge has been initialized + */ + midiBridge.connectAllInputsToFirstOutput = function() { + if(checkIfReady()) { + return parseJSON(applet.connectAllInputsToFirstOutput()); + } + }; + + /** + * Connect midi a midi input to the bridge, and/or a midi input to a midi output + * @param midiInId : [int] id of the midi input that will be connected to the bridge, use the ids as retrieved by getDevices() + * @param midiOutId : [int] optional, the id of the midi output that will be connected to the chosen midi input + * @param filter : [array] an array containing status codes that will *not* be sent from the chosen midi input to the chosen midi output + * e.g. if you supply the array [midiBridge.PITCH_BEND, midiBridge.POLY_PRESSURE], pitch bend and poly pressure midi messages will not be forwarded to the output + */ + midiBridge.addConnection = function(midiInId, midiOutId, filter) { + if(checkIfReady()) { + midiOutId = midiOutId == undefined ? -1 : midiOutId; + filter = filter == undefined ? [] : filter; + return parseJSON(applet.addConnection(midiInId, midiOutId, filter)); + } + }; + + /** + * Remove a midi connection between between an input and the midibridge, and/or the given in- and output + * @param midiIdIn : [int] the midi input + * @param midiIdOut : [int] optional, the midi output + */ + midiBridge.removeConnection = function(midiInId, midiOutId) { + if(checkIfReady()) { + return parseJSON(applet.removeConnection(midiInId, midiOutId)); + } + }; + + /** + * All previously setup midi connections will be disconnected + */ + midiBridge.disconnectAll = function() { + if(checkIfReady()) { + return parseJSON(applet.disconnectAll()); + } + }; + + midiBridge.loadBase64String = function(data){ + return parseJSON(applet.loadBase64String(data)); + } + + midiBridge.playBase64String = function(data){ + return parseJSON(applet.playBase64String(data)); + } + + midiBridge.loadMidiFile = function(url){ + return parseJSON(applet.loadMidiFile(url)); + } + + midiBridge.playMidiFile = function(url){ + return parseJSON(applet.playMidiFile(url)); + } + + midiBridge.startSequencer = function(){ + applet.startSequencer(); + } + + midiBridge.pauseSequencer = function(){ + applet.pauseSequencer(); + } + + midiBridge.stopSequencer = function(){ + applet.stopSequencer(); + } + + midiBridge.closeSequencer = function(){ + applet.closeSequencer(); + } + + midiBridge.getSequencerPosition = function(){ + return applet.getSequencerPosition(); + } + + midiBridge.setSequencerPosition = function(pos){ + applet.setSequencerPosition(pos); + } + + /** + * Check if a midiBridge function is called before initialization + */ + function checkIfReady() { + if(!midiBridge.ready) { + if(onerror) { + onerror("midibridge not ready!"); + } + return "midibridge not ready!"; + } + return true; + } + + /** + * A div with the applet object is added to the body of your html document + */ + function loadJava() { + //console.log("loadJava"); + var javaDiv = document.createElement("div"); + javaDiv.setAttribute("id", "midibridge-java"); + var html = ""; + html += ''; + html += ''; + html += ''; + html += ''; + html += ''; + html += ''; + //html += 'Your browser needs the Java plugin to use the midibridge. You can download it here'; + html += ''; + javaDiv.innerHTML = html; + document.body.appendChild(javaDiv); + } + + /** + * class MidiMessage is used to wrap the midi note data that arrives from the applet + */ + var MidiMessage = (function()//constructor + { + var _constructor = function(data) { + this.data1 = data.data1; + this.data2 = data.data2; + this.status = data.status; + this.status = this.data2 == 0 && this.status == midiBridge.NOTE_ON ? midiBridge.NOTE_OFF : this.status; + this.channel = data.channel; + this.noteName = midiBridge.getNoteName(this.data1, midiBridge.noteNameModus); + this.statusCode = midiBridge.getStatus(this.status); + this.microsecond = data.microsecond; + this.time = midiBridge.getNiceTime(this.microsecond); + }; + + _constructor.prototype = { + toString : function() { + var s = ""; + s += this.noteName + " " + this.statusCode + " " + this.data1 + " " + this.data2 + " " + this.status; + s += this.microsecond ? this.microsecond + " " + this.time : ""; + //console.log(s); + return s; + }, + toJSONString : function() { + var s; + if(this.microsecond){ + s= "{'notename':" + this.noteName + ", 'status':" + this.status + ", 'data1':" + this.data1 + ", 'data2':" + this.data2 + ", 'microsecond':" + this.microsecond + ", 'time':" + this.time + "}"; + }else{ + s= "{'notename':" + this.noteName + ", 'status':" + this.status + ", 'data1':" + this.data1 + ", 'data2':" + this.data2 + "}"; + } + //console.log(s); + return s; + } + } + + return _constructor; + })(); + + + midiBridge.getNoteName = function(noteNumber, mode) { + + var octave = Math.floor(((noteNumber) / 12) - 1); + var noteName = noteNames[mode][noteNumber % 12]; + return noteName + "" + octave; + }; + + + midiBridge.getNoteNumber = function(noteName, octave) { + var index = -1; + noteName = noteName.toUpperCase(); + for(var key in noteNames) { + var modus = noteNames[key]; + for(var i = 0, max = modus.length; i < max; i++) { + if(modus[i] === noteName) { + index = i; + break; + } + } + } + if(index === -1) { + return "invalid note name"; + } + noteNumber = (12 + index) + (octave * 12); + return noteNumber; + } + + + midiBridge.getStatus = function($statusCode) { + return status[$statusCode]; + }; + + midiBridge.getNiceTime = function(microseconds) + { + //console.log(microseconds); + var r = ""; + + var t = (microseconds / 1000 / 1000) >> 0; + var h = (t / (60 * 60)) >> 0; + var m = ((t % (60 * 60)) / 60) >> 0; + var s = t % (60); + var ms = (((microseconds /1000) - (h * 3600000) - (m * 60000) - (s * 1000)) + 0.5) >> 0; + + //console.log(t,h,m,s,ms); + + r += h > 0 ? h + ":" : ""; + r += h > 0 ? m < 10 ? "0" + m : m : m; + r += ":"; + r += s < 10 ? "0" + s : s; + r += ":"; + r += ms == 0 ? "000" : ms < 10 ? "00" + ms : ms < 100 ? "0" + ms : ms; + + return r; + } + + + function getApplet() { + try { + applet = midiBridge.getObject("midibridge-applet"); + } catch(e) { + //console.log(e) + //Firefox needs more time to initialize the Applet + setTimeout(getApplet, 25); + return; + } + } + + midiBridge.getObject = function(objectName) { + var ua = navigator.userAgent.toLowerCase(); + //console.log(ua); + if(ua.indexOf("msie") !== -1 || ua.indexOf("webkit") !== -1) { + return window[objectName]; + } else { + return document[objectName]; + } + } + + //add addEventListener to IE8 + if(!window.addEventListener) { + window.addEventListener = function($id, $callback, $bubble) { + window.attachEvent('onload', $callback); + } + + } + + window.midiBridge = midiBridge; + +})(window); \ No newline at end of file diff --git a/js/Color.js b/js/Color.js new file mode 100644 index 0000000..11428b2 --- /dev/null +++ b/js/Color.js @@ -0,0 +1,154 @@ +/* + + Color.Space : 0.3 : mudcu.be + ----------------------------- + STRING <-> HEX <-> RGB <-> HSL + ----------------------------- + var HEX = 0xFF0000; + var HSL = Color.Space(HEX, "HEX>RGB>HSL"); + +*/ + +if (!window.Color) Color = {}; +if (!window.Color.Space) Color.Space = {}; + +(function () { + +var DEG_RAD = Math.PI / 180; +var RAD_DEG = 1 / DEG_RAD; + +var shortcuts = { }; +var root = Color.Space = function(color, route) { + if (shortcuts[route]) { + route = shortcuts[route]; + } + var arr = route.split(">"); + var key = ""; + for (var n = 0; n < arr.length; n ++) { + if (n > 1) { + key = key.split("_"); + key.shift(); + key = key.join("_"); + } + key += (n == 0 ? "" : "_") + arr[n]; + if (n > 0) color = root[key](color); + } + return color; +}; + +// STRING = 'FFFFFF' | 'FFFFFFFF' + +root.STRING_HEX = function (o) { + return parseInt('0x' + o); +}; + +// HEX = 0x000000 -> 0xFFFFFF + +root.HEX_STRING = function (o, maxLength) { + if (!maxLength) maxLength = 6; + if (!o) o = 0; + var z = o.toString(16); + // when string is lesser than maxLength + var n = z.length; + while (n < maxLength) { + z = '0' + z; + n++; + } + // when string is greater than maxLength + var n = z.length; + while (n > maxLength) { + z = z.substr(1); + n--; + } + return z; +}; + +root.HEX_RGB = function (o) { + return { + R: (o >> 16), + G: (o >> 8) & 0xFF, + B: o & 0xFF + }; +}; + +// RGB = R: Red / G: Green / B: Blue + +root.RGB_HEX = function (o) { + if (o.R < 0) o.R = 0; + if (o.G < 0) o.G = 0; + if (o.B < 0) o.B = 0; + if (o.R > 255) o.R = 255; + if (o.G > 255) o.G = 255; + if (o.B > 255) o.B = 255; + return o.R << 16 | o.G << 8 | o.B; +}; + +root.RGB_HSL = function (o) { // RGB from 0 to 1 + // http://www.easyrgb.com/index.php?X=MATH&H=18#text18 + var _R = o.R / 255, + _G = o.G / 255, + _B = o.B / 255, + min = Math.min(_R, _G, _B), + max = Math.max(_R, _G, _B), + D = max - min, + H, + S, + L = (max + min) / 2; + if (D == 0) { // No chroma + H = 0; + S = 0; + } else { // Chromatic data + if (L < 0.5) S = D / (max + min); + else S = D / (2 - max - min); + var DR = (((max - _R) / 6) + (D / 2)) / D; + var DG = (((max - _G) / 6) + (D / 2)) / D; + var DB = (((max - _B) / 6) + (D / 2)) / D; + if (_R == max) H = DB - DG; + else if (_G == max) H = (1 / 3) + DR - DB; + else if (_B == max) H = (2 / 3) + DG - DR; + if (H < 0) H += 1; + if (H > 1) H -= 1; + } + return { + H: H * 360, + S: S * 100, + L: L * 100 + }; +}; + +// HSL (1978) = H: Hue / S: Saturation / L: Lightess + +root.HSL_RGB = function (o) { + // http://www.easyrgb.com/index.php?X=MATH&H=19 + var H = o.H / 360, + S = o.S / 100, + L = o.L / 100, + R, G, B, _1, _2; + function Hue_2_RGB(v1, v2, vH) { + if (vH < 0) vH += 1; + if (vH > 1) vH -= 1; + if ((6 * vH) < 1) return v1 + (v2 - v1) * 6 * vH; + if ((2 * vH) < 1) return v2; + if ((3 * vH) < 2) return v1 + (v2 - v1) * ((2 / 3) - vH) * 6; + return v1; + } + if (S == 0) { // HSL from 0 to 1 + R = L * 255; + G = L * 255; + B = L * 255; + } else { + if (L < 0.5) _2 = L * (1 + S); + else _2 = (L + S) - (S * L); + _1 = 2 * L - _2; + R = 255 * Hue_2_RGB(_1, _2, H + (1 / 3)); + G = 255 * Hue_2_RGB(_1, _2, H); + B = 255 * Hue_2_RGB(_1, _2, H - (1 / 3)); + } + return { + R: R, + G: G, + B: B + }; +}; + +})(); \ No newline at end of file diff --git a/js/DOMLoader.XMLHttp.js b/js/DOMLoader.XMLHttp.js new file mode 100644 index 0000000..99b48e0 --- /dev/null +++ b/js/DOMLoader.XMLHttp.js @@ -0,0 +1,126 @@ +/* + + DOMLoader.XMLHttp : 0.1 : mudcu.be + ----------------------------------- + DOMLoader.sendRequest({ + url: "./dir/something.extension", + error: function(event) { + console.log(event); + }, + callback: function(response) { + console.log(response.responseText); + }, + progress: function (event) { + var percent = event.loaded / event.total * 100 >> 0; + loader.message("loading: " + percent + "%"); + } + }); + +*/ + +if (typeof(DOMLoader) === "undefined") DOMLoader = {}; + +(function() { "use strict"; + +// Add XMLHttpRequest when not available + +if (typeof (window.XMLHttpRequest) === "undefined") { + (function () { // http://www.quirksmode.org/js/xmlhttp.html + var factories = [ + function () { + return new ActiveXObject("Msxml2.XMLHTTP"); + }, function () { + return new ActiveXObject("Msxml3.XMLHTTP"); + }, function () { + return new ActiveXObject("Microsoft.XMLHTTP"); + }]; + for (var i = 0; i < factories.length; i++) { + try { + factories[i](); + } catch (e) { + continue; + } + break; + } + window.XMLHttpRequest = factories[i]; + })(); +} + +if (typeof ((new XMLHttpRequest()).responseText) === "undefined") { + // http://stackoverflow.com/questions/1919972/how-do-i-access-xhr-responsebody-for-binary-data-from-javascript-in-ie + var IEBinaryToArray_ByteStr_Script = + "\r\n"+ + "\r\n"; + + // inject VBScript + document.write(IEBinaryToArray_ByteStr_Script); + + DOMLoader.sendRequest = function(config) { + // helper to convert from responseBody to a "responseText" like thing + function getResponseText(binary) { + var byteMapping = {}; + for (var i = 0; i < 256; i++) { + for (var j = 0; j < 256; j++) { + byteMapping[String.fromCharCode(i + j * 256)] = String.fromCharCode(i) + String.fromCharCode(j); + } + } + // call into VBScript utility fns + var rawBytes = IEBinaryToArray_ByteStr(binary); + var lastChr = IEBinaryToArray_ByteStr_Last(binary); + return rawBytes.replace(/[\s\S]/g, function (match) { + return byteMapping[match]; + }) + lastChr; + } + // + var req = new XMLHttpRequest(); + req.open("GET", config.url, true); + req.setRequestHeader("Accept-Charset", "x-user-defined"); + if (config.responseType) req.responseType = config.responseType; + if (config.error) req.onerror = config.error; + if (config.progress) req.onprogress = config.progress; + req.onreadystatechange = function (event) { + if (req.readyState === 4) { + if (req.status === 200) { + req.responseText = getResponseText(req.responseBody); + } else { + req = false; + } + if (config.callback) config.callback(req); + } + }; + req.send(null); + return req; + } +} else { + DOMLoader.sendRequest = function(config) { + var req = new XMLHttpRequest(); + req.open('GET', config.url, true); + if (req.overrideMimeType) req.overrideMimeType("text/plain; charset=x-user-defined"); + if (config.responseType) req.responseType = config.responseType; + if (config.error) req.onerror = config.error; + if (config.progress) req.onprogress = config.progress; + req.onreadystatechange = function (event) { + if (req.readyState === 4) { + if (req.status !== 200) req = false; + if (config.callback) config.callback(req); + } + }; + req.send(""); + return req; + }; +} + +})(); \ No newline at end of file diff --git a/js/DOMLoader.script.js b/js/DOMLoader.script.js new file mode 100644 index 0000000..3474983 --- /dev/null +++ b/js/DOMLoader.script.js @@ -0,0 +1,131 @@ +/* + + DOMLoader : 0.2 : mudcu.be + --------------------------- + DOMLoader.script.add({ + strictOrder: true, + srcs: [ + { + src: "../js/jszip/jszip.js", + verify: "JSZip", + callback: function() { + console.log(1) + } + }, + { + src: "../inc/downloadify/js/swfobject.js", + verify: "swfobject", + callback: function() { + console.log(2) + } + } + ], + callback: function() { + console.log(3) + } + }); + +*/ + +if (typeof(DOMLoader) === "undefined") DOMLoader = {}; + +DOMLoader.script = function() { + this.loaded = {}; + this.loading = {}; + return this; +}; + +DOMLoader.script.prototype.add = function(config) { + var that = this; + var srcs = config.srcs; + if (typeof(srcs) === "undefined") { + srcs = [{ + src: config.src, + verify: config.verify + }]; + } + /// adding the elements to the head + var doc = document.getElementsByTagName("head")[0]; + /// + var testElement = function(element, test) { + if (that.loaded[element.src]) return; + if (test && !eval(test)) return; + that.loaded[element.src] = true; + // + if (that.loading[element.src]) that.loading[element.src](); + delete that.loading[element.src]; + // + if (element.callback) element.callback(); + if (typeof(getNext) !== "undefined") getNext(); + }; + /// + var batchTest = []; + var addElement = function(element) { + if (/([\w\d.\[\]])$/.test(element.verify)) { // check whether its a variable reference + element.test = "(typeof(" + element.verify + ") !== \"undefined\")"; + batchTest.push(element.test); + } + var script = document.createElement("script"); + script.onreadystatechange = function() { + if (this.readyState !== "loaded" && this.readyState !== "complete") return; + testElement(element); + }; + script.onload = function() { + testElement(element); + }; + script.setAttribute("type", "text/javascript"); + script.setAttribute("src", element.src); + doc.appendChild(script); + that.loading[element.src] = function() {}; + }; + /// checking to see whether everything loaded properly + var onLoad = function(element) { + if (element) { + testElement(element, element.test); + } else { + for (var n = 0; n < srcs.length; n ++) { + testElement(srcs[n], srcs[n].test); + } + } + if (!config.strictOrder && eval(batchTest.join(" && "))) { // finished loading all the requested scripts + if (config.callback) config.callback(); + } else { // keep calling back the function + setTimeout(function() { //- should get slower over time? + onLoad(element); + }, 10); + } + }; + /// loading methods; strict ordering or loose ordering + if (config.strictOrder) { + var ID = -1; + var getNext = function() { + ID ++; + if (!srcs[ID]) { // all elements are loaded + if (config.callback) config.callback(); + } else { // loading new script + var element = srcs[ID]; + var src = element.src; + if (that.loading[src]) { // already loading from another call (attach to event) + that.loading[src] = function() { + if (element.callback) element.callback(); + getNext(); + } + } else if (!that.loaded[src]) { // create script element + addElement(element); + onLoad(element); + } else { // it's already been successfully loaded + getNext(); + } + } + }; + getNext(); + } else { // loose ordering + for (var ID = 0; ID < srcs.length; ID ++) { + if (that.loaded[srcs[ID].src]) return; + addElement(srcs[ID]); + } + onLoad(); + } +}; + +DOMLoader.script = (new DOMLoader.script()); \ No newline at end of file diff --git a/js/Event.Mouse.js b/js/Event.Mouse.js new file mode 100644 index 0000000..fdf5e0f --- /dev/null +++ b/js/Event.Mouse.js @@ -0,0 +1,155 @@ +/* + + Event.Mouse : 0.3.1 : mudcu.be + ------------------------------------- + Event.add(document, "mousedown", function(event) { + Event.drag({ + type: "absolute", + event: event, + element: document, + callback: function (event, coords, state, self) { + Event.stopPropagation(event); + Event.preventDefault(event); + console.log(coords); + } + }); + }); + + // this does the same thing + Event.drag({ + type: "absolute", + element: document, + callback: function (event, coords, state, self) { + console.log(coords); + } + }); + + /// easier mousewheel events + Event.mousewheel(window, function(event, state, wheelData, self) { + self.stop.prevent.remove(); + }); + +*/ + +if (typeof(Event) === "undefined") var Event = {}; + +Event.drag = +Event.dragElement = function(props) { + var el = props.element || document.body; + var doc = el.ownerDocument; // could be within an iframe + if (typeof(props.event) === "undefined") { // create event + Event.add(el, "mousedown", function(event) { + props.event = event; + Event.dragElement(props); + Event.preventDefault(event); + Event.stopPropagation(event); + }); + return; + } + // functions accessible externally + var self = { + cancel: function() { + Event.remove(doc, "mousemove", mouseMove); + Event.remove(doc, "mouseup", mouseUp); + } + }; + // event move + var mouseMove = function (event, state) { + if (typeof(state) === "undefined") state = "move"; + var coord = Event.coords(event); + switch (props.type) { + case "move": // move + props.callback(event, { + x: coord.x + oX - eX, + y: coord.y + oY - eY + }, state, self); + break; + case "difference": // relative, from position within element + props.callback(event, { + x: coord.x - oX, + y: coord.y - oY + }, state, self); + break; + case "relative": // eveything is relative from origin + props.callback(event, { + x: coord.x - eX, + y: coord.y - eY + }, state, self); + break; + default: // "absolute", origin is 0x0 + props.callback(event, { + x: coord.x, + y: coord.y + }, state, self); + break; + } + }; + // event up + var mouseUp = function(event) { + self.cancel(); + mouseMove(event, "up"); + }; + // current element position + var origin = abPos(el); + var oX = origin.x; + var oY = origin.y; + // current mouse position + var event = props.event; + var coord = Event.coords(event); + var eX = coord.x; + var eY = coord.y; + // events + Event.add(doc, "mousemove", mouseMove); + Event.add(doc, "mouseup", mouseUp); + mouseMove(event, "down"); // run mouse-down + // + return self; +}; + +Event.coords = (function() { + if (window.ActiveXObject) { + return function(event) { + return { + x: event.clientX + document.documentElement.scrollLeft, + y: event.clientY + document.documentElement.scrollTop + }; + }; + } else { + return function(event) { + return { + x: event.pageX, + y: event.pageY + }; + }; + } +})(); + +//////////////// MouseWheel //////////////// + +Event.mousewheel = function(target, listener, timeout) { + var interval = 0; + var self = Event(target, "mousewheel", function(event) { + event = event || window.event; + var wheelData = event.detail ? event.detail * -1 : event.wheelDelta / 40; + listener(event, "wheel", wheelData); + window.clearInterval(interval); + interval = window.setInterval(function() { + window.clearInterval(interval); + listener(event, "wheelup", wheelData, self); + }, timeout || 150); + }); + return self; +}; + +///// DOM.absPos + +var abPos = function(o) { + o = typeof(o) === 'object' ? o : document.getElementById(o); + var offset = { x: 0, y: 0 }; + while(o != null) { + offset.x += o.offsetLeft; + offset.y += o.offsetTop; + o = o.offsetParent; + }; + return offset; +}; \ No newline at end of file diff --git a/js/Event.js b/js/Event.js new file mode 100644 index 0000000..b5b37e3 --- /dev/null +++ b/js/Event.js @@ -0,0 +1,203 @@ +/* + + Event.js : v1.1 : mudcu.be + ----------------------- + /// calling "Event" with "new" provides additional support; + Event(syntax.area, "click", function(event, self) { + self.stop().prevent().remove(); + }); + + /// calling "Event" without "new" also works, but requires more work (and is faster); + var click = Event.add(syntax.area, "click", function(event) { + Event.stop(event); + Event.prevent(event); + Event.remove(syntax.area, "click", click); + }); + + /// multiple event-types bound to one function + var binding = Event(window, "click,mousemove,mousemove,mouseup", function(event, self) { + self.stop().prevent(); // stopPropagation and preventDefault + binding.remove(); // removes all the listeners + }); + + /// multiple events bound to one element + var binding = Event(window, { + "mousedown": function(event, self) { + self.remove(); // remove all the listeners + }, + "mouseup": function(event, self) { + binding.remove(); // just remove this listener + } + }); + +*/ + +var Event = (function(root) { "use strict"; + var add = document.addEventListener ? 'addEventListener' : 'attachEvent'; + var remove = document.removeEventListener ? 'removeEventListener' : 'detachEvent'; + var isEvent = (function () { + var events = {}; + var types = [ + 'abort', 'beforeunload', 'blur', 'broadcast', 'change', 'click', 'close', + 'command', 'commandupdate', 'contextmenu', 'dblclick', 'dragdrop', + 'dragenter', 'dragexit', 'draggesture', 'dragover', 'error', 'focus', + 'input', 'keydown', 'keypress', 'keyup', 'load', 'mousedown', + 'mousewheel', 'mouseenter', 'mouseleave', 'mousemove', 'mouseout', 'mouseover', + 'mouseup', 'move', 'overflow', 'overflowchanged', 'popuphidden', + 'popuphiding', 'popupshowing', 'popupshown', 'select', 'scroll', + 'syncfrompreference', 'synctopreference', 'readystatechange', + 'reset', 'resize', 'select', 'submit', 'underflow', 'unload' + ]; + for (var n = 0, length = types.length; n < length; n ++) { + events[types[n]] = true; + } + return events; + })(); + // event wrappers, and associated variables + var wrappers = {}; + var counter = 0; + var testElement = document.createElement("div"); + var getEventID = function(object) { + if (object === window) return "#window"; + if (object === document) return "#document"; + if (!object) object = {}; // FIXME: Happens in iOS + if (!object.uniqueID) { + object.uniqueID = "id" + counter ++; + } + return object.uniqueID; + }; + // function to create new Events + root = {}; // double type the root function as object + function + root = function(target, type, listener, scope) { + // find the where function was called from (window is undefined) + var that = typeof(this) !== "undefined" ? this : {}; + // check for multiple events in one string + if (type.indexOf && type.indexOf(",") !== -1) { + type = type.split(","); + } + // check type for multipel events + if (typeof(type) !== "string") { // has multiple events + that.events = {}; + if (typeof(type.length) === "undefined") { // has multiple listeners (object) + for (var key in type) { + if (isEvent[key] && typeof(type[key]) === "function") { + that.events[key] = Event(target, key, type[key], scope); + } + } + } else { // has multiple listeners glued together (array) + for (var n = 0, length = type.length; n < length; n ++) { + that.events[type[n]] = Event(target, type[n], listener, scope); + } + } + that.remove = function() { // remove multiple events + for (var key in that.events) { + that.events[key].remove(); + } + return that; + }; + that.add = function() { // add multiple events + for (var key in that.events) { + that.events[key].add(); + } + return that; + }; + return that; + } else { // is single call + if (!(target && type && listener)) return "missing data."; + type = standardize(type); + } + // tracked wrapper + var wrapperID = type + getEventID(target) + "." + getEventID(listener); + if (!wrappers[wrapperID]) { // create new wrapper + wrappers[wrapperID] = function(event) { + return listener.call(scope, that.event = event, that); + }; + } + // the wrapped listener + var wrapper = wrappers[wrapperID]; + target[add](type, wrapper, false); + // + that.stop = function(event) { + event = event || that.event; + if (event.stopPropagation) { + event.stopPropagation(); + } else { // <= IE8 + event.cancelBubble = true; + } + return that; + }; + that.prevent = function(event) { + event = event || that.event; + if (event.preventDefault) { + event.preventDefault(); + } else { // <= IE8 + event.returnValue = false; + } + return that; + }; + that.add = function() { // so you can add it back + target[add](type, wrapper, false); + return that; + }; + that.remove = function() { + target[remove](type, wrapper, false); + return that; + }; + return that; + }; + + root.add = function(target, type, listener, scope) { + type = standardize(type); + target[add](type, wrap(type, target, listener, scope || target), false); + return listener; + }; + + root.remove = function(target, type, listener, scope) { + type = standardize(type); + target[remove](type, wrap(type, target, listener, scope || target), false); + return listener; + }; + + root.stop = + root.stopPropagation = function(event) { + if (event.stopPropagation) { + event.stopPropagation(); + } else { // <= IE8 + event.cancelBubble = true; + } + }; + + root.prevent = + root.preventDefault = function(event) { + if (event.preventDefault) { + event.preventDefault(); + } else { // <= IE8 + event.returnValue = false; + } + }; + + ///////////// + + var standardize = function(type) { // fix any browser discrepancies + if (!document.addEventListener) { + return "on" + type; + } else if (type === "mousewheel" && !("onmousewheel" in testElement)) { + return "DOMMouseScroll"; + } else { // + return type; + } + }; + + var wrap = function(type, target, listener, scope) { // un-tracked wrapper + var wrapperID = type + getEventID(target) + "." + getEventID(listener); + if (!wrappers[wrapperID]) { + wrappers[wrapperID] = function(event) { + return listener.call(scope, event); + }; + } + return wrappers[wrapperID]; + }; + // + return root; + // +})(Event); \ No newline at end of file diff --git a/js/MIDI.Player.js b/js/MIDI.Player.js new file mode 100644 index 0000000..6c940ed --- /dev/null +++ b/js/MIDI.Player.js @@ -0,0 +1,279 @@ +/* + + MIDI.Player : 0.3 + ------------------------------------- + https://github.com/mudx/MIDI.js + ------------------------------------- + requires jasmid + +*/ + +if (typeof (MIDI) === "undefined") var MIDI = {}; +if (typeof (MIDI.Player) === "undefined") MIDI.Player = {}; + +(function() { "use strict"; + +var root = MIDI.Player; +root.callback = undefined; // your custom callback goes here! +root.currentTime = 0; +root.endTime = 0; +root.restart = 0; +root.playing = false; +root.timeWarp = 1; + +// +root.start = +root.resume = function () { + if (root.currentTime < -1) root.currentTime = -1; + startAudio(root.currentTime); +}; + +root.pause = function () { + var tmp = root.restart; + stopAudio(); + root.restart = tmp; +}; + +root.stop = function () { + stopAudio(); + root.restart = 0; + root.currentTime = 0; +}; + +root.addListener = function(callback) { + onMidiEvent = callback; +}; + +root.removeListener = function() { + onMidiEvent = undefined; +}; + +root.clearAnimation = function() { + if (root.interval) { + window.clearInterval(root.interval); + } +}; + +root.setAnimation = function(config) { + var callback = (typeof(config) === "function") ? config : config.callback; + var delay = config.delay || 100; + var currentTime = 0; + var tOurTime = 0; + var tTheirTime = 0; + // + root.clearAnimation(); + root.interval = window.setInterval(function (){ + if (root.endTime === 0) return; + if (root.playing) { + currentTime = (tTheirTime == root.currentTime) ? tOurTime-(new Date()).getTime() : 0; + if (root.currentTime === 0) { + currentTime = 0; + } else { + currentTime = root.currentTime - currentTime; + } + if (tTheirTime != root.currentTime) { + tOurTime = (new Date()).getTime(); + tTheirTime = root.currentTime; + } + } else { // paused + currentTime = root.currentTime; + } + var endTime = root.endTime; + var percent = currentTime / endTime; + var total = currentTime / 1000; + var minutes = total / 60; + var seconds = total - (minutes * 60); + var t1 = minutes * 60 + seconds; + var t2 = (endTime / 1000); + if (t2 - t1 < -1) return; + callback({ + now: t1, + end: t2, + events: noteRegistrar + }); + }, delay); +}; + +// helpers + +var loadMidiFile = function() { // reads midi into javascript array of events + root.replayer = new Replayer(MidiFile(root.currentData), root.timeWarp); + root.data = root.replayer.getData(); + root.endTime = getLength(); +}; + +root.loadFile = function (file, callback) { + root.stop(); + if (file.indexOf("base64,") !== -1) { + var data = window.atob(file.split(",")[1]); + root.currentData = data; + loadMidiFile(); + if (callback) callback(data); + return; + } + var fetch = new XMLHttpRequest(); + fetch.open('GET', file); + fetch.overrideMimeType("text/plain; charset=x-user-defined"); + fetch.onreadystatechange = function () { + if (this.readyState === 4 && this.status === 200) { + var t = this.responseText || ""; + var ff = []; + var mx = t.length; + var scc = String.fromCharCode; + for (var z = 0; z < mx; z++) { + ff[z] = scc(t.charCodeAt(z) & 255); + } + var data = window.atob(ff.join("")); + root.currentData = data; + loadMidiFile(); + if (callback) callback(data); + } + }; + fetch.send(); +}; + +// Playing the audio + +var eventQueue = []; // hold events to be triggered +var queuedTime; // +var startTime = 0; // to measure time elapse +var noteRegistrar = {}; // get event for requested note +var onMidiEvent = undefined; // listener callback +var scheduleTracking = function (channel, note, currentTime, offset, message, velocity) { + var interval = window.setInterval(function () { + window.clearInterval(interval); + var data = { + channel: channel, + note: note, + now: currentTime, + end: root.endTime, + message: message, + velocity: velocity + }; + // + if (message === 128) { + delete noteRegistrar[note]; + } else { + noteRegistrar[note] = data; + } + if (onMidiEvent) { + onMidiEvent(data); + } + root.currentTime = currentTime; + if (root.currentTime === queuedTime && queuedTime < root.endTime) { // grab next sequence + startAudio(queuedTime, true); + } + }, currentTime - offset); + return interval; +}; + +var getContext = function() { + if (MIDI.lang === 'WebAudioAPI') { + return MIDI.Player.ctx; + } else if (!root.ctx) { + root.ctx = { currentTime: 0 }; + } + return root.ctx; +}; + +var getLength = function() { + var data = root.data; + var length = data.length; + var totalTime = 0.5; + for (var n = 0; n < length; n++) { + totalTime += data[n][1]; + } + return totalTime; +}; + +var startAudio = function (currentTime, fromCache) { + if (!root.replayer) return; + if (!fromCache) { + if (typeof (currentTime) === "undefined") currentTime = root.restart; + if (root.playing) stopAudio(); + root.playing = true; + root.data = root.replayer.getData(); + root.endTime = getLength(); + } + var note; + var offset = 0; + var messages = 0; + var data = root.data; + var ctx = getContext(); + var length = data.length; + // + queuedTime = 0.5; + startTime = ctx.currentTime; + // + for (var n = 0; n < length && messages < 100; n++) { + queuedTime += data[n][1]; + if (queuedTime <= currentTime) { + offset = queuedTime; + continue; + } + currentTime = queuedTime - offset; + var event = data[n][0].event; + if (event.type !== "channel") continue; + var channel = event.channel; + switch (event.subtype) { + case 'noteOn': + if (MIDI.channels[channel].mute) break; + note = event.noteNumber - (root.MIDIOffset || 0); + eventQueue.push({ + event: event, + source: MIDI.noteOn(channel, event.noteNumber, event.velocity, currentTime / 1000 + ctx.currentTime), + interval: scheduleTracking(channel, note, queuedTime, offset, 144, event.velocity) + }); + messages ++; + break; + case 'noteOff': + if (MIDI.channels[channel].mute) break; + note = event.noteNumber - (root.MIDIOffset || 0); + eventQueue.push({ + event: event, + source: MIDI.noteOff(channel, event.noteNumber, currentTime / 1000 + ctx.currentTime), + interval: scheduleTracking(channel, note, queuedTime, offset - 10, 128) + }); + break; + default: + break; + } + } +}; + +var stopAudio = function () { + var ctx = getContext(); + root.playing = false; + root.restart += (ctx.currentTime - startTime) * 1000; + // stop the audio, and intervals + while (eventQueue.length) { + var o = eventQueue.pop(); + window.clearInterval(o.interval); + if (!o.source) continue; // is not webaudio + if (typeof(o.source) === "number") { + window.clearTimeout(o.source); + } else { // webaudio + var source = o.source; + source.disconnect(0); + source.noteOff(0); + } + } + // run callback to cancel any notes still playing + for (var key in noteRegistrar) { + var o = noteRegistrar[key] + if (noteRegistrar[key].message === 144 && onMidiEvent) { + onMidiEvent({ + channel: o.channel, + note: o.note, + now: o.now, + end: o.end, + message: 128, + velocity: o.velocity + }); + } + } + // reset noteRegistrar + noteRegistrar = {}; +}; + +})(); \ No newline at end of file diff --git a/js/MIDI.Plugin.js b/js/MIDI.Plugin.js new file mode 100644 index 0000000..9d26203 --- /dev/null +++ b/js/MIDI.Plugin.js @@ -0,0 +1,486 @@ +/* + + MIDI.Plugin : 0.3 + ------------------------------------- + https://github.com/mudx/MIDI.js + ------------------------------------- + MIDI.WebAudioAPI + MIDI.Flash + MIDI.HTML5 + MIDI.instruments + MIDI.channels + MIDI.keyToNote + MIDI.noteToKey + + setMute? + getInstruments? + +*/ + +if (typeof (MIDI) === "undefined") var MIDI = {}; +if (typeof (MIDI.Plugin) === "undefined") MIDI.Plugin = {}; + +(function() { "use strict"; + +/* + Web Audio API - OGG or MPEG Soundbank + -------------------------------------- + https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html +*/ + +if (typeof (MIDI.WebAudioAPI) === "undefined") MIDI.WebAudioAPI = {}; + +if (window.AudioContext || window.webkitAudioContext) (function () { + + var AudioContext = window.AudioContext || window.webkitAudioContext; + var root = MIDI.WebAudioAPI; + var ctx; + var sources = {}; + var masterVolume = 1; + var audioBuffers = {}; + var audioLoader = function (urlList, index, bufferList, oncomplete) { + var url = urlList[index]; + var base64 = MIDI.Soundfont[url].split(",")[1]; + var buffer = Base64Binary.decodeArrayBuffer(base64); + ctx.decodeAudioData(buffer, function (buffer) { + var msg = url; while(msg.length < 3) msg += " "; + if (typeof(loader) !== "undefined") { + loader.message("Downloading: 100%
    Processing: "+(index/87 * 100 >> 0)+"%
    " + msg); + } + buffer.id = url; + bufferList[index] = buffer; + // + if (bufferList.length === urlList.length) { + while (bufferList.length) { + buffer = bufferList.pop(); + var nodeId = MIDI.keyToNote[buffer.id]; + audioBuffers[nodeId] = buffer; + } + oncomplete(); + } + }); + }; + + root.setVolume = function (n) { + masterVolume = n; + }; + + root.programChange = function (instrument) { + + }; + + root.noteOn = function (channel, note, velocity, delay) { + /// check whether the note exists + if (!audioBuffers[note]) return; + /// convert relative delay to absolute delay + if (delay < ctx.currentTime) delay += ctx.currentTime; + /// crate audio buffer + var source = ctx.createBufferSource(); + sources[channel + "" + note] = source; + source.buffer = audioBuffers[note]; + source.connect(ctx.destination); + // + var gainNode = ctx.createGainNode(); + var value = -0.5 + (velocity / 100) * 2; + var minus = (1 - masterVolume) * 2; + gainNode.connect(ctx.destination); + gainNode.gain.value = Math.max(-1, value - minus); + source.connect(gainNode); + // +// source.playbackRate.value = 2; + /// + source.noteOn(delay || 0); + return source; + }; + + root.chordOn = function (channel, chord, velocity, delay) { + var ret = {}, note; + for (var n = 0, length = chord.length; n < length; n ++) { + ret[note = chord[n]] = root.noteOn(channel, note, velocity, delay); + } + return ret; + }; + + // FIX: needs some way to fade out smoothly.. + root.noteOff = function (channel, note, delay) { +// var source = sources[channel+""+note]; +// if (!source) return; +// source.noteOff(delay || 0); +// return source; + }; + + root.chordOff = function (channel, chord, delay) { + + }; + + root.connect = function (callback) { + + MIDI.lang = 'WebAudioAPI'; + MIDI.setVolume = root.setVolume; + MIDI.programChange = root.programChange; + MIDI.noteOn = root.noteOn; + MIDI.noteOff = root.noteOff; + MIDI.chordOn = root.chordOn; + MIDI.chordOff = root.chordOff; + // + MIDI.Player.ctx = ctx = new AudioContext(); + /// + var urlList = []; + var keyToNote = MIDI.keyToNote; + for (var key in keyToNote) urlList.push(key); + var bufferList = []; + for (var i = 0; i < urlList.length; i++) { + audioLoader(urlList, i, bufferList, callback); + } + }; + +})(); + +/* + HTML5