soundjs.ts 263 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080
  1. /*!
  2. * SoundJS
  3. * Visit http://createjs.com/ for documentation, updates and examples.
  4. *
  5. * Copyright (c) 2010 gskinner.com, inc.
  6. *
  7. * Permission is hereby granted, free of charge, to any person
  8. * obtaining a copy of this software and associated documentation
  9. * files (the "Software"), to deal in the Software without
  10. * restriction, including without limitation the rights to use,
  11. * copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the
  13. * Software is furnished to do so, subject to the following
  14. * conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be
  17. * included in all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  20. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  21. * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  22. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  23. * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  24. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  25. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  26. * OTHER DEALINGS IN THE SOFTWARE.
  27. */
  28. // @ts-nocheck
  29. //##############################################################################
  30. // version.js
  31. //##############################################################################
  32. let createjs: any = window.createjs || {};
  33. (function () {
  34. /**
  35. * Static class holding library specific information such as the version and buildDate of the library.
  36. * The SoundJS class has been renamed {{#crossLink "Sound"}}{{/crossLink}}. Please see {{#crossLink "Sound"}}{{/crossLink}}
  37. * for information on using sound.
  38. * @class SoundJS
  39. **/
  40. var s = createjs.SoundJS = createjs.SoundJS || {};
  41. /**
  42. * The version string for this release.
  43. * @property version
  44. * @type String
  45. * @static
  46. **/
  47. s.version = /*=version*/"NEXT"; // injected by build process
  48. /**
  49. * The build date for this release in UTC format.
  50. * @property buildDate
  51. * @type String
  52. * @static
  53. **/
  54. s.buildDate = /*=date*/"Thu, 12 Oct 2017 16:33:45 GMT"; // injected by build process
  55. })();
  56. //##############################################################################
  57. // extend.js
  58. //##############################################################################
  59. /**
  60. * @class Utility Methods
  61. */
  62. /**
  63. * Sets up the prototype chain and constructor property for a new class.
  64. *
  65. * This should be called right after creating the class constructor.
  66. *
  67. * function MySubClass() {}
  68. * createjs.extend(MySubClass, MySuperClass);
  69. * MySubClass.prototype.doSomething = function() { }
  70. *
  71. * var foo = new MySubClass();
  72. * console.log(foo instanceof MySuperClass); // true
  73. * console.log(foo.prototype.constructor === MySubClass); // true
  74. *
  75. * @method extend
  76. * @param {Function} subclass The subclass.
  77. * @param {Function} superclass The superclass to extend.
  78. * @return {Function} Returns the subclass's new prototype.
  79. */
  80. createjs.extend = function(subclass, superclass) {
  81. "use strict";
  82. function o() { this.constructor = subclass; }
  83. o.prototype = superclass.prototype;
  84. return (subclass.prototype = new o());
  85. };
  86. //##############################################################################
  87. // promote.js
  88. //##############################################################################
  89. /**
  90. * @class Utility Methods
  91. */
  92. /**
  93. * Promotes any methods on the super class that were overridden, by creating an alias in the format `prefix_methodName`.
  94. * It is recommended to use the super class's name as the prefix.
  95. * An alias to the super class's constructor is always added in the format `prefix_constructor`.
  96. * This allows the subclass to call super class methods without using `function.call`, providing better performance.
  97. *
  98. * For example, if `MySubClass` extends `MySuperClass`, and both define a `draw` method, then calling `promote(MySubClass, "MySuperClass")`
  99. * would add a `MySuperClass_constructor` method to MySubClass and promote the `draw` method on `MySuperClass` to the
  100. * prototype of `MySubClass` as `MySuperClass_draw`.
  101. *
  102. * This should be called after the class's prototype is fully defined.
  103. *
  104. * function ClassA(name) {
  105. * this.name = name;
  106. * }
  107. * ClassA.prototype.greet = function() {
  108. * return "Hello "+this.name;
  109. * }
  110. *
  111. * function ClassB(name, punctuation) {
  112. * this.ClassA_constructor(name);
  113. * this.punctuation = punctuation;
  114. * }
  115. * createjs.extend(ClassB, ClassA);
  116. * ClassB.prototype.greet = function() {
  117. * return this.ClassA_greet()+this.punctuation;
  118. * }
  119. * createjs.promote(ClassB, "ClassA");
  120. *
  121. * var foo = new ClassB("World", "!?!");
  122. * console.log(foo.greet()); // Hello World!?!
  123. *
  124. * @method promote
  125. * @param {Function} subclass The class to promote super class methods on.
  126. * @param {String} prefix The prefix to add to the promoted method names. Usually the name of the superclass.
  127. * @return {Function} Returns the subclass.
  128. */
  129. createjs.promote = function(subclass, prefix) {
  130. "use strict";
  131. var subP = subclass.prototype, supP = (Object.getPrototypeOf&&Object.getPrototypeOf(subP))||subP.__proto__;
  132. if (supP) {
  133. subP[(prefix+="_") + "constructor"] = supP.constructor; // constructor is not always innumerable
  134. for (var n in supP) {
  135. if (subP.hasOwnProperty(n) && (typeof supP[n] == "function")) { subP[prefix + n] = supP[n]; }
  136. }
  137. }
  138. return subclass;
  139. };
  140. //##############################################################################
  141. // deprecate.js
  142. //##############################################################################
  143. /**
  144. * @class Utility Methods
  145. */
  146. /**
  147. * Wraps deprecated methods so they still be used, but throw warnings to developers.
  148. *
  149. * obj.deprecatedMethod = createjs.deprecate("Old Method Name", obj._fallbackMethod);
  150. *
  151. * The recommended approach for deprecated properties is:
  152. *
  153. * try {
  154. * Obj ect.defineProperties(object, {
  155. * readyOnlyProp: { get: createjs.deprecate("readOnlyProp", function() { return this.alternateProp; }) },
  156. * readWriteProp: {
  157. * get: createjs.deprecate("readOnlyProp", function() { return this.alternateProp; }),
  158. * set: createjs.deprecate("readOnlyProp", function(val) { this.alternateProp = val; })
  159. * });
  160. * } catch (e) {}
  161. *
  162. * @method deprecate
  163. * @param {Function} [fallbackMethod=null] A method to call when the deprecated method is used. See the example for how
  164. * @param {String} [name=null] The name of the method or property to display in the console warning.
  165. * to deprecate properties.
  166. * @return {Function} If a fallbackMethod is supplied, returns a closure that will call the fallback method after
  167. * logging the warning in the console.
  168. */
  169. createjs.deprecate = function(fallbackMethod, name) {
  170. "use strict";
  171. return function() {
  172. var msg = "Deprecated property or method '"+name+"'. See docs for info.";
  173. console && (console.warn ? console.warn(msg) : console.log(msg));
  174. return fallbackMethod && fallbackMethod.apply(this, arguments);
  175. }
  176. };
  177. //##############################################################################
  178. // indexOf.js
  179. //##############################################################################
  180. /**
  181. * @class Utility Methods
  182. */
  183. /**
  184. * Finds the first occurrence of a specified value searchElement in the passed in array, and returns the index of
  185. * that value. Returns -1 if value is not found.
  186. *
  187. * var i = createjs.indexOf(myArray, myElementToFind);
  188. *
  189. * @method indexOf
  190. * @param {Array} array Array to search for searchElement
  191. * @param searchElement Element to find in array.
  192. * @return {Number} The first index of searchElement in array.
  193. */
  194. createjs.indexOf = function (array, searchElement){
  195. "use strict";
  196. for (var i = 0,l=array.length; i < l; i++) {
  197. if (searchElement === array[i]) {
  198. return i;
  199. }
  200. }
  201. return -1;
  202. };
  203. //##############################################################################
  204. // proxy.js
  205. //##############################################################################
  206. /**
  207. * Various utilities that the CreateJS Suite uses. Utilities are created as separate files, and will be available on the
  208. * createjs namespace directly.
  209. *
  210. * <h4>Example</h4>
  211. *
  212. * myObject.addEventListener("change", createjs.proxy(myMethod, scope));
  213. *
  214. * @class Utility Methods
  215. * @main Utility Methods
  216. */
  217. (function() {
  218. "use strict";
  219. /**
  220. * A function proxy for methods. By default, JavaScript methods do not maintain scope, so passing a method as a
  221. * callback will result in the method getting called in the scope of the caller. Using a proxy ensures that the
  222. * method gets called in the correct scope.
  223. *
  224. * Additional arguments can be passed that will be applied to the function when it is called.
  225. *
  226. * <h4>Example</h4>
  227. *
  228. * myObject.addEventListener("event", createjs.proxy(myHandler, this, arg1, arg2));
  229. *
  230. * function myHandler(arg1, arg2) {
  231. * // This gets called when myObject.myCallback is executed.
  232. * }
  233. *
  234. * @method proxy
  235. * @param {Function} method The function to call
  236. * @param {Object} scope The scope to call the method name on
  237. * @param {mixed} [arg] * Arguments that are appended to the callback for additional params.
  238. * @public
  239. * @static
  240. */
  241. createjs.proxy = function (method, scope) {
  242. var aArgs = Array.prototype.slice.call(arguments, 2);
  243. return function () {
  244. return method.apply(scope, Array.prototype.slice.call(arguments, 0).concat(aArgs));
  245. };
  246. }
  247. }());
  248. //##############################################################################
  249. // BrowserDetect.js
  250. //##############################################################################
  251. /**
  252. * @class Utility Methods
  253. */
  254. (function() {
  255. "use strict";
  256. /**
  257. * An object that determines the current browser, version, operating system, and other environment
  258. * variables via user agent string.
  259. *
  260. * Used for audio because feature detection is unable to detect the many limitations of mobile devices.
  261. *
  262. * <h4>Example</h4>
  263. *
  264. * if (createjs.BrowserDetect.isIOS) { // do stuff }
  265. *
  266. * @property BrowserDetect
  267. * @type {Object}
  268. * @param {Boolean} isFirefox True if our browser is Firefox.
  269. * @param {Boolean} isOpera True if our browser is opera.
  270. * @param {Boolean} isChrome True if our browser is Chrome. Note that Chrome for Android returns true, but is a
  271. * completely different browser with different abilities.
  272. * @param {Boolean} isIOS True if our browser is safari for iOS devices (iPad, iPhone, and iPod).
  273. * @param {Boolean} isAndroid True if our browser is Android.
  274. * @param {Boolean} isBlackberry True if our browser is Blackberry.
  275. * @constructor
  276. * @static
  277. */
  278. function BrowserDetect() {
  279. throw "BrowserDetect cannot be instantiated";
  280. };
  281. var agent = BrowserDetect.agent = window.navigator.userAgent;
  282. BrowserDetect.isWindowPhone = (agent.indexOf("IEMobile") > -1) || (agent.indexOf("Windows Phone") > -1);
  283. BrowserDetect.isFirefox = (agent.indexOf("Firefox") > -1);
  284. BrowserDetect.isOpera = (window.opera != null);
  285. BrowserDetect.isChrome = (agent.indexOf("Chrome") > -1); // NOTE that Chrome on Android returns true but is a completely different browser with different abilities
  286. BrowserDetect.isIOS = (agent.indexOf("iPod") > -1 || agent.indexOf("iPhone") > -1 || agent.indexOf("iPad") > -1) && !BrowserDetect.isWindowPhone;
  287. BrowserDetect.isAndroid = (agent.indexOf("Android") > -1) && !BrowserDetect.isWindowPhone;
  288. BrowserDetect.isBlackberry = (agent.indexOf("Blackberry") > -1);
  289. createjs.BrowserDetect = BrowserDetect;
  290. }());
  291. //##############################################################################
  292. // EventDispatcher.js
  293. //##############################################################################
  294. (function() {
  295. "use strict";
  296. // constructor:
  297. /**
  298. * EventDispatcher provides methods for managing queues of event listeners and dispatching events.
  299. *
  300. * You can either extend EventDispatcher or mix its methods into an existing prototype or instance by using the
  301. * EventDispatcher {{#crossLink "EventDispatcher/initialize"}}{{/crossLink}} method.
  302. *
  303. * Together with the CreateJS Event class, EventDispatcher provides an extended event model that is based on the
  304. * DOM Level 2 event model, including addEventListener, removeEventListener, and dispatchEvent. It supports
  305. * bubbling / capture, preventDefault, stopPropagation, stopImmediatePropagation, and handleEvent.
  306. *
  307. * EventDispatcher also exposes a {{#crossLink "EventDispatcher/on"}}{{/crossLink}} method, which makes it easier
  308. * to create scoped listeners, listeners that only run once, and listeners with associated arbitrary data. The
  309. * {{#crossLink "EventDispatcher/off"}}{{/crossLink}} method is merely an alias to
  310. * {{#crossLink "EventDispatcher/removeEventListener"}}{{/crossLink}}.
  311. *
  312. * Another addition to the DOM Level 2 model is the {{#crossLink "EventDispatcher/removeAllEventListeners"}}{{/crossLink}}
  313. * method, which can be used to listeners for all events, or listeners for a specific event. The Event object also
  314. * includes a {{#crossLink "Event/remove"}}{{/crossLink}} method which removes the active listener.
  315. *
  316. * <h4>Example</h4>
  317. * Add EventDispatcher capabilities to the "MyClass" class.
  318. *
  319. * EventDispatcher.initialize(MyClass.prototype);
  320. *
  321. * Add an event (see {{#crossLink "EventDispatcher/addEventListener"}}{{/crossLink}}).
  322. *
  323. * instance.addEventListener("eventName", handlerMethod);
  324. * function handlerMethod(event) {
  325. * console.log(event.target + " Was Clicked");
  326. * }
  327. *
  328. * <b>Maintaining proper scope</b><br />
  329. * Scope (ie. "this") can be be a challenge with events. Using the {{#crossLink "EventDispatcher/on"}}{{/crossLink}}
  330. * method to subscribe to events simplifies this.
  331. *
  332. * instance.addEventListener("click", function(event) {
  333. * console.log(instance == this); // false, scope is ambiguous.
  334. * });
  335. *
  336. * instance.on("click", function(event) {
  337. * console.log(instance == this); // true, "on" uses dispatcher scope by default.
  338. * });
  339. *
  340. * If you want to use addEventListener instead, you may want to use function.bind() or a similar proxy to manage
  341. * scope.
  342. *
  343. * <b>Browser support</b>
  344. * The event model in CreateJS can be used separately from the suite in any project, however the inheritance model
  345. * requires modern browsers (IE9+).
  346. *
  347. *
  348. * @class EventDispatcher
  349. * @constructor
  350. **/
  351. function EventDispatcher() {
  352. // private properties:
  353. /**
  354. * @protected
  355. * @property _listeners
  356. * @type Object
  357. **/
  358. this._listeners = null;
  359. /**
  360. * @protected
  361. * @property _captureListeners
  362. * @type Object
  363. **/
  364. this._captureListeners = null;
  365. }
  366. var p = EventDispatcher.prototype;
  367. // static public methods:
  368. /**
  369. * Static initializer to mix EventDispatcher methods into a target object or prototype.
  370. *
  371. * EventDispatcher.initialize(MyClass.prototype); // add to the prototype of the class
  372. * EventDispatcher.initialize(myObject); // add to a specific instance
  373. *
  374. * @method initialize
  375. * @static
  376. * @param {Object} target The target object to inject EventDispatcher methods into. This can be an instance or a
  377. * prototype.
  378. **/
  379. EventDispatcher.initialize = function(target) {
  380. target.addEventListener = p.addEventListener;
  381. target.on = p.on;
  382. target.removeEventListener = target.off = p.removeEventListener;
  383. target.removeAllEventListeners = p.removeAllEventListeners;
  384. target.hasEventListener = p.hasEventListener;
  385. target.dispatchEvent = p.dispatchEvent;
  386. target._dispatchEvent = p._dispatchEvent;
  387. target.willTrigger = p.willTrigger;
  388. };
  389. // public methods:
  390. /**
  391. * Adds the specified event listener. Note that adding multiple listeners to the same function will result in
  392. * multiple callbacks getting fired.
  393. *
  394. * <h4>Example</h4>
  395. *
  396. * displayObject.addEventListener("click", handleClick);
  397. * function handleClick(event) {
  398. * // Click happened.
  399. * }
  400. *
  401. * @method addEventListener
  402. * @param {String} type The string type of the event.
  403. * @param {Function | Object} listener An object with a handleEvent method, or a function that will be called when
  404. * the event is dispatched.
  405. * @param {Boolean} [useCapture] For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.
  406. * @return {Function | Object} Returns the listener for chaining or assignment.
  407. **/
  408. p.addEventListener = function(type, listener, useCapture) {
  409. var listeners;
  410. if (useCapture) {
  411. listeners = this._captureListeners = this._captureListeners||{};
  412. } else {
  413. listeners = this._listeners = this._listeners||{};
  414. }
  415. var arr = listeners[type];
  416. if (arr) { this.removeEventListener(type, listener, useCapture); }
  417. arr = listeners[type]; // remove may have deleted the array
  418. if (!arr) { listeners[type] = [listener]; }
  419. else { arr.push(listener); }
  420. return listener;
  421. };
  422. /**
  423. * A shortcut method for using addEventListener that makes it easier to specify an execution scope, have a listener
  424. * only run once, associate arbitrary data with the listener, and remove the listener.
  425. *
  426. * This method works by creating an anonymous wrapper function and subscribing it with addEventListener.
  427. * The wrapper function is returned for use with `removeEventListener` (or `off`).
  428. *
  429. * <b>IMPORTANT:</b> To remove a listener added with `on`, you must pass in the returned wrapper function as the listener, or use
  430. * {{#crossLink "Event/remove"}}{{/crossLink}}. Likewise, each time you call `on` a NEW wrapper function is subscribed, so multiple calls
  431. * to `on` with the same params will create multiple listeners.
  432. *
  433. * <h4>Example</h4>
  434. *
  435. * var listener = myBtn.on("click", handleClick, null, false, {count:3});
  436. * function handleClick(evt, data) {
  437. * data.count -= 1;
  438. * console.log(this == myBtn); // true - scope defaults to the dispatcher
  439. * if (data.count == 0) {
  440. * alert("clicked 3 times!");
  441. * myBtn.off("click", listener);
  442. * // alternately: evt.remove();
  443. * }
  444. * }
  445. *
  446. * @method on
  447. * @param {String} type The string type of the event.
  448. * @param {Function | Object} listener An object with a handleEvent method, or a function that will be called when
  449. * the event is dispatched.
  450. * @param {Object} [scope] The scope to execute the listener in. Defaults to the dispatcher/currentTarget for function listeners, and to the listener itself for object listeners (ie. using handleEvent).
  451. * @param {Boolean} [once=false] If true, the listener will remove itself after the first time it is triggered.
  452. * @param {*} [data] Arbitrary data that will be included as the second parameter when the listener is called.
  453. * @param {Boolean} [useCapture=false] For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.
  454. * @return {Function} Returns the anonymous function that was created and assigned as the listener. This is needed to remove the listener later using .removeEventListener.
  455. **/
  456. p.on = function(type, listener, scope, once, data, useCapture) {
  457. if (listener.handleEvent) {
  458. scope = scope||listener;
  459. listener = listener.handleEvent;
  460. }
  461. scope = scope||this;
  462. return this.addEventListener(type, function(evt) {
  463. listener.call(scope, evt, data);
  464. once&&evt.remove();
  465. }, useCapture);
  466. };
  467. /**
  468. * Removes the specified event listener.
  469. *
  470. * <b>Important Note:</b> that you must pass the exact function reference used when the event was added. If a proxy
  471. * function, or function closure is used as the callback, the proxy/closure reference must be used - a new proxy or
  472. * closure will not work.
  473. *
  474. * <h4>Example</h4>
  475. *
  476. * displayObject.removeEventListener("click", handleClick);
  477. *
  478. * @method removeEventListener
  479. * @param {String} type The string type of the event.
  480. * @param {Function | Object} listener The listener function or object.
  481. * @param {Boolean} [useCapture] For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.
  482. **/
  483. p.removeEventListener = function(type, listener, useCapture) {
  484. var listeners = useCapture ? this._captureListeners : this._listeners;
  485. if (!listeners) { return; }
  486. var arr = listeners[type];
  487. if (!arr) { return; }
  488. for (var i=0,l=arr.length; i<l; i++) {
  489. if (arr[i] == listener) {
  490. if (l==1) { delete(listeners[type]); } // allows for faster checks.
  491. else { arr.splice(i,1); }
  492. break;
  493. }
  494. }
  495. };
  496. /**
  497. * A shortcut to the removeEventListener method, with the same parameters and return value. This is a companion to the
  498. * .on method.
  499. *
  500. * <b>IMPORTANT:</b> To remove a listener added with `on`, you must pass in the returned wrapper function as the listener. See
  501. * {{#crossLink "EventDispatcher/on"}}{{/crossLink}} for an example.
  502. *
  503. * @method off
  504. * @param {String} type The string type of the event.
  505. * @param {Function | Object} listener The listener function or object.
  506. * @param {Boolean} [useCapture] For events that bubble, indicates whether to listen for the event in the capture or bubbling/target phase.
  507. **/
  508. p.off = p.removeEventListener;
  509. /**
  510. * Removes all listeners for the specified type, or all listeners of all types.
  511. *
  512. * <h4>Example</h4>
  513. *
  514. * // Remove all listeners
  515. * displayObject.removeAllEventListeners();
  516. *
  517. * // Remove all click listeners
  518. * displayObject.removeAllEventListeners("click");
  519. *
  520. * @method removeAllEventListeners
  521. * @param {String} [type] The string type of the event. If omitted, all listeners for all types will be removed.
  522. **/
  523. p.removeAllEventListeners = function(type) {
  524. if (!type) { this._listeners = this._captureListeners = null; }
  525. else {
  526. if (this._listeners) { delete(this._listeners[type]); }
  527. if (this._captureListeners) { delete(this._captureListeners[type]); }
  528. }
  529. };
  530. /**
  531. * Dispatches the specified event to all listeners.
  532. *
  533. * <h4>Example</h4>
  534. *
  535. * // Use a string event
  536. * this.dispatchEvent("complete");
  537. *
  538. * // Use an Event instance
  539. * var event = new createjs.Event("progress");
  540. * this.dispatchEvent(event);
  541. *
  542. * @method dispatchEvent
  543. * @param {Object | String | Event} eventObj An object with a "type" property, or a string type.
  544. * While a generic object will work, it is recommended to use a CreateJS Event instance. If a string is used,
  545. * dispatchEvent will construct an Event instance if necessary with the specified type. This latter approach can
  546. * be used to avoid event object instantiation for non-bubbling events that may not have any listeners.
  547. * @param {Boolean} [bubbles] Specifies the `bubbles` value when a string was passed to eventObj.
  548. * @param {Boolean} [cancelable] Specifies the `cancelable` value when a string was passed to eventObj.
  549. * @return {Boolean} Returns false if `preventDefault()` was called on a cancelable event, true otherwise.
  550. **/
  551. p.dispatchEvent = function(eventObj, bubbles, cancelable) {
  552. if (typeof eventObj == "string") {
  553. // skip everything if there's no listeners and it doesn't bubble:
  554. var listeners = this._listeners;
  555. if (!bubbles && (!listeners || !listeners[eventObj])) { return true; }
  556. eventObj = new createjs.Event(eventObj, bubbles, cancelable);
  557. } else if (eventObj.target && eventObj.clone) {
  558. // redispatching an active event object, so clone it:
  559. eventObj = eventObj.clone();
  560. }
  561. // TODO: it would be nice to eliminate this. Maybe in favour of evtObj instanceof Event? Or !!evtObj.createEvent
  562. try { eventObj.target = this; } catch (e) {} // try/catch allows redispatching of native events
  563. if (!eventObj.bubbles || !this.parent) {
  564. this._dispatchEvent(eventObj, 2);
  565. } else {
  566. var top=this, list=[top];
  567. while (top.parent) { list.push(top = top.parent); }
  568. var i, l=list.length;
  569. // capture & atTarget
  570. for (i=l-1; i>=0 && !eventObj.propagationStopped; i--) {
  571. list[i]._dispatchEvent(eventObj, 1+(i==0));
  572. }
  573. // bubbling
  574. for (i=1; i<l && !eventObj.propagationStopped; i++) {
  575. list[i]._dispatchEvent(eventObj, 3);
  576. }
  577. }
  578. return !eventObj.defaultPrevented;
  579. };
  580. /**
  581. * Indicates whether there is at least one listener for the specified event type.
  582. * @method hasEventListener
  583. * @param {String} type The string type of the event.
  584. * @return {Boolean} Returns true if there is at least one listener for the specified event.
  585. **/
  586. p.hasEventListener = function(type) {
  587. var listeners = this._listeners, captureListeners = this._captureListeners;
  588. return !!((listeners && listeners[type]) || (captureListeners && captureListeners[type]));
  589. };
  590. /**
  591. * Indicates whether there is at least one listener for the specified event type on this object or any of its
  592. * ancestors (parent, parent's parent, etc). A return value of true indicates that if a bubbling event of the
  593. * specified type is dispatched from this object, it will trigger at least one listener.
  594. *
  595. * This is similar to {{#crossLink "EventDispatcher/hasEventListener"}}{{/crossLink}}, but it searches the entire
  596. * event flow for a listener, not just this object.
  597. * @method willTrigger
  598. * @param {String} type The string type of the event.
  599. * @return {Boolean} Returns `true` if there is at least one listener for the specified event.
  600. **/
  601. p.willTrigger = function(type) {
  602. var o = this;
  603. while (o) {
  604. if (o.hasEventListener(type)) { return true; }
  605. o = o.parent;
  606. }
  607. return false;
  608. };
  609. /**
  610. * @method toString
  611. * @return {String} a string representation of the instance.
  612. **/
  613. p.toString = function() {
  614. return "[EventDispatcher]";
  615. };
  616. // private methods:
  617. /**
  618. * @method _dispatchEvent
  619. * @param {Object | Event} eventObj
  620. * @param {Object} eventPhase
  621. * @protected
  622. **/
  623. p._dispatchEvent = function(eventObj, eventPhase) {
  624. var l, arr, listeners = (eventPhase <= 2) ? this._captureListeners : this._listeners;
  625. if (eventObj && listeners && (arr = listeners[eventObj.type]) && (l=arr.length)) {
  626. try { eventObj.currentTarget = this; } catch (e) {}
  627. try { eventObj.eventPhase = eventPhase|0; } catch (e) {}
  628. eventObj.removed = false;
  629. arr = arr.slice(); // to avoid issues with items being removed or added during the dispatch
  630. for (var i=0; i<l && !eventObj.immediatePropagationStopped; i++) {
  631. var o = arr[i];
  632. if (o.handleEvent) { o.handleEvent(eventObj); }
  633. else { o(eventObj); }
  634. if (eventObj.removed) {
  635. this.off(eventObj.type, o, eventPhase==1);
  636. eventObj.removed = false;
  637. }
  638. }
  639. }
  640. if (eventPhase === 2) { this._dispatchEvent(eventObj, 2.1); }
  641. };
  642. createjs.EventDispatcher = EventDispatcher;
  643. }());
  644. //##############################################################################
  645. // Event.js
  646. //##############################################################################
  647. (function() {
  648. "use strict";
  649. // constructor:
  650. /**
  651. * Contains properties and methods shared by all events for use with
  652. * {{#crossLink "EventDispatcher"}}{{/crossLink}}.
  653. *
  654. * Note that Event objects are often reused, so you should never
  655. * rely on an event object's state outside of the call stack it was received in.
  656. * @class Event
  657. * @param {String} type The event type.
  658. * @param {Boolean} bubbles Indicates whether the event will bubble through the display list.
  659. * @param {Boolean} cancelable Indicates whether the default behaviour of this event can be cancelled.
  660. * @constructor
  661. **/
  662. function Event(type, bubbles, cancelable) {
  663. // public properties:
  664. /**
  665. * The type of event.
  666. * @property type
  667. * @type String
  668. **/
  669. this.type = type;
  670. /**
  671. * The object that generated an event.
  672. * @property target
  673. * @type Object
  674. * @default null
  675. * @readonly
  676. */
  677. this.target = null;
  678. /**
  679. * The current target that a bubbling event is being dispatched from. For non-bubbling events, this will
  680. * always be the same as target. For example, if childObj.parent = parentObj, and a bubbling event
  681. * is generated from childObj, then a listener on parentObj would receive the event with
  682. * target=childObj (the original target) and currentTarget=parentObj (where the listener was added).
  683. * @property currentTarget
  684. * @type Object
  685. * @default null
  686. * @readonly
  687. */
  688. this.currentTarget = null;
  689. /**
  690. * For bubbling events, this indicates the current event phase:<OL>
  691. * <LI> capture phase: starting from the top parent to the target</LI>
  692. * <LI> at target phase: currently being dispatched from the target</LI>
  693. * <LI> bubbling phase: from the target to the top parent</LI>
  694. * </OL>
  695. * @property eventPhase
  696. * @type Number
  697. * @default 0
  698. * @readonly
  699. */
  700. this.eventPhase = 0;
  701. /**
  702. * Indicates whether the event will bubble through the display list.
  703. * @property bubbles
  704. * @type Boolean
  705. * @default false
  706. * @readonly
  707. */
  708. this.bubbles = !!bubbles;
  709. /**
  710. * Indicates whether the default behaviour of this event can be cancelled via
  711. * {{#crossLink "Event/preventDefault"}}{{/crossLink}}. This is set via the Event constructor.
  712. * @property cancelable
  713. * @type Boolean
  714. * @default false
  715. * @readonly
  716. */
  717. this.cancelable = !!cancelable;
  718. /**
  719. * The epoch time at which this event was created.
  720. * @property timeStamp
  721. * @type Number
  722. * @default 0
  723. * @readonly
  724. */
  725. this.timeStamp = (new Date()).getTime();
  726. /**
  727. * Indicates if {{#crossLink "Event/preventDefault"}}{{/crossLink}} has been called
  728. * on this event.
  729. * @property defaultPrevented
  730. * @type Boolean
  731. * @default false
  732. * @readonly
  733. */
  734. this.defaultPrevented = false;
  735. /**
  736. * Indicates if {{#crossLink "Event/stopPropagation"}}{{/crossLink}} or
  737. * {{#crossLink "Event/stopImmediatePropagation"}}{{/crossLink}} has been called on this event.
  738. * @property propagationStopped
  739. * @type Boolean
  740. * @default false
  741. * @readonly
  742. */
  743. this.propagationStopped = false;
  744. /**
  745. * Indicates if {{#crossLink "Event/stopImmediatePropagation"}}{{/crossLink}} has been called
  746. * on this event.
  747. * @property immediatePropagationStopped
  748. * @type Boolean
  749. * @default false
  750. * @readonly
  751. */
  752. this.immediatePropagationStopped = false;
  753. /**
  754. * Indicates if {{#crossLink "Event/remove"}}{{/crossLink}} has been called on this event.
  755. * @property removed
  756. * @type Boolean
  757. * @default false
  758. * @readonly
  759. */
  760. this.removed = false;
  761. }
  762. var p = Event.prototype;
  763. // public methods:
  764. /**
  765. * Sets {{#crossLink "Event/defaultPrevented"}}{{/crossLink}} to true if the event is cancelable.
  766. * Mirrors the DOM level 2 event standard. In general, cancelable events that have `preventDefault()` called will
  767. * cancel the default behaviour associated with the event.
  768. * @method preventDefault
  769. **/
  770. p.preventDefault = function() {
  771. this.defaultPrevented = this.cancelable&&true;
  772. };
  773. /**
  774. * Sets {{#crossLink "Event/propagationStopped"}}{{/crossLink}} to true.
  775. * Mirrors the DOM event standard.
  776. * @method stopPropagation
  777. **/
  778. p.stopPropagation = function() {
  779. this.propagationStopped = true;
  780. };
  781. /**
  782. * Sets {{#crossLink "Event/propagationStopped"}}{{/crossLink}} and
  783. * {{#crossLink "Event/immediatePropagationStopped"}}{{/crossLink}} to true.
  784. * Mirrors the DOM event standard.
  785. * @method stopImmediatePropagation
  786. **/
  787. p.stopImmediatePropagation = function() {
  788. this.immediatePropagationStopped = this.propagationStopped = true;
  789. };
  790. /**
  791. * Causes the active listener to be removed via removeEventListener();
  792. *
  793. * myBtn.addEventListener("click", function(evt) {
  794. * // do stuff...
  795. * evt.remove(); // removes this listener.
  796. * });
  797. *
  798. * @method remove
  799. **/
  800. p.remove = function() {
  801. this.removed = true;
  802. };
  803. /**
  804. * Returns a clone of the Event instance.
  805. * @method clone
  806. * @return {Event} a clone of the Event instance.
  807. **/
  808. p.clone = function() {
  809. return new Event(this.type, this.bubbles, this.cancelable);
  810. };
  811. /**
  812. * Provides a chainable shortcut method for setting a number of properties on the instance.
  813. *
  814. * @method set
  815. * @param {Object} props A generic object containing properties to copy to the instance.
  816. * @return {Event} Returns the instance the method is called on (useful for chaining calls.)
  817. * @chainable
  818. */
  819. p.set = function(props) {
  820. for (var n in props) { this[n] = props[n]; }
  821. return this;
  822. };
  823. /**
  824. * Returns a string representation of this object.
  825. * @method toString
  826. * @return {String} a string representation of the instance.
  827. **/
  828. p.toString = function() {
  829. return "[Event (type="+this.type+")]";
  830. };
  831. createjs.Event = Event;
  832. }());
  833. //##############################################################################
  834. // ErrorEvent.js
  835. //##############################################################################
  836. (function() {
  837. "use strict";
  838. /**
  839. * A general error {{#crossLink "Event"}}{{/crossLink}}, that describes an error that occurred, as well as any details.
  840. * @class ErrorEvent
  841. * @param {String} [title] The error title
  842. * @param {String} [message] The error description
  843. * @param {Object} [data] Additional error data
  844. * @constructor
  845. */
  846. function ErrorEvent(title, message, data) {
  847. this.Event_constructor("error");
  848. /**
  849. * The short error title, which indicates the type of error that occurred.
  850. * @property title
  851. * @type String
  852. */
  853. this.title = title;
  854. /**
  855. * The verbose error message, containing details about the error.
  856. * @property message
  857. * @type String
  858. */
  859. this.message = message;
  860. /**
  861. * Additional data attached to an error.
  862. * @property data
  863. * @type {Object}
  864. */
  865. this.data = data;
  866. }
  867. var p = createjs.extend(ErrorEvent, createjs.Event);
  868. p.clone = function() {
  869. return new createjs.ErrorEvent(this.title, this.message, this.data);
  870. };
  871. createjs.ErrorEvent = createjs.promote(ErrorEvent, "Event");
  872. }());
  873. //##############################################################################
  874. // ProgressEvent.js
  875. //##############################################################################
  876. (function (scope) {
  877. "use strict";
  878. // constructor
  879. /**
  880. * A CreateJS {{#crossLink "Event"}}{{/crossLink}} that is dispatched when progress changes.
  881. * @class ProgressEvent
  882. * @param {Number} loaded The amount that has been loaded. This can be any number relative to the total.
  883. * @param {Number} [total=1] The total amount that will load. This will default to 1, so if the `loaded` value is
  884. * a percentage (between 0 and 1), it can be omitted.
  885. * @todo Consider having this event be a "fileprogress" event as well
  886. * @constructor
  887. */
  888. function ProgressEvent(loaded, total) {
  889. this.Event_constructor("progress");
  890. /**
  891. * The amount that has been loaded (out of a total amount)
  892. * @property loaded
  893. * @type {Number}
  894. */
  895. this.loaded = loaded;
  896. /**
  897. * The total "size" of the load.
  898. * @property total
  899. * @type {Number}
  900. * @default 1
  901. */
  902. this.total = (total == null) ? 1 : total;
  903. /**
  904. * The percentage (out of 1) that the load has been completed. This is calculated using `loaded/total`.
  905. * @property progress
  906. * @type {Number}
  907. * @default 0
  908. */
  909. this.progress = (total == 0) ? 0 : this.loaded / this.total;
  910. };
  911. var p = createjs.extend(ProgressEvent, createjs.Event);
  912. /**
  913. * Returns a clone of the ProgressEvent instance.
  914. * @method clone
  915. * @return {ProgressEvent} a clone of the Event instance.
  916. **/
  917. p.clone = function() {
  918. return new createjs.ProgressEvent(this.loaded, this.total);
  919. };
  920. createjs.ProgressEvent = createjs.promote(ProgressEvent, "Event");
  921. }(window));
  922. //##############################################################################
  923. // LoadItem.js
  924. //##############################################################################
  925. (function () {
  926. "use strict";
  927. /**
  928. * All loaders accept an item containing the properties defined in this class. If a raw object is passed instead,
  929. * it will not be affected, but it must contain at least a {{#crossLink "src:property"}}{{/crossLink}} property. A
  930. * string path or HTML tag is also acceptable, but it will be automatically converted to a LoadItem using the
  931. * {{#crossLink "create"}}{{/crossLink}} method by {{#crossLink "AbstractLoader"}}{{/crossLink}}
  932. * @class LoadItem
  933. * @constructor
  934. * @since 0.6.0
  935. */
  936. function LoadItem() {
  937. /**
  938. * The source of the file that is being loaded. This property is <b>required</b>. The source can either be a
  939. * string (recommended), or an HTML tag.
  940. * This can also be an object, but in that case it has to include a type and be handled by a plugin.
  941. * @property src
  942. * @type {String}
  943. * @default null
  944. */
  945. this.src = null;
  946. /**
  947. * The type file that is being loaded. The type of the file is usually inferred by the extension, but can also
  948. * be set manually. This is helpful in cases where a file does not have an extension.
  949. * @property type
  950. * @type {String}
  951. * @default null
  952. */
  953. this.type = null;
  954. /**
  955. * A string identifier which can be used to reference the loaded object. If none is provided, this will be
  956. * automatically set to the {{#crossLink "src:property"}}{{/crossLink}}.
  957. * @property id
  958. * @type {String}
  959. * @default null
  960. */
  961. this.id = null;
  962. /**
  963. * Determines if a manifest will maintain the order of this item, in relation to other items in the manifest
  964. * that have also set the `maintainOrder` property to `true`. This only applies when the max connections has
  965. * been set above 1 (using {{#crossLink "LoadQueue/setMaxConnections"}}{{/crossLink}}). Everything with this
  966. * property set to `false` will finish as it is loaded. Ordered items are combined with script tags loading in
  967. * order when {{#crossLink "LoadQueue/maintainScriptOrder:property"}}{{/crossLink}} is set to `true`.
  968. * @property maintainOrder
  969. * @type {Boolean}
  970. * @default false
  971. */
  972. this.maintainOrder = false;
  973. /**
  974. * A callback used by JSONP requests that defines what global method to call when the JSONP content is loaded.
  975. * @property callback
  976. * @type {String}
  977. * @default null
  978. */
  979. this.callback = null;
  980. /**
  981. * An arbitrary data object, which is included with the loaded object.
  982. * @property data
  983. * @type {Object}
  984. * @default null
  985. */
  986. this.data = null;
  987. /**
  988. * The request method used for HTTP calls. Both {{#crossLink "Methods/GET:property"}}{{/crossLink}} or
  989. * {{#crossLink "Methods/POST:property"}}{{/crossLink}} request types are supported, and are defined as
  990. * constants on {{#crossLink "AbstractLoader"}}{{/crossLink}}.
  991. * @property method
  992. * @type {String}
  993. * @default GET
  994. */
  995. this.method = createjs.Methods.GET;
  996. /**
  997. * An object hash of name/value pairs to send to the server.
  998. * @property values
  999. * @type {Object}
  1000. * @default null
  1001. */
  1002. this.values = null;
  1003. /**
  1004. * An object hash of headers to attach to an XHR request. PreloadJS will automatically attach some default
  1005. * headers when required, including "Origin", "Content-Type", and "X-Requested-With". You may override the
  1006. * default headers by including them in your headers object.
  1007. * @property headers
  1008. * @type {Object}
  1009. * @default null
  1010. */
  1011. this.headers = null;
  1012. /**
  1013. * Enable credentials for XHR requests.
  1014. * @property withCredentials
  1015. * @type {Boolean}
  1016. * @default false
  1017. */
  1018. this.withCredentials = false;
  1019. /**
  1020. * Set the mime type of XHR-based requests. This is automatically set to "text/plain; charset=utf-8" for text
  1021. * based files (json, xml, text, css, js).
  1022. * @property mimeType
  1023. * @type {String}
  1024. * @default null
  1025. */
  1026. this.mimeType = null;
  1027. /**
  1028. * Sets the crossOrigin attribute for CORS-enabled images loading cross-domain.
  1029. * @property crossOrigin
  1030. * @type {boolean}
  1031. * @default Anonymous
  1032. */
  1033. this.crossOrigin = null;
  1034. /**
  1035. * The duration in milliseconds to wait before a request times out. This only applies to tag-based and and XHR
  1036. * (level one) loading, as XHR (level 2) provides its own timeout event.
  1037. * @property loadTimeout
  1038. * @type {Number}
  1039. * @default 8000 (8 seconds)
  1040. */
  1041. this.loadTimeout = s.LOAD_TIMEOUT_DEFAULT;
  1042. };
  1043. var p = LoadItem.prototype = {};
  1044. var s = LoadItem;
  1045. /**
  1046. * Default duration in milliseconds to wait before a request times out. This only applies to tag-based and and XHR
  1047. * (level one) loading, as XHR (level 2) provides its own timeout event.
  1048. * @property LOAD_TIMEOUT_DEFAULT
  1049. * @type {number}
  1050. * @static
  1051. */
  1052. s.LOAD_TIMEOUT_DEFAULT = 8000;
  1053. /**
  1054. * Create a LoadItem.
  1055. * <ul>
  1056. * <li>String-based items are converted to a LoadItem with a populated {{#crossLink "src:property"}}{{/crossLink}}.</li>
  1057. * <li>LoadItem instances are returned as-is</li>
  1058. * <li>Objects are returned with any needed properties added</li>
  1059. * </ul>
  1060. * @method create
  1061. * @param {LoadItem|String|Object} value The load item value
  1062. * @returns {LoadItem|Object}
  1063. * @static
  1064. */
  1065. s.create = function (value) {
  1066. if (typeof value == "string") {
  1067. var item = new LoadItem();
  1068. item.src = value;
  1069. return item;
  1070. } else if (value instanceof s) {
  1071. return value;
  1072. } else if (value instanceof Object && value.src) {
  1073. if (value.loadTimeout == null) {
  1074. value.loadTimeout = s.LOAD_TIMEOUT_DEFAULT;
  1075. }
  1076. return value;
  1077. } else {
  1078. throw new Error("Type not recognized.");
  1079. }
  1080. };
  1081. /**
  1082. * Provides a chainable shortcut method for setting a number of properties on the instance.
  1083. *
  1084. * <h4>Example</h4>
  1085. *
  1086. * var loadItem = new createjs.LoadItem().set({src:"image.png", maintainOrder:true});
  1087. *
  1088. * @method set
  1089. * @param {Object} props A generic object containing properties to copy to the LoadItem instance.
  1090. * @return {LoadItem} Returns the instance the method is called on (useful for chaining calls.)
  1091. */
  1092. p.set = function(props) {
  1093. for (var n in props) { this[n] = props[n]; }
  1094. return this;
  1095. };
  1096. createjs.LoadItem = s;
  1097. }());
  1098. //##############################################################################
  1099. // Methods.js
  1100. //##############################################################################
  1101. (function() {
  1102. var s = {};
  1103. /**
  1104. * Defines a POST request, use for a method value when loading data.
  1105. * @property POST
  1106. * @type {string}
  1107. * @default post
  1108. * @static
  1109. */
  1110. s.POST = "POST";
  1111. /**
  1112. * Defines a GET request, use for a method value when loading data.
  1113. * @property GET
  1114. * @type {string}
  1115. * @default get
  1116. * @static
  1117. */
  1118. s.GET = "GET";
  1119. createjs.Methods = s;
  1120. }());
  1121. //##############################################################################
  1122. // Types.js
  1123. //##############################################################################
  1124. (function() {
  1125. var s = {};
  1126. /**
  1127. * The preload type for generic binary types. Note that images are loaded as binary files when using XHR.
  1128. * @property BINARY
  1129. * @type {String}
  1130. * @default binary
  1131. * @static
  1132. * @since 0.6.0
  1133. */
  1134. s.BINARY = "binary";
  1135. /**
  1136. * The preload type for css files. CSS files are loaded using a &lt;link&gt; when loaded with XHR, or a
  1137. * &lt;style&gt; tag when loaded with tags.
  1138. * @property CSS
  1139. * @type {String}
  1140. * @default css
  1141. * @static
  1142. * @since 0.6.0
  1143. */
  1144. s.CSS = "css";
  1145. /**
  1146. * The preload type for font files.
  1147. * @property FONT
  1148. * @type {String}
  1149. * @default font
  1150. * @static
  1151. * @since 0.9.0
  1152. */
  1153. s.FONT = "font";
  1154. /**
  1155. * The preload type for fonts specified with CSS (such as Google fonts)
  1156. * @property FONTCSS
  1157. * @type {String}
  1158. * @default fontcss
  1159. * @static
  1160. * @since 0.9.0
  1161. */
  1162. s.FONTCSS = "fontcss";
  1163. /**
  1164. * The preload type for image files, usually png, gif, or jpg/jpeg. Images are loaded into an &lt;image&gt; tag.
  1165. * @property IMAGE
  1166. * @type {String}
  1167. * @default image
  1168. * @static
  1169. * @since 0.6.0
  1170. */
  1171. s.IMAGE = "image";
  1172. /**
  1173. * The preload type for javascript files, usually with the "js" file extension. JavaScript files are loaded into a
  1174. * &lt;script&gt; tag.
  1175. *
  1176. * Since version 0.4.1+, due to how tag-loaded scripts work, all JavaScript files are automatically injected into
  1177. * the body of the document to maintain parity between XHR and tag-loaded scripts. In version 0.4.0 and earlier,
  1178. * only tag-loaded scripts are injected.
  1179. * @property JAVASCRIPT
  1180. * @type {String}
  1181. * @default javascript
  1182. * @static
  1183. * @since 0.6.0
  1184. */
  1185. s.JAVASCRIPT = "javascript";
  1186. /**
  1187. * The preload type for json files, usually with the "json" file extension. JSON data is loaded and parsed into a
  1188. * JavaScript object. Note that if a `callback` is present on the load item, the file will be loaded with JSONP,
  1189. * no matter what the {{#crossLink "LoadQueue/preferXHR:property"}}{{/crossLink}} property is set to, and the JSON
  1190. * must contain a matching wrapper function.
  1191. * @property JSON
  1192. * @type {String}
  1193. * @default json
  1194. * @static
  1195. * @since 0.6.0
  1196. */
  1197. s.JSON = "json";
  1198. /**
  1199. * The preload type for jsonp files, usually with the "json" file extension. JSON data is loaded and parsed into a
  1200. * JavaScript object. You are required to pass a callback parameter that matches the function wrapper in the JSON.
  1201. * Note that JSONP will always be used if there is a callback present, no matter what the {{#crossLink "LoadQueue/preferXHR:property"}}{{/crossLink}}
  1202. * property is set to.
  1203. * @property JSONP
  1204. * @type {String}
  1205. * @default jsonp
  1206. * @static
  1207. * @since 0.6.0
  1208. */
  1209. s.JSONP = "jsonp";
  1210. /**
  1211. * The preload type for json-based manifest files, usually with the "json" file extension. The JSON data is loaded
  1212. * and parsed into a JavaScript object. PreloadJS will then look for a "manifest" property in the JSON, which is an
  1213. * Array of files to load, following the same format as the {{#crossLink "LoadQueue/loadManifest"}}{{/crossLink}}
  1214. * method. If a "callback" is specified on the manifest object, then it will be loaded using JSONP instead,
  1215. * regardless of what the {{#crossLink "LoadQueue/preferXHR:property"}}{{/crossLink}} property is set to.
  1216. * @property MANIFEST
  1217. * @type {String}
  1218. * @default manifest
  1219. * @static
  1220. * @since 0.6.0
  1221. */
  1222. s.MANIFEST = "manifest";
  1223. /**
  1224. * The preload type for sound files, usually mp3, ogg, or wav. When loading via tags, audio is loaded into an
  1225. * &lt;audio&gt; tag.
  1226. * @property SOUND
  1227. * @type {String}
  1228. * @default sound
  1229. * @static
  1230. * @since 0.6.0
  1231. */
  1232. s.SOUND = "sound";
  1233. /**
  1234. * The preload type for video files, usually mp4, ts, or ogg. When loading via tags, video is loaded into an
  1235. * &lt;video&gt; tag.
  1236. * @property VIDEO
  1237. * @type {String}
  1238. * @default video
  1239. * @static
  1240. * @since 0.6.0
  1241. */
  1242. s.VIDEO = "video";
  1243. /**
  1244. * The preload type for SpriteSheet files. SpriteSheet files are JSON files that contain string image paths.
  1245. * @property SPRITESHEET
  1246. * @type {String}
  1247. * @default spritesheet
  1248. * @static
  1249. * @since 0.6.0
  1250. */
  1251. s.SPRITESHEET = "spritesheet";
  1252. /**
  1253. * The preload type for SVG files.
  1254. * @property SVG
  1255. * @type {String}
  1256. * @default svg
  1257. * @static
  1258. * @since 0.6.0
  1259. */
  1260. s.SVG = "svg";
  1261. /**
  1262. * The preload type for text files, which is also the default file type if the type can not be determined. Text is
  1263. * loaded as raw text.
  1264. * @property TEXT
  1265. * @type {String}
  1266. * @default text
  1267. * @static
  1268. * @since 0.6.0
  1269. */
  1270. s.TEXT = "text";
  1271. /**
  1272. * The preload type for xml files. XML is loaded into an XML document.
  1273. * @property XML
  1274. * @type {String}
  1275. * @default xml
  1276. * @static
  1277. * @since 0.6.0
  1278. */
  1279. s.XML = "xml";
  1280. createjs.Types = s;
  1281. }());
  1282. //##############################################################################
  1283. // Elements.js
  1284. //##############################################################################
  1285. (function () {
  1286. /**
  1287. * Convenience methods for creating various elements used by PrelaodJS.
  1288. *
  1289. * @class DomUtils
  1290. */
  1291. var s = {};
  1292. s.a = function() {
  1293. return s.el("a");
  1294. }
  1295. s.svg = function() {
  1296. return s.el("svg");
  1297. }
  1298. s.object = function() {
  1299. return s.el("object");
  1300. }
  1301. s.image = function() {
  1302. return s.el("image");
  1303. }
  1304. s.img = function() {
  1305. return s.el("img");
  1306. }
  1307. s.style = function() {
  1308. return s.el("style");
  1309. }
  1310. s.link = function() {
  1311. return s.el("link");
  1312. }
  1313. s.script = function() {
  1314. return s.el("script");
  1315. }
  1316. s.audio = function() {
  1317. return s.el("audio");
  1318. }
  1319. s.video = function() {
  1320. return s.el("video");
  1321. }
  1322. s.text = function(value) {
  1323. return document.createTextNode(value);
  1324. }
  1325. s.el = function(name) {
  1326. return document.createElement(name);
  1327. }
  1328. createjs.Elements = s;
  1329. }());
  1330. //##############################################################################
  1331. // DomUtils.js
  1332. //##############################################################################
  1333. (function () {
  1334. /**
  1335. * A few utilities for interacting with the dom.
  1336. * @class DomUtils
  1337. */
  1338. var s = {
  1339. container: null
  1340. };
  1341. s.appendToHead = function (el) {
  1342. s.getHead().appendChild(el);
  1343. }
  1344. s.appendToBody = function (el) {
  1345. if (s.container == null) {
  1346. s.container = document.createElement("div");
  1347. s.container.id = "preloadjs-container";
  1348. var style = s.container.style;
  1349. style.visibility = "hidden";
  1350. style.position = "absolute";
  1351. style.width = s.container.style.height = "10px";
  1352. style.overflow = "hidden";
  1353. style.transform = style.msTransform = style.webkitTransform = style.oTransform = "translate(-10px, -10px)"; //LM: Not working
  1354. s.getBody().appendChild(s.container);
  1355. }
  1356. s.container.appendChild(el);
  1357. }
  1358. s.getHead = function () {
  1359. return document.head || document.getElementsByTagName("head")[0];
  1360. }
  1361. s.getBody = function () {
  1362. return document.body || document.getElementsByTagName("body")[0];
  1363. }
  1364. s.removeChild = function(el) {
  1365. if (el.parent) {
  1366. el.parent.removeChild(el);
  1367. }
  1368. }
  1369. /**
  1370. * Check if item is a valid HTMLImageElement
  1371. * @method isImageTag
  1372. * @param {Object} item
  1373. * @returns {Boolean}
  1374. * @static
  1375. */
  1376. s.isImageTag = function(item) {
  1377. return item instanceof HTMLImageElement;
  1378. };
  1379. /**
  1380. * Check if item is a valid HTMLAudioElement
  1381. * @method isAudioTag
  1382. * @param {Object} item
  1383. * @returns {Boolean}
  1384. * @static
  1385. */
  1386. s.isAudioTag = function(item) {
  1387. if (window.HTMLAudioElement) {
  1388. return item instanceof HTMLAudioElement;
  1389. } else {
  1390. return false;
  1391. }
  1392. };
  1393. /**
  1394. * Check if item is a valid HTMLVideoElement
  1395. * @method isVideoTag
  1396. * @param {Object} item
  1397. * @returns {Boolean}
  1398. * @static
  1399. */
  1400. s.isVideoTag = function(item) {
  1401. if (window.HTMLVideoElement) {
  1402. return item instanceof HTMLVideoElement;
  1403. } else {
  1404. return false;
  1405. }
  1406. };
  1407. createjs.DomUtils = s;
  1408. }());
  1409. //##############################################################################
  1410. // RequestUtils.js
  1411. //##############################################################################
  1412. (function () {
  1413. /**
  1414. * Utilities that assist with parsing load items, and determining file types, etc.
  1415. * @class RequestUtils
  1416. */
  1417. var s = {};
  1418. /**
  1419. * Determine if a specific type should be loaded as a binary file. Currently, only images and items marked
  1420. * specifically as "binary" are loaded as binary. Note that audio is <b>not</b> a binary type, as we can not play
  1421. * back using an audio tag if it is loaded as binary. Plugins can change the item type to binary to ensure they get
  1422. * a binary result to work with. Binary files are loaded using XHR2. Types are defined as static constants on
  1423. * {{#crossLink "AbstractLoader"}}{{/crossLink}}.
  1424. * @method isBinary
  1425. * @param {String} type The item type.
  1426. * @return {Boolean} If the specified type is binary.
  1427. * @static
  1428. */
  1429. s.isBinary = function (type) {
  1430. switch (type) {
  1431. case createjs.Types.IMAGE:
  1432. case createjs.Types.BINARY:
  1433. return true;
  1434. default:
  1435. return false;
  1436. }
  1437. };
  1438. /**
  1439. * Determine if a specific type is a text-based asset, and should be loaded as UTF-8.
  1440. * @method isText
  1441. * @param {String} type The item type.
  1442. * @return {Boolean} If the specified type is text.
  1443. * @static
  1444. */
  1445. s.isText = function (type) {
  1446. switch (type) {
  1447. case createjs.Types.TEXT:
  1448. case createjs.Types.JSON:
  1449. case createjs.Types.MANIFEST:
  1450. case createjs.Types.XML:
  1451. case createjs.Types.CSS:
  1452. case createjs.Types.SVG:
  1453. case createjs.Types.JAVASCRIPT:
  1454. case createjs.Types.SPRITESHEET:
  1455. return true;
  1456. default:
  1457. return false;
  1458. }
  1459. };
  1460. /**
  1461. * Determine the type of the object using common extensions. Note that the type can be passed in with the load item
  1462. * if it is an unusual extension.
  1463. * @method getTypeByExtension
  1464. * @param {String} extension The file extension to use to determine the load type.
  1465. * @return {String} The determined load type (for example, `createjs.Types.IMAGE`). Will return `null` if
  1466. * the type can not be determined by the extension.
  1467. * @static
  1468. */
  1469. s.getTypeByExtension = function (extension) {
  1470. if (extension == null) {
  1471. return createjs.Types.TEXT;
  1472. }
  1473. switch (extension.toLowerCase()) {
  1474. case "jpeg":
  1475. case "jpg":
  1476. case "gif":
  1477. case "png":
  1478. case "webp":
  1479. case "bmp":
  1480. return createjs.Types.IMAGE;
  1481. case "ogg":
  1482. case "mp3":
  1483. case "webm":
  1484. return createjs.Types.SOUND;
  1485. case "mp4":
  1486. case "webm":
  1487. case "ts":
  1488. return createjs.Types.VIDEO;
  1489. case "json":
  1490. return createjs.Types.JSON;
  1491. case "xml":
  1492. return createjs.Types.XML;
  1493. case "css":
  1494. return createjs.Types.CSS;
  1495. case "js":
  1496. return createjs.Types.JAVASCRIPT;
  1497. case 'svg':
  1498. return createjs.Types.SVG;
  1499. default:
  1500. return createjs.Types.TEXT;
  1501. }
  1502. };
  1503. createjs.RequestUtils = s;
  1504. }());
  1505. //##############################################################################
  1506. // URLUtils.js
  1507. //##############################################################################
  1508. (function () {
  1509. /**
  1510. * Utilities that assist with parsing load items, and determining file types, etc.
  1511. * @class URLUtils
  1512. */
  1513. var s = {};
  1514. /**
  1515. * The Regular Expression used to test file URLS for an absolute path.
  1516. * @property ABSOLUTE_PATH
  1517. * @type {RegExp}
  1518. * @static
  1519. */
  1520. s.ABSOLUTE_PATT = /^(?:\w+:)?\/{2}/i;
  1521. /**
  1522. * The Regular Expression used to test file URLS for a relative path.
  1523. * @property RELATIVE_PATH
  1524. * @type {RegExp}
  1525. * @static
  1526. */
  1527. s.RELATIVE_PATT = (/^[./]*?\//i);
  1528. /**
  1529. * The Regular Expression used to test file URLS for an extension. Note that URIs must already have the query string
  1530. * removed.
  1531. * @property EXTENSION_PATT
  1532. * @type {RegExp}
  1533. * @static
  1534. */
  1535. s.EXTENSION_PATT = /\/?[^/]+\.(\w{1,5})$/i;
  1536. /**
  1537. * Parse a file path to determine the information we need to work with it. Currently, PreloadJS needs to know:
  1538. * <ul>
  1539. * <li>If the path is absolute. Absolute paths start with a protocol (such as `http://`, `file://`, or
  1540. * `//networkPath`)</li>
  1541. * <li>If the path is relative. Relative paths start with `../` or `/path` (or similar)</li>
  1542. * <li>The file extension. This is determined by the filename with an extension. Query strings are dropped, and
  1543. * the file path is expected to follow the format `name.ext`.</li>
  1544. * </ul>
  1545. *
  1546. * @method parseURI
  1547. * @param {String} path
  1548. * @returns {Object} An Object with an `absolute` and `relative` Boolean values,
  1549. * the pieces of the path (protocol, hostname, port, pathname, search, hash, host)
  1550. * as well as an optional 'extension` property, which is the lowercase extension.
  1551. *
  1552. * @static
  1553. */
  1554. s.parseURI = function (path) {
  1555. var info = {
  1556. absolute: false,
  1557. relative: false,
  1558. protocol: null,
  1559. hostname: null,
  1560. port: null,
  1561. pathname: null,
  1562. search: null,
  1563. hash: null,
  1564. host: null
  1565. };
  1566. if (path == null) { return info; }
  1567. // Inject the path parts.
  1568. var parser = createjs.Elements.a();
  1569. parser.href = path;
  1570. for (var n in info) {
  1571. if (n in parser) {
  1572. info[n] = parser[n];
  1573. }
  1574. }
  1575. // Drop the query string
  1576. var queryIndex = path.indexOf("?");
  1577. if (queryIndex > -1) {
  1578. path = path.substr(0, queryIndex);
  1579. }
  1580. // Absolute
  1581. var match;
  1582. if (s.ABSOLUTE_PATT.test(path)) {
  1583. info.absolute = true;
  1584. // Relative
  1585. } else if (s.RELATIVE_PATT.test(path)) {
  1586. info.relative = true;
  1587. }
  1588. // Extension
  1589. if (match = path.match(s.EXTENSION_PATT)) {
  1590. info.extension = match[1].toLowerCase();
  1591. }
  1592. return info;
  1593. };
  1594. /**
  1595. * Formats an object into a query string for either a POST or GET request.
  1596. * @method formatQueryString
  1597. * @param {Object} data The data to convert to a query string.
  1598. * @param {Array} [query] Existing name/value pairs to append on to this query.
  1599. * @static
  1600. */
  1601. s.formatQueryString = function (data, query) {
  1602. if (data == null) {
  1603. throw new Error("You must specify data.");
  1604. }
  1605. var params = [];
  1606. for (var n in data) {
  1607. params.push(n + "=" + escape(data[n]));
  1608. }
  1609. if (query) {
  1610. params = params.concat(query);
  1611. }
  1612. return params.join("&");
  1613. };
  1614. /**
  1615. * A utility method that builds a file path using a source and a data object, and formats it into a new path.
  1616. * @method buildURI
  1617. * @param {String} src The source path to add values to.
  1618. * @param {Object} [data] Object used to append values to this request as a query string. Existing parameters on the
  1619. * path will be preserved.
  1620. * @returns {string} A formatted string that contains the path and the supplied parameters.
  1621. * @static
  1622. */
  1623. s.buildURI = function (src, data) {
  1624. if (data == null) {
  1625. return src;
  1626. }
  1627. var query = [];
  1628. var idx = src.indexOf("?");
  1629. if (idx != -1) {
  1630. var q = src.slice(idx + 1);
  1631. query = query.concat(q.split("&"));
  1632. }
  1633. if (idx != -1) {
  1634. return src.slice(0, idx) + "?" + this.formatQueryString(data, query);
  1635. } else {
  1636. return src + "?" + this.formatQueryString(data, query);
  1637. }
  1638. };
  1639. /**
  1640. * @method isCrossDomain
  1641. * @param {LoadItem|Object} item A load item with a `src` property.
  1642. * @return {Boolean} If the load item is loading from a different domain than the current location.
  1643. * @static
  1644. */
  1645. s.isCrossDomain = function (item) {
  1646. var target = createjs.Elements.a();
  1647. target.href = item.src;
  1648. var host = createjs.Elements.a();
  1649. host.href = location.href;
  1650. var crossdomain = (target.hostname != "") &&
  1651. (target.port != host.port ||
  1652. target.protocol != host.protocol ||
  1653. target.hostname != host.hostname);
  1654. return crossdomain;
  1655. };
  1656. /**
  1657. * @method isLocal
  1658. * @param {LoadItem|Object} item A load item with a `src` property
  1659. * @return {Boolean} If the load item is loading from the "file:" protocol. Assume that the host must be local as
  1660. * well.
  1661. * @static
  1662. */
  1663. s.isLocal = function (item) {
  1664. var target = createjs.Elements.a();
  1665. target.href = item.src;
  1666. return target.hostname == "" && target.protocol == "file:";
  1667. };
  1668. createjs.URLUtils = s;
  1669. }());
  1670. //##############################################################################
  1671. // AbstractLoader.js
  1672. //##############################################################################
  1673. (function () {
  1674. "use strict";
  1675. // constructor
  1676. /**
  1677. * The base loader, which defines all the generic methods, properties, and events. All loaders extend this class,
  1678. * including the {{#crossLink "LoadQueue"}}{{/crossLink}}.
  1679. * @class AbstractLoader
  1680. * @param {LoadItem|object|string} loadItem The item to be loaded.
  1681. * @param {Boolean} [preferXHR] Determines if the LoadItem should <em>try</em> and load using XHR, or take a
  1682. * tag-based approach, which can be better in cross-domain situations. Not all loaders can load using one or the
  1683. * other, so this is a suggested directive.
  1684. * @param {String} [type] The type of loader. Loader types are defined as constants on the AbstractLoader class,
  1685. * such as {{#crossLink "IMAGE:property"}}{{/crossLink}}, {{#crossLink "CSS:property"}}{{/crossLink}}, etc.
  1686. * @extends EventDispatcher
  1687. */
  1688. function AbstractLoader(loadItem, preferXHR, type) {
  1689. this.EventDispatcher_constructor();
  1690. // public properties
  1691. /**
  1692. * If the loader has completed loading. This provides a quick check, but also ensures that the different approaches
  1693. * used for loading do not pile up resulting in more than one `complete` {{#crossLink "Event"}}{{/crossLink}}.
  1694. * @property loaded
  1695. * @type {Boolean}
  1696. * @default false
  1697. */
  1698. this.loaded = false;
  1699. /**
  1700. * Determine if the loader was canceled. Canceled loads will not fire complete events. Note that this property
  1701. * is readonly, so {{#crossLink "LoadQueue"}}{{/crossLink}} queues should be closed using {{#crossLink "LoadQueue/close"}}{{/crossLink}}
  1702. * instead.
  1703. * @property canceled
  1704. * @type {Boolean}
  1705. * @default false
  1706. * @readonly
  1707. */
  1708. this.canceled = false;
  1709. /**
  1710. * The current load progress (percentage) for this item. This will be a number between 0 and 1.
  1711. *
  1712. * <h4>Example</h4>
  1713. *
  1714. * var queue = new createjs.LoadQueue();
  1715. * queue.loadFile("largeImage.png");
  1716. * queue.on("progress", function() {
  1717. * console.log("Progress:", queue.progress, event.progress);
  1718. * });
  1719. *
  1720. * @property progress
  1721. * @type {Number}
  1722. * @default 0
  1723. */
  1724. this.progress = 0;
  1725. /**
  1726. * The type of item this loader will load. See {{#crossLink "AbstractLoader"}}{{/crossLink}} for a full list of
  1727. * supported types.
  1728. * @property type
  1729. * @type {String}
  1730. */
  1731. this.type = type;
  1732. /**
  1733. * A formatter function that converts the loaded raw result into the final result. For example, the JSONLoader
  1734. * converts a string of text into a JavaScript object. Not all loaders have a resultFormatter, and this property
  1735. * can be overridden to provide custom formatting.
  1736. *
  1737. * Optionally, a resultFormatter can return a callback function in cases where the formatting needs to be
  1738. * asynchronous, such as creating a new image. The callback function is passed 2 parameters, which are callbacks
  1739. * to handle success and error conditions in the resultFormatter. Note that the resultFormatter method is
  1740. * called in the current scope, as well as the success and error callbacks.
  1741. *
  1742. * <h4>Example asynchronous resultFormatter</h4>
  1743. *
  1744. * function _formatResult(loader) {
  1745. * return function(success, error) {
  1746. * if (errorCondition) { error(errorDetailEvent); }
  1747. * success(result);
  1748. * }
  1749. * }
  1750. * @property resultFormatter
  1751. * @type {Function}
  1752. * @default null
  1753. */
  1754. this.resultFormatter = null;
  1755. // protected properties
  1756. /**
  1757. * The {{#crossLink "LoadItem"}}{{/crossLink}} this loader represents. Note that this is null in a {{#crossLink "LoadQueue"}}{{/crossLink}},
  1758. * but will be available on loaders such as {{#crossLink "XMLLoader"}}{{/crossLink}} and {{#crossLink "ImageLoader"}}{{/crossLink}}.
  1759. * @property _item
  1760. * @type {LoadItem|Object}
  1761. * @private
  1762. */
  1763. if (loadItem) {
  1764. this._item = createjs.LoadItem.create(loadItem);
  1765. } else {
  1766. this._item = null;
  1767. }
  1768. /**
  1769. * Whether the loader will try and load content using XHR (true) or HTML tags (false).
  1770. * @property _preferXHR
  1771. * @type {Boolean}
  1772. * @private
  1773. */
  1774. this._preferXHR = preferXHR;
  1775. /**
  1776. * The loaded result after it is formatted by an optional {{#crossLink "resultFormatter"}}{{/crossLink}}. For
  1777. * items that are not formatted, this will be the same as the {{#crossLink "_rawResult:property"}}{{/crossLink}}.
  1778. * The result is accessed using the {{#crossLink "getResult"}}{{/crossLink}} method.
  1779. * @property _result
  1780. * @type {Object|String}
  1781. * @private
  1782. */
  1783. this._result = null;
  1784. /**
  1785. * The loaded result before it is formatted. The rawResult is accessed using the {{#crossLink "getResult"}}{{/crossLink}}
  1786. * method, and passing `true`.
  1787. * @property _rawResult
  1788. * @type {Object|String}
  1789. * @private
  1790. */
  1791. this._rawResult = null;
  1792. /**
  1793. * A list of items that loaders load behind the scenes. This does not include the main item the loader is
  1794. * responsible for loading. Examples of loaders that have sub-items include the {{#crossLink "SpriteSheetLoader"}}{{/crossLink}} and
  1795. * {{#crossLink "ManifestLoader"}}{{/crossLink}}.
  1796. * @property _loadItems
  1797. * @type {null}
  1798. * @protected
  1799. */
  1800. this._loadedItems = null;
  1801. /**
  1802. * The attribute the items loaded using tags use for the source.
  1803. * @type {string}
  1804. * @default null
  1805. * @private
  1806. */
  1807. this._tagSrcAttribute = null;
  1808. /**
  1809. * An HTML tag (or similar) that a loader may use to load HTML content, such as images, scripts, etc.
  1810. * @property _tag
  1811. * @type {Object}
  1812. * @private
  1813. */
  1814. this._tag = null;
  1815. };
  1816. var p = createjs.extend(AbstractLoader, createjs.EventDispatcher);
  1817. var s = AbstractLoader;
  1818. // Remove these @deprecated properties after 1.0
  1819. try {
  1820. Object.defineProperties(s, {
  1821. POST: { get: createjs.deprecate(function() { return createjs.Methods.POST; }, "AbstractLoader.POST") },
  1822. GET: { get: createjs.deprecate(function() { return createjs.Methods.GET; }, "AbstractLoader.GET") },
  1823. BINARY: { get: createjs.deprecate(function() { return createjs.Types.BINARY; }, "AbstractLoader.BINARY") },
  1824. CSS: { get: createjs.deprecate(function() { return createjs.Types.CSS; }, "AbstractLoader.CSS") },
  1825. FONT: { get: createjs.deprecate(function() { return createjs.Types.FONT; }, "AbstractLoader.FONT") },
  1826. FONTCSS: { get: createjs.deprecate(function() { return createjs.Types.FONTCSS; }, "AbstractLoader.FONTCSS") },
  1827. IMAGE: { get: createjs.deprecate(function() { return createjs.Types.IMAGE; }, "AbstractLoader.IMAGE") },
  1828. JAVASCRIPT: { get: createjs.deprecate(function() { return createjs.Types.JAVASCRIPT; }, "AbstractLoader.JAVASCRIPT") },
  1829. JSON: { get: createjs.deprecate(function() { return createjs.Types.JSON; }, "AbstractLoader.JSON") },
  1830. JSONP: { get: createjs.deprecate(function() { return createjs.Types.JSONP; }, "AbstractLoader.JSONP") },
  1831. MANIFEST: { get: createjs.deprecate(function() { return createjs.Types.MANIFEST; }, "AbstractLoader.MANIFEST") },
  1832. SOUND: { get: createjs.deprecate(function() { return createjs.Types.SOUND; }, "AbstractLoader.SOUND") },
  1833. VIDEO: { get: createjs.deprecate(function() { return createjs.Types.VIDEO; }, "AbstractLoader.VIDEO") },
  1834. SPRITESHEET: { get: createjs.deprecate(function() { return createjs.Types.SPRITESHEET; }, "AbstractLoader.SPRITESHEET") },
  1835. SVG: { get: createjs.deprecate(function() { return createjs.Types.SVG; }, "AbstractLoader.SVG") },
  1836. TEXT: { get: createjs.deprecate(function() { return createjs.Types.TEXT; }, "AbstractLoader.TEXT") },
  1837. XML: { get: createjs.deprecate(function() { return createjs.Types.XML; }, "AbstractLoader.XML") }
  1838. });
  1839. } catch (e) {}
  1840. // Events
  1841. /**
  1842. * The {{#crossLink "ProgressEvent"}}{{/crossLink}} that is fired when the overall progress changes. Prior to
  1843. * version 0.6.0, this was just a regular {{#crossLink "Event"}}{{/crossLink}}.
  1844. * @event progress
  1845. * @since 0.3.0
  1846. */
  1847. /**
  1848. * The {{#crossLink "Event"}}{{/crossLink}} that is fired when a load starts.
  1849. * @event loadstart
  1850. * @param {Object} target The object that dispatched the event.
  1851. * @param {String} type The event type.
  1852. * @since 0.3.1
  1853. */
  1854. /**
  1855. * The {{#crossLink "Event"}}{{/crossLink}} that is fired when the entire queue has been loaded.
  1856. * @event complete
  1857. * @param {Object} target The object that dispatched the event.
  1858. * @param {String} type The event type.
  1859. * @since 0.3.0
  1860. */
  1861. /**
  1862. * The {{#crossLink "ErrorEvent"}}{{/crossLink}} that is fired when the loader encounters an error. If the error was
  1863. * encountered by a file, the event will contain the item that caused the error. Prior to version 0.6.0, this was
  1864. * just a regular {{#crossLink "Event"}}{{/crossLink}}.
  1865. * @event error
  1866. * @since 0.3.0
  1867. */
  1868. /**
  1869. * The {{#crossLink "Event"}}{{/crossLink}} that is fired when the loader encounters an internal file load error.
  1870. * This enables loaders to maintain internal queues, and surface file load errors.
  1871. * @event fileerror
  1872. * @param {Object} target The object that dispatched the event.
  1873. * @param {String} type The event type ("fileerror")
  1874. * @param {LoadItem|object} The item that encountered the error
  1875. * @since 0.6.0
  1876. */
  1877. /**
  1878. * The {{#crossLink "Event"}}{{/crossLink}} that is fired when a loader internally loads a file. This enables
  1879. * loaders such as {{#crossLink "ManifestLoader"}}{{/crossLink}} to maintain internal {{#crossLink "LoadQueue"}}{{/crossLink}}s
  1880. * and notify when they have loaded a file. The {{#crossLink "LoadQueue"}}{{/crossLink}} class dispatches a
  1881. * slightly different {{#crossLink "LoadQueue/fileload:event"}}{{/crossLink}} event.
  1882. * @event fileload
  1883. * @param {Object} target The object that dispatched the event.
  1884. * @param {String} type The event type ("fileload")
  1885. * @param {Object} item The file item which was specified in the {{#crossLink "LoadQueue/loadFile"}}{{/crossLink}}
  1886. * or {{#crossLink "LoadQueue/loadManifest"}}{{/crossLink}} call. If only a string path or tag was specified, the
  1887. * object will contain that value as a `src` property.
  1888. * @param {Object} result The HTML tag or parsed result of the loaded item.
  1889. * @param {Object} rawResult The unprocessed result, usually the raw text or binary data before it is converted
  1890. * to a usable object.
  1891. * @since 0.6.0
  1892. */
  1893. /**
  1894. * The {{#crossLink "Event"}}{{/crossLink}} that is fired after the internal request is created, but before a load.
  1895. * This allows updates to the loader for specific loading needs, such as binary or XHR image loading.
  1896. * @event initialize
  1897. * @param {Object} target The object that dispatched the event.
  1898. * @param {String} type The event type ("initialize")
  1899. * @param {AbstractLoader} loader The loader that has been initialized.
  1900. */
  1901. /**
  1902. * Get a reference to the manifest item that is loaded by this loader. In some cases this will be the value that was
  1903. * passed into {{#crossLink "LoadQueue"}}{{/crossLink}} using {{#crossLink "LoadQueue/loadFile"}}{{/crossLink}} or
  1904. * {{#crossLink "LoadQueue/loadManifest"}}{{/crossLink}}. However if only a String path was passed in, then it will
  1905. * be a {{#crossLink "LoadItem"}}{{/crossLink}}.
  1906. * @method getItem
  1907. * @return {Object} The manifest item that this loader is responsible for loading.
  1908. * @since 0.6.0
  1909. */
  1910. p.getItem = function () {
  1911. return this._item;
  1912. };
  1913. /**
  1914. * Get a reference to the content that was loaded by the loader (only available after the {{#crossLink "complete:event"}}{{/crossLink}}
  1915. * event is dispatched.
  1916. * @method getResult
  1917. * @param {Boolean} [raw=false] Determines if the returned result will be the formatted content, or the raw loaded
  1918. * data (if it exists).
  1919. * @return {Object}
  1920. * @since 0.6.0
  1921. */
  1922. p.getResult = function (raw) {
  1923. return raw ? this._rawResult : this._result;
  1924. };
  1925. /**
  1926. * Return the `tag` this object creates or uses for loading.
  1927. * @method getTag
  1928. * @return {Object} The tag instance
  1929. * @since 0.6.0
  1930. */
  1931. p.getTag = function () {
  1932. return this._tag;
  1933. };
  1934. /**
  1935. * Set the `tag` this item uses for loading.
  1936. * @method setTag
  1937. * @param {Object} tag The tag instance
  1938. * @since 0.6.0
  1939. */
  1940. p.setTag = function(tag) {
  1941. this._tag = tag;
  1942. };
  1943. /**
  1944. * Begin loading the item. This method is required when using a loader by itself.
  1945. *
  1946. * <h4>Example</h4>
  1947. *
  1948. * var queue = new createjs.LoadQueue();
  1949. * queue.on("complete", handleComplete);
  1950. * queue.loadManifest(fileArray, false); // Note the 2nd argument that tells the queue not to start loading yet
  1951. * queue.load();
  1952. *
  1953. * @method load
  1954. */
  1955. p.load = function () {
  1956. this._createRequest();
  1957. this._request.on("complete", this, this);
  1958. this._request.on("progress", this, this);
  1959. this._request.on("loadStart", this, this);
  1960. this._request.on("abort", this, this);
  1961. this._request.on("timeout", this, this);
  1962. this._request.on("error", this, this);
  1963. var evt = new createjs.Event("initialize");
  1964. evt.loader = this._request;
  1965. this.dispatchEvent(evt);
  1966. this._request.load();
  1967. };
  1968. /**
  1969. * Close the the item. This will stop any open requests (although downloads using HTML tags may still continue in
  1970. * the background), but events will not longer be dispatched.
  1971. * @method cancel
  1972. */
  1973. p.cancel = function () {
  1974. this.canceled = true;
  1975. this.destroy();
  1976. };
  1977. /**
  1978. * Clean up the loader.
  1979. * @method destroy
  1980. */
  1981. p.destroy = function() {
  1982. if (this._request) {
  1983. this._request.removeAllEventListeners();
  1984. this._request.destroy();
  1985. }
  1986. this._request = null;
  1987. this._item = null;
  1988. this._rawResult = null;
  1989. this._result = null;
  1990. this._loadItems = null;
  1991. this.removeAllEventListeners();
  1992. };
  1993. /**
  1994. * Get any items loaded internally by the loader. The enables loaders such as {{#crossLink "ManifestLoader"}}{{/crossLink}}
  1995. * to expose items it loads internally.
  1996. * @method getLoadedItems
  1997. * @return {Array} A list of the items loaded by the loader.
  1998. * @since 0.6.0
  1999. */
  2000. p.getLoadedItems = function () {
  2001. return this._loadedItems;
  2002. };
  2003. // Private methods
  2004. /**
  2005. * Create an internal request used for loading. By default, an {{#crossLink "XHRRequest"}}{{/crossLink}} or
  2006. * {{#crossLink "TagRequest"}}{{/crossLink}} is created, depending on the value of {{#crossLink "preferXHR:property"}}{{/crossLink}}.
  2007. * Other loaders may override this to use different request types, such as {{#crossLink "ManifestLoader"}}{{/crossLink}},
  2008. * which uses {{#crossLink "JSONLoader"}}{{/crossLink}} or {{#crossLink "JSONPLoader"}}{{/crossLink}} under the hood.
  2009. * @method _createRequest
  2010. * @protected
  2011. */
  2012. p._createRequest = function() {
  2013. if (!this._preferXHR) {
  2014. this._request = new createjs.TagRequest(this._item, this._tag || this._createTag(), this._tagSrcAttribute);
  2015. } else {
  2016. this._request = new createjs.XHRRequest(this._item);
  2017. }
  2018. };
  2019. /**
  2020. * Create the HTML tag used for loading. This method does nothing by default, and needs to be implemented
  2021. * by loaders that require tag loading.
  2022. * @method _createTag
  2023. * @param {String} src The tag source
  2024. * @return {HTMLElement} The tag that was created
  2025. * @protected
  2026. */
  2027. p._createTag = function(src) { return null; };
  2028. /**
  2029. * Dispatch a loadstart {{#crossLink "Event"}}{{/crossLink}}. Please see the {{#crossLink "AbstractLoader/loadstart:event"}}{{/crossLink}}
  2030. * event for details on the event payload.
  2031. * @method _sendLoadStart
  2032. * @protected
  2033. */
  2034. p._sendLoadStart = function () {
  2035. if (this._isCanceled()) { return; }
  2036. this.dispatchEvent("loadstart");
  2037. };
  2038. /**
  2039. * Dispatch a {{#crossLink "ProgressEvent"}}{{/crossLink}}.
  2040. * @method _sendProgress
  2041. * @param {Number | Object} value The progress of the loaded item, or an object containing <code>loaded</code>
  2042. * and <code>total</code> properties.
  2043. * @protected
  2044. */
  2045. p._sendProgress = function (value) {
  2046. if (this._isCanceled()) { return; }
  2047. var event = null;
  2048. if (typeof(value) == "number") {
  2049. this.progress = value;
  2050. event = new createjs.ProgressEvent(this.progress);
  2051. } else {
  2052. event = value;
  2053. this.progress = value.loaded / value.total;
  2054. event.progress = this.progress;
  2055. if (isNaN(this.progress) || this.progress == Infinity) { this.progress = 0; }
  2056. }
  2057. this.hasEventListener("progress") && this.dispatchEvent(event);
  2058. };
  2059. /**
  2060. * Dispatch a complete {{#crossLink "Event"}}{{/crossLink}}. Please see the {{#crossLink "AbstractLoader/complete:event"}}{{/crossLink}} event
  2061. * @method _sendComplete
  2062. * @protected
  2063. */
  2064. p._sendComplete = function () {
  2065. if (this._isCanceled()) { return; }
  2066. this.loaded = true;
  2067. var event = new createjs.Event("complete");
  2068. event.rawResult = this._rawResult;
  2069. if (this._result != null) {
  2070. event.result = this._result;
  2071. }
  2072. this.dispatchEvent(event);
  2073. };
  2074. /**
  2075. * Dispatch an error {{#crossLink "Event"}}{{/crossLink}}. Please see the {{#crossLink "AbstractLoader/error:event"}}{{/crossLink}}
  2076. * event for details on the event payload.
  2077. * @method _sendError
  2078. * @param {ErrorEvent} event The event object containing specific error properties.
  2079. * @protected
  2080. */
  2081. p._sendError = function (event) {
  2082. if (this._isCanceled() || !this.hasEventListener("error")) { return; }
  2083. if (event == null) {
  2084. event = new createjs.ErrorEvent("PRELOAD_ERROR_EMPTY"); // TODO: Populate error
  2085. }
  2086. this.dispatchEvent(event);
  2087. };
  2088. /**
  2089. * Determine if the load has been canceled. This is important to ensure that method calls or asynchronous events
  2090. * do not cause issues after the queue has been cleaned up.
  2091. * @method _isCanceled
  2092. * @return {Boolean} If the loader has been canceled.
  2093. * @protected
  2094. */
  2095. p._isCanceled = function () {
  2096. if (window.createjs == null || this.canceled) {
  2097. return true;
  2098. }
  2099. return false;
  2100. };
  2101. /**
  2102. * A custom result formatter function, which is called just before a request dispatches its complete event. Most
  2103. * loader types already have an internal formatter, but this can be user-overridden for custom formatting. The
  2104. * formatted result will be available on Loaders using {{#crossLink "getResult"}}{{/crossLink}}, and passing `true`.
  2105. * @property resultFormatter
  2106. * @type Function
  2107. * @return {Object} The formatted result
  2108. * @since 0.6.0
  2109. */
  2110. p.resultFormatter = null;
  2111. /**
  2112. * Handle events from internal requests. By default, loaders will handle, and redispatch the necessary events, but
  2113. * this method can be overridden for custom behaviours.
  2114. * @method handleEvent
  2115. * @param {Event} event The event that the internal request dispatches.
  2116. * @protected
  2117. * @since 0.6.0
  2118. */
  2119. p.handleEvent = function (event) {
  2120. switch (event.type) {
  2121. case "complete":
  2122. this._rawResult = event.target._response;
  2123. var result = this.resultFormatter && this.resultFormatter(this);
  2124. // The resultFormatter is asynchronous
  2125. if (result instanceof Function) {
  2126. result.call(this,
  2127. createjs.proxy(this._resultFormatSuccess, this),
  2128. createjs.proxy(this._resultFormatFailed, this)
  2129. );
  2130. // The result formatter is synchronous
  2131. } else {
  2132. this._result = result || this._rawResult;
  2133. this._sendComplete();
  2134. }
  2135. break;
  2136. case "progress":
  2137. this._sendProgress(event);
  2138. break;
  2139. case "error":
  2140. this._sendError(event);
  2141. break;
  2142. case "loadstart":
  2143. this._sendLoadStart();
  2144. break;
  2145. case "abort":
  2146. case "timeout":
  2147. if (!this._isCanceled()) {
  2148. this.dispatchEvent(new createjs.ErrorEvent("PRELOAD_" + event.type.toUpperCase() + "_ERROR"));
  2149. }
  2150. break;
  2151. }
  2152. };
  2153. /**
  2154. * The "success" callback passed to {{#crossLink "AbstractLoader/resultFormatter"}}{{/crossLink}} asynchronous
  2155. * functions.
  2156. * @method _resultFormatSuccess
  2157. * @param {Object} result The formatted result
  2158. * @private
  2159. */
  2160. p._resultFormatSuccess = function (result) {
  2161. this._result = result;
  2162. this._sendComplete();
  2163. };
  2164. /**
  2165. * The "error" callback passed to {{#crossLink "AbstractLoader/resultFormatter"}}{{/crossLink}} asynchronous
  2166. * functions.
  2167. * @method _resultFormatSuccess
  2168. * @param {Object} error The error event
  2169. * @private
  2170. */
  2171. p._resultFormatFailed = function (event) {
  2172. this._sendError(event);
  2173. };
  2174. /**
  2175. * @method toString
  2176. * @return {String} a string representation of the instance.
  2177. */
  2178. p.toString = function () {
  2179. return "[PreloadJS AbstractLoader]";
  2180. };
  2181. createjs.AbstractLoader = createjs.promote(AbstractLoader, "EventDispatcher");
  2182. }());
  2183. //##############################################################################
  2184. // AbstractMediaLoader.js
  2185. //##############################################################################
  2186. (function () {
  2187. "use strict";
  2188. // constructor
  2189. /**
  2190. * The AbstractMediaLoader is a base class that handles some of the shared methods and properties of loaders that
  2191. * handle HTML media elements, such as Video and Audio.
  2192. * @class AbstractMediaLoader
  2193. * @param {LoadItem|Object} loadItem
  2194. * @param {Boolean} preferXHR
  2195. * @param {String} type The type of media to load. Usually "video" or "audio".
  2196. * @extends AbstractLoader
  2197. * @constructor
  2198. */
  2199. function AbstractMediaLoader(loadItem, preferXHR, type) {
  2200. this.AbstractLoader_constructor(loadItem, preferXHR, type);
  2201. // public properties
  2202. this.resultFormatter = this._formatResult;
  2203. // protected properties
  2204. this._tagSrcAttribute = "src";
  2205. this.on("initialize", this._updateXHR, this);
  2206. };
  2207. var p = createjs.extend(AbstractMediaLoader, createjs.AbstractLoader);
  2208. // static properties
  2209. // public methods
  2210. p.load = function () {
  2211. // TagRequest will handle most of this, but Sound / Video need a few custom properties, so just handle them here.
  2212. if (!this._tag) {
  2213. this._tag = this._createTag(this._item.src);
  2214. }
  2215. this._tag.preload = "auto";
  2216. this._tag.load();
  2217. this.AbstractLoader_load();
  2218. };
  2219. // protected methods
  2220. /**
  2221. * Creates a new tag for loading if it doesn't exist yet.
  2222. * @method _createTag
  2223. * @private
  2224. */
  2225. p._createTag = function () {};
  2226. p._createRequest = function() {
  2227. if (!this._preferXHR) {
  2228. this._request = new createjs.MediaTagRequest(this._item, this._tag || this._createTag(), this._tagSrcAttribute);
  2229. } else {
  2230. this._request = new createjs.XHRRequest(this._item);
  2231. }
  2232. };
  2233. // protected methods
  2234. /**
  2235. * Before the item loads, set its mimeType and responseType.
  2236. * @property _updateXHR
  2237. * @param {Event} event
  2238. * @private
  2239. */
  2240. p._updateXHR = function (event) {
  2241. // Only exists for XHR
  2242. if (event.loader.setResponseType) {
  2243. event.loader.setResponseType("blob");
  2244. }
  2245. };
  2246. /**
  2247. * The result formatter for media files.
  2248. * @method _formatResult
  2249. * @param {AbstractLoader} loader
  2250. * @returns {HTMLVideoElement|HTMLAudioElement}
  2251. * @private
  2252. */
  2253. p._formatResult = function (loader) {
  2254. this._tag.removeEventListener && this._tag.removeEventListener("canplaythrough", this._loadedHandler);
  2255. this._tag.onstalled = null;
  2256. if (this._preferXHR) {
  2257. var URL = window.URL || window.webkitURL;
  2258. var result = loader.getResult(true);
  2259. loader.getTag().src = URL.createObjectURL(result);
  2260. }
  2261. return loader.getTag();
  2262. };
  2263. createjs.AbstractMediaLoader = createjs.promote(AbstractMediaLoader, "AbstractLoader");
  2264. }());
  2265. //##############################################################################
  2266. // AbstractRequest.js
  2267. //##############################################################################
  2268. (function () {
  2269. "use strict";
  2270. /**
  2271. * A base class for actual data requests, such as {{#crossLink "XHRRequest"}}{{/crossLink}}, {{#crossLink "TagRequest"}}{{/crossLink}},
  2272. * and {{#crossLink "MediaRequest"}}{{/crossLink}}. PreloadJS loaders will typically use a data loader under the
  2273. * hood to get data.
  2274. * @class AbstractRequest
  2275. * @param {LoadItem} item
  2276. * @constructor
  2277. */
  2278. var AbstractRequest = function (item) {
  2279. this._item = item;
  2280. };
  2281. var p = createjs.extend(AbstractRequest, createjs.EventDispatcher);
  2282. // public methods
  2283. /**
  2284. * Begin a load.
  2285. * @method load
  2286. */
  2287. p.load = function() {};
  2288. /**
  2289. * Clean up a request.
  2290. * @method destroy
  2291. */
  2292. p.destroy = function() {};
  2293. /**
  2294. * Cancel an in-progress request.
  2295. * @method cancel
  2296. */
  2297. p.cancel = function() {};
  2298. createjs.AbstractRequest = createjs.promote(AbstractRequest, "EventDispatcher");
  2299. }());
  2300. //##############################################################################
  2301. // TagRequest.js
  2302. //##############################################################################
  2303. (function () {
  2304. "use strict";
  2305. // constructor
  2306. /**
  2307. * An {{#crossLink "AbstractRequest"}}{{/crossLink}} that loads HTML tags, such as images and scripts.
  2308. * @class TagRequest
  2309. * @param {LoadItem} loadItem
  2310. * @param {HTMLElement} tag
  2311. * @param {String} srcAttribute The tag attribute that specifies the source, such as "src", "href", etc.
  2312. */
  2313. function TagRequest(loadItem, tag, srcAttribute) {
  2314. this.AbstractRequest_constructor(loadItem);
  2315. // protected properties
  2316. /**
  2317. * The HTML tag instance that is used to load.
  2318. * @property _tag
  2319. * @type {HTMLElement}
  2320. * @protected
  2321. */
  2322. this._tag = tag;
  2323. /**
  2324. * The tag attribute that specifies the source, such as "src", "href", etc.
  2325. * @property _tagSrcAttribute
  2326. * @type {String}
  2327. * @protected
  2328. */
  2329. this._tagSrcAttribute = srcAttribute;
  2330. /**
  2331. * A method closure used for handling the tag load event.
  2332. * @property _loadedHandler
  2333. * @type {Function}
  2334. * @private
  2335. */
  2336. this._loadedHandler = createjs.proxy(this._handleTagComplete, this);
  2337. /**
  2338. * Determines if the element was added to the DOM automatically by PreloadJS, so it can be cleaned up after.
  2339. * @property _addedToDOM
  2340. * @type {Boolean}
  2341. * @private
  2342. */
  2343. this._addedToDOM = false;
  2344. };
  2345. var p = createjs.extend(TagRequest, createjs.AbstractRequest);
  2346. // public methods
  2347. p.load = function () {
  2348. this._tag.onload = createjs.proxy(this._handleTagComplete, this);
  2349. this._tag.onreadystatechange = createjs.proxy(this._handleReadyStateChange, this);
  2350. this._tag.onerror = createjs.proxy(this._handleError, this);
  2351. var evt = new createjs.Event("initialize");
  2352. evt.loader = this._tag;
  2353. this.dispatchEvent(evt);
  2354. this._loadTimeout = setTimeout(createjs.proxy(this._handleTimeout, this), this._item.loadTimeout);
  2355. this._tag[this._tagSrcAttribute] = this._item.src;
  2356. // wdg:: Append the tag AFTER setting the src, or SVG loading on iOS will fail.
  2357. if (this._tag.parentNode == null) {
  2358. createjs.DomUtils.appendToBody(this._tag);
  2359. this._addedToDOM = true;
  2360. }
  2361. };
  2362. p.destroy = function() {
  2363. this._clean();
  2364. this._tag = null;
  2365. this.AbstractRequest_destroy();
  2366. };
  2367. // private methods
  2368. /**
  2369. * Handle the readyStateChange event from a tag. We need this in place of the `onload` callback (mainly SCRIPT
  2370. * and LINK tags), but other cases may exist.
  2371. * @method _handleReadyStateChange
  2372. * @private
  2373. */
  2374. p._handleReadyStateChange = function () {
  2375. clearTimeout(this._loadTimeout);
  2376. // This is strictly for tags in browsers that do not support onload.
  2377. var tag = this._tag;
  2378. // Complete is for old IE support.
  2379. if (tag.readyState == "loaded" || tag.readyState == "complete") {
  2380. this._handleTagComplete();
  2381. }
  2382. };
  2383. /**
  2384. * Handle any error events from the tag.
  2385. * @method _handleError
  2386. * @protected
  2387. */
  2388. p._handleError = function() {
  2389. this._clean();
  2390. this.dispatchEvent("error");
  2391. };
  2392. /**
  2393. * Handle the tag's onload callback.
  2394. * @method _handleTagComplete
  2395. * @private
  2396. */
  2397. p._handleTagComplete = function () {
  2398. this._rawResult = this._tag;
  2399. this._result = this.resultFormatter && this.resultFormatter(this) || this._rawResult;
  2400. this._clean();
  2401. this.dispatchEvent("complete");
  2402. };
  2403. /**
  2404. * The tag request has not loaded within the time specified in loadTimeout.
  2405. * @method _handleError
  2406. * @param {Object} event The XHR error event.
  2407. * @private
  2408. */
  2409. p._handleTimeout = function () {
  2410. this._clean();
  2411. this.dispatchEvent(new createjs.Event("timeout"));
  2412. };
  2413. /**
  2414. * Remove event listeners, but don't destroy the request object
  2415. * @method _clean
  2416. * @private
  2417. */
  2418. p._clean = function() {
  2419. this._tag.onload = null;
  2420. this._tag.onreadystatechange = null;
  2421. this._tag.onerror = null;
  2422. if (this._addedToDOM && this._tag.parentNode != null) {
  2423. this._tag.parentNode.removeChild(this._tag);
  2424. }
  2425. clearTimeout(this._loadTimeout);
  2426. };
  2427. /**
  2428. * Handle a stalled audio event. The main place this happens is with HTMLAudio in Chrome when playing back audio
  2429. * that is already in a load, but not complete.
  2430. * @method _handleStalled
  2431. * @private
  2432. */
  2433. p._handleStalled = function () {
  2434. //Ignore, let the timeout take care of it. Sometimes its not really stopped.
  2435. };
  2436. createjs.TagRequest = createjs.promote(TagRequest, "AbstractRequest");
  2437. }());
  2438. //##############################################################################
  2439. // MediaTagRequest.js
  2440. //##############################################################################
  2441. (function () {
  2442. "use strict";
  2443. // constructor
  2444. /**
  2445. * An {{#crossLink "TagRequest"}}{{/crossLink}} that loads HTML tags for video and audio.
  2446. * @class MediaTagRequest
  2447. * @param {LoadItem} loadItem
  2448. * @param {HTMLAudioElement|HTMLVideoElement} tag
  2449. * @param {String} srcAttribute The tag attribute that specifies the source, such as "src", "href", etc.
  2450. * @constructor
  2451. */
  2452. function MediaTagRequest(loadItem, tag, srcAttribute) {
  2453. this.AbstractRequest_constructor(loadItem);
  2454. // protected properties
  2455. this._tag = tag;
  2456. this._tagSrcAttribute = srcAttribute;
  2457. this._loadedHandler = createjs.proxy(this._handleTagComplete, this);
  2458. };
  2459. var p = createjs.extend(MediaTagRequest, createjs.TagRequest);
  2460. var s = MediaTagRequest;
  2461. // public methods
  2462. p.load = function () {
  2463. var sc = createjs.proxy(this._handleStalled, this);
  2464. this._stalledCallback = sc;
  2465. var pc = createjs.proxy(this._handleProgress, this);
  2466. this._handleProgress = pc;
  2467. this._tag.addEventListener("stalled", sc);
  2468. this._tag.addEventListener("progress", pc);
  2469. // This will tell us when audio is buffered enough to play through, but not when its loaded.
  2470. // The tag doesn't keep loading in Chrome once enough has buffered, and we have decided that behaviour is sufficient.
  2471. this._tag.addEventListener && this._tag.addEventListener("canplaythrough", this._loadedHandler, false); // canplaythrough callback doesn't work in Chrome, so we use an event.
  2472. this.TagRequest_load();
  2473. };
  2474. // private methods
  2475. p._handleReadyStateChange = function () {
  2476. clearTimeout(this._loadTimeout);
  2477. // This is strictly for tags in browsers that do not support onload.
  2478. var tag = this._tag;
  2479. // Complete is for old IE support.
  2480. if (tag.readyState == "loaded" || tag.readyState == "complete") {
  2481. this._handleTagComplete();
  2482. }
  2483. };
  2484. p._handleStalled = function () {
  2485. //Ignore, let the timeout take care of it. Sometimes its not really stopped.
  2486. };
  2487. /**
  2488. * An XHR request has reported progress.
  2489. * @method _handleProgress
  2490. * @param {Object} event The XHR progress event.
  2491. * @private
  2492. */
  2493. p._handleProgress = function (event) {
  2494. if (!event || event.loaded > 0 && event.total == 0) {
  2495. return; // Sometimes we get no "total", so just ignore the progress event.
  2496. }
  2497. var newEvent = new createjs.ProgressEvent(event.loaded, event.total);
  2498. this.dispatchEvent(newEvent);
  2499. };
  2500. // protected methods
  2501. p._clean = function () {
  2502. this._tag.removeEventListener && this._tag.removeEventListener("canplaythrough", this._loadedHandler);
  2503. this._tag.removeEventListener("stalled", this._stalledCallback);
  2504. this._tag.removeEventListener("progress", this._progressCallback);
  2505. this.TagRequest__clean();
  2506. };
  2507. createjs.MediaTagRequest = createjs.promote(MediaTagRequest, "TagRequest");
  2508. }());
  2509. //##############################################################################
  2510. // XHRRequest.js
  2511. //##############################################################################
  2512. (function () {
  2513. "use strict";
  2514. // constructor
  2515. /**
  2516. * A preloader that loads items using XHR requests, usually XMLHttpRequest. However XDomainRequests will be used
  2517. * for cross-domain requests if possible, and older versions of IE fall back on to ActiveX objects when necessary.
  2518. * XHR requests load the content as text or binary data, provide progress and consistent completion events, and
  2519. * can be canceled during load. Note that XHR is not supported in IE 6 or earlier, and is not recommended for
  2520. * cross-domain loading.
  2521. * @class XHRRequest
  2522. * @constructor
  2523. * @param {Object} item The object that defines the file to load. Please see the {{#crossLink "LoadQueue/loadFile"}}{{/crossLink}}
  2524. * for an overview of supported file properties.
  2525. * @extends AbstractLoader
  2526. */
  2527. function XHRRequest (item) {
  2528. this.AbstractRequest_constructor(item);
  2529. // protected properties
  2530. /**
  2531. * A reference to the XHR request used to load the content.
  2532. * @property _request
  2533. * @type {XMLHttpRequest | XDomainRequest | ActiveX.XMLHTTP}
  2534. * @private
  2535. */
  2536. this._request = null;
  2537. /**
  2538. * A manual load timeout that is used for browsers that do not support the onTimeout event on XHR (XHR level 1,
  2539. * typically IE9).
  2540. * @property _loadTimeout
  2541. * @type {Number}
  2542. * @private
  2543. */
  2544. this._loadTimeout = null;
  2545. /**
  2546. * The browser's XHR (XMLHTTPRequest) version. Supported versions are 1 and 2. There is no official way to detect
  2547. * the version, so we use capabilities to make a best guess.
  2548. * @property _xhrLevel
  2549. * @type {Number}
  2550. * @default 1
  2551. * @private
  2552. */
  2553. this._xhrLevel = 1;
  2554. /**
  2555. * The response of a loaded file. This is set because it is expensive to look up constantly. This property will be
  2556. * null until the file is loaded.
  2557. * @property _response
  2558. * @type {mixed}
  2559. * @private
  2560. */
  2561. this._response = null;
  2562. /**
  2563. * The response of the loaded file before it is modified. In most cases, content is converted from raw text to
  2564. * an HTML tag or a formatted object which is set to the <code>result</code> property, but the developer may still
  2565. * want to access the raw content as it was loaded.
  2566. * @property _rawResponse
  2567. * @type {String|Object}
  2568. * @private
  2569. */
  2570. this._rawResponse = null;
  2571. this._canceled = false;
  2572. // Setup our event handlers now.
  2573. this._handleLoadStartProxy = createjs.proxy(this._handleLoadStart, this);
  2574. this._handleProgressProxy = createjs.proxy(this._handleProgress, this);
  2575. this._handleAbortProxy = createjs.proxy(this._handleAbort, this);
  2576. this._handleErrorProxy = createjs.proxy(this._handleError, this);
  2577. this._handleTimeoutProxy = createjs.proxy(this._handleTimeout, this);
  2578. this._handleLoadProxy = createjs.proxy(this._handleLoad, this);
  2579. this._handleReadyStateChangeProxy = createjs.proxy(this._handleReadyStateChange, this);
  2580. if (!this._createXHR(item)) {
  2581. //TODO: Throw error?
  2582. }
  2583. };
  2584. var p = createjs.extend(XHRRequest, createjs.AbstractRequest);
  2585. // static properties
  2586. /**
  2587. * A list of XMLHTTP object IDs to try when building an ActiveX object for XHR requests in earlier versions of IE.
  2588. * @property ACTIVEX_VERSIONS
  2589. * @type {Array}
  2590. * @since 0.4.2
  2591. * @private
  2592. */
  2593. XHRRequest.ACTIVEX_VERSIONS = [
  2594. "Msxml2.XMLHTTP.6.0",
  2595. "Msxml2.XMLHTTP.5.0",
  2596. "Msxml2.XMLHTTP.4.0",
  2597. "MSXML2.XMLHTTP.3.0",
  2598. "MSXML2.XMLHTTP",
  2599. "Microsoft.XMLHTTP"
  2600. ];
  2601. // Public methods
  2602. /**
  2603. * Look up the loaded result.
  2604. * @method getResult
  2605. * @param {Boolean} [raw=false] Return a raw result instead of a formatted result. This applies to content
  2606. * loaded via XHR such as scripts, XML, CSS, and Images. If there is no raw result, the formatted result will be
  2607. * returned instead.
  2608. * @return {Object} A result object containing the content that was loaded, such as:
  2609. * <ul>
  2610. * <li>An image tag (&lt;image /&gt;) for images</li>
  2611. * <li>A script tag for JavaScript (&lt;script /&gt;). Note that scripts loaded with tags may be added to the
  2612. * HTML head.</li>
  2613. * <li>A style tag for CSS (&lt;style /&gt;)</li>
  2614. * <li>Raw text for TEXT</li>
  2615. * <li>A formatted JavaScript object defined by JSON</li>
  2616. * <li>An XML document</li>
  2617. * <li>An binary arraybuffer loaded by XHR</li>
  2618. * </ul>
  2619. * Note that if a raw result is requested, but not found, the result will be returned instead.
  2620. */
  2621. p.getResult = function (raw) {
  2622. if (raw && this._rawResponse) {
  2623. return this._rawResponse;
  2624. }
  2625. return this._response;
  2626. };
  2627. // Overrides abstract method in AbstractRequest
  2628. p.cancel = function () {
  2629. this.canceled = true;
  2630. this._clean();
  2631. this._request.abort();
  2632. };
  2633. // Overrides abstract method in AbstractLoader
  2634. p.load = function () {
  2635. if (this._request == null) {
  2636. this._handleError();
  2637. return;
  2638. }
  2639. //Events
  2640. if (this._request.addEventListener != null) {
  2641. this._request.addEventListener("loadstart", this._handleLoadStartProxy, false);
  2642. this._request.addEventListener("progress", this._handleProgressProxy, false);
  2643. this._request.addEventListener("abort", this._handleAbortProxy, false);
  2644. this._request.addEventListener("error", this._handleErrorProxy, false);
  2645. this._request.addEventListener("timeout", this._handleTimeoutProxy, false);
  2646. // Note: We don't get onload in all browsers (earlier FF and IE). onReadyStateChange handles these.
  2647. this._request.addEventListener("load", this._handleLoadProxy, false);
  2648. this._request.addEventListener("readystatechange", this._handleReadyStateChangeProxy, false);
  2649. } else {
  2650. // IE9 support
  2651. this._request.onloadstart = this._handleLoadStartProxy;
  2652. this._request.onprogress = this._handleProgressProxy;
  2653. this._request.onabort = this._handleAbortProxy;
  2654. this._request.onerror = this._handleErrorProxy;
  2655. this._request.ontimeout = this._handleTimeoutProxy;
  2656. // Note: We don't get onload in all browsers (earlier FF and IE). onReadyStateChange handles these.
  2657. this._request.onload = this._handleLoadProxy;
  2658. this._request.onreadystatechange = this._handleReadyStateChangeProxy;
  2659. }
  2660. // Set up a timeout if we don't have XHR2
  2661. if (this._xhrLevel == 1) {
  2662. this._loadTimeout = setTimeout(createjs.proxy(this._handleTimeout, this), this._item.loadTimeout);
  2663. }
  2664. // Sometimes we get back 404s immediately, particularly when there is a cross origin request. // note this does not catch in Chrome
  2665. try {
  2666. if (!this._item.values) {
  2667. this._request.send();
  2668. } else {
  2669. this._request.send(createjs.URLUtils.formatQueryString(this._item.values));
  2670. }
  2671. } catch (error) {
  2672. this.dispatchEvent(new createjs.ErrorEvent("XHR_SEND", null, error));
  2673. }
  2674. };
  2675. p.setResponseType = function (type) {
  2676. // Some old browsers doesn't support blob, so we convert arraybuffer to blob after response is downloaded
  2677. if (type === 'blob') {
  2678. type = window.URL ? 'blob' : 'arraybuffer';
  2679. this._responseType = type;
  2680. }
  2681. this._request.responseType = type;
  2682. };
  2683. /**
  2684. * Get all the response headers from the XmlHttpRequest.
  2685. *
  2686. * <strong>From the docs:</strong> Return all the HTTP headers, excluding headers that are a case-insensitive match
  2687. * for Set-Cookie or Set-Cookie2, as a single string, with each header line separated by a U+000D CR U+000A LF pair,
  2688. * excluding the status line, and with each header name and header value separated by a U+003A COLON U+0020 SPACE
  2689. * pair.
  2690. * @method getAllResponseHeaders
  2691. * @return {String}
  2692. * @since 0.4.1
  2693. */
  2694. p.getAllResponseHeaders = function () {
  2695. if (this._request.getAllResponseHeaders instanceof Function) {
  2696. return this._request.getAllResponseHeaders();
  2697. } else {
  2698. return null;
  2699. }
  2700. };
  2701. /**
  2702. * Get a specific response header from the XmlHttpRequest.
  2703. *
  2704. * <strong>From the docs:</strong> Returns the header field value from the response of which the field name matches
  2705. * header, unless the field name is Set-Cookie or Set-Cookie2.
  2706. * @method getResponseHeader
  2707. * @param {String} header The header name to retrieve.
  2708. * @return {String}
  2709. * @since 0.4.1
  2710. */
  2711. p.getResponseHeader = function (header) {
  2712. if (this._request.getResponseHeader instanceof Function) {
  2713. return this._request.getResponseHeader(header);
  2714. } else {
  2715. return null;
  2716. }
  2717. };
  2718. // protected methods
  2719. /**
  2720. * The XHR request has reported progress.
  2721. * @method _handleProgress
  2722. * @param {Object} event The XHR progress event.
  2723. * @private
  2724. */
  2725. p._handleProgress = function (event) {
  2726. if (!event || event.loaded > 0 && event.total == 0) {
  2727. return; // Sometimes we get no "total", so just ignore the progress event.
  2728. }
  2729. var newEvent = new createjs.ProgressEvent(event.loaded, event.total);
  2730. this.dispatchEvent(newEvent);
  2731. };
  2732. /**
  2733. * The XHR request has reported a load start.
  2734. * @method _handleLoadStart
  2735. * @param {Object} event The XHR loadStart event.
  2736. * @private
  2737. */
  2738. p._handleLoadStart = function (event) {
  2739. clearTimeout(this._loadTimeout);
  2740. this.dispatchEvent("loadstart");
  2741. };
  2742. /**
  2743. * The XHR request has reported an abort event.
  2744. * @method handleAbort
  2745. * @param {Object} event The XHR abort event.
  2746. * @private
  2747. */
  2748. p._handleAbort = function (event) {
  2749. this._clean();
  2750. this.dispatchEvent(new createjs.ErrorEvent("XHR_ABORTED", null, event));
  2751. };
  2752. /**
  2753. * The XHR request has reported an error event.
  2754. * @method _handleError
  2755. * @param {Object} event The XHR error event.
  2756. * @private
  2757. */
  2758. p._handleError = function (event) {
  2759. this._clean();
  2760. this.dispatchEvent(new createjs.ErrorEvent(event.message));
  2761. };
  2762. /**
  2763. * The XHR request has reported a readyState change. Note that older browsers (IE 7 & 8) do not provide an onload
  2764. * event, so we must monitor the readyStateChange to determine if the file is loaded.
  2765. * @method _handleReadyStateChange
  2766. * @param {Object} event The XHR readyStateChange event.
  2767. * @private
  2768. */
  2769. p._handleReadyStateChange = function (event) {
  2770. if (this._request.readyState == 4) {
  2771. this._handleLoad();
  2772. }
  2773. };
  2774. /**
  2775. * The XHR request has completed. This is called by the XHR request directly, or by a readyStateChange that has
  2776. * <code>request.readyState == 4</code>. Only the first call to this method will be processed.
  2777. *
  2778. * Note that This method uses {{#crossLink "_checkError"}}{{/crossLink}} to determine if the server has returned an
  2779. * error code.
  2780. * @method _handleLoad
  2781. * @param {Object} event The XHR load event.
  2782. * @private
  2783. */
  2784. p._handleLoad = function (event) {
  2785. if (this.loaded) {
  2786. return;
  2787. }
  2788. this.loaded = true;
  2789. var error = this._checkError();
  2790. if (error) {
  2791. this._handleError(error);
  2792. return;
  2793. }
  2794. this._response = this._getResponse();
  2795. // Convert arraybuffer back to blob
  2796. if (this._responseType === 'arraybuffer') {
  2797. try {
  2798. this._response = new Blob([this._response]);
  2799. } catch (e) {
  2800. // Fallback to use BlobBuilder if Blob constructor is not supported
  2801. // Tested on Android 2.3 ~ 4.2 and iOS5 safari
  2802. window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
  2803. if (e.name === 'TypeError' && window.BlobBuilder) {
  2804. var builder = new BlobBuilder();
  2805. builder.append(this._response);
  2806. this._response = builder.getBlob();
  2807. }
  2808. }
  2809. }
  2810. this._clean();
  2811. this.dispatchEvent(new createjs.Event("complete"));
  2812. };
  2813. /**
  2814. * The XHR request has timed out. This is called by the XHR request directly, or via a <code>setTimeout</code>
  2815. * callback.
  2816. * @method _handleTimeout
  2817. * @param {Object} [event] The XHR timeout event. This is occasionally null when called by the backup setTimeout.
  2818. * @private
  2819. */
  2820. p._handleTimeout = function (event) {
  2821. this._clean();
  2822. this.dispatchEvent(new createjs.ErrorEvent("PRELOAD_TIMEOUT", null, event));
  2823. };
  2824. // Protected
  2825. /**
  2826. * Determine if there is an error in the current load.
  2827. * Currently this checks the status of the request for problem codes, and not actual response content:
  2828. * <ul>
  2829. * <li>Status codes between 400 and 599 (HTTP error range)</li>
  2830. * <li>A status of 0, but *only when the application is running on a server*. If the application is running
  2831. * on `file:`, then it may incorrectly treat an error on local (or embedded applications) as a successful
  2832. * load.</li>
  2833. * </ul>
  2834. * @method _checkError
  2835. * @return {Error} An error with the status code in the `message` argument.
  2836. * @private
  2837. */
  2838. p._checkError = function () {
  2839. var status = parseInt(this._request.status);
  2840. if (status >= 400 && status <= 599) {
  2841. return new Error(status);
  2842. } else if (status == 0) {
  2843. if ((/^https?:/).test(location.protocol)) { return new Error(0); }
  2844. return null; // Likely an embedded app.
  2845. } else {
  2846. return null;
  2847. }
  2848. };
  2849. /**
  2850. * Validate the response. Different browsers have different approaches, some of which throw errors when accessed
  2851. * in other browsers. If there is no response, the <code>_response</code> property will remain null.
  2852. * @method _getResponse
  2853. * @private
  2854. */
  2855. p._getResponse = function () {
  2856. if (this._response != null) {
  2857. return this._response;
  2858. }
  2859. if (this._request.response != null) {
  2860. return this._request.response;
  2861. }
  2862. // Android 2.2 uses .responseText
  2863. try {
  2864. if (this._request.responseText != null) {
  2865. return this._request.responseText;
  2866. }
  2867. } catch (e) {
  2868. }
  2869. // When loading XML, IE9 does not return .response, instead it returns responseXML.xml
  2870. try {
  2871. if (this._request.responseXML != null) {
  2872. return this._request.responseXML;
  2873. }
  2874. } catch (e) {
  2875. }
  2876. return null;
  2877. };
  2878. /**
  2879. * Create an XHR request. Depending on a number of factors, we get totally different results.
  2880. * <ol><li>Some browsers get an <code>XDomainRequest</code> when loading cross-domain.</li>
  2881. * <li>XMLHttpRequest are created when available.</li>
  2882. * <li>ActiveX.XMLHTTP objects are used in older IE browsers.</li>
  2883. * <li>Text requests override the mime type if possible</li>
  2884. * <li>Origin headers are sent for crossdomain requests in some browsers.</li>
  2885. * <li>Binary loads set the response type to "arraybuffer"</li></ol>
  2886. * @method _createXHR
  2887. * @param {Object} item The requested item that is being loaded.
  2888. * @return {Boolean} If an XHR request or equivalent was successfully created.
  2889. * @private
  2890. */
  2891. p._createXHR = function (item) {
  2892. // Check for cross-domain loads. We can't fully support them, but we can try.
  2893. var crossdomain = createjs.URLUtils.isCrossDomain(item);
  2894. var headers = {};
  2895. // Create the request. Fallback to whatever support we have.
  2896. var req = null;
  2897. if (window.XMLHttpRequest) {
  2898. req = new XMLHttpRequest();
  2899. // This is 8 or 9, so use XDomainRequest instead.
  2900. if (crossdomain && req.withCredentials === undefined && window.XDomainRequest) {
  2901. req = new XDomainRequest();
  2902. }
  2903. } else { // Old IE versions use a different approach
  2904. for (var i = 0, l = s.ACTIVEX_VERSIONS.length; i < l; i++) {
  2905. var axVersion = s.ACTIVEX_VERSIONS[i];
  2906. try {
  2907. req = new ActiveXObject(axVersion);
  2908. break;
  2909. } catch (e) {
  2910. }
  2911. }
  2912. if (req == null) {
  2913. return false;
  2914. }
  2915. }
  2916. // Default to utf-8 for Text requests.
  2917. if (item.mimeType == null && createjs.RequestUtils.isText(item.type)) {
  2918. item.mimeType = "text/plain; charset=utf-8";
  2919. }
  2920. // IE9 doesn't support overrideMimeType(), so we need to check for it.
  2921. if (item.mimeType && req.overrideMimeType) {
  2922. req.overrideMimeType(item.mimeType);
  2923. }
  2924. // Determine the XHR level
  2925. this._xhrLevel = (typeof req.responseType === "string") ? 2 : 1;
  2926. var src = null;
  2927. if (item.method == createjs.Methods.GET) {
  2928. src = createjs.URLUtils.buildURI(item.src, item.values);
  2929. } else {
  2930. src = item.src;
  2931. }
  2932. // Open the request. Set cross-domain flags if it is supported (XHR level 1 only)
  2933. req.open(item.method || createjs.Methods.GET, src, true);
  2934. if (crossdomain && req instanceof XMLHttpRequest && this._xhrLevel == 1) {
  2935. headers["Origin"] = location.origin;
  2936. }
  2937. // To send data we need to set the Content-type header)
  2938. if (item.values && item.method == createjs.Methods.POST) {
  2939. headers["Content-Type"] = "application/x-www-form-urlencoded";
  2940. }
  2941. if (!crossdomain && !headers["X-Requested-With"]) {
  2942. headers["X-Requested-With"] = "XMLHttpRequest";
  2943. }
  2944. if (item.headers) {
  2945. for (var n in item.headers) {
  2946. headers[n] = item.headers[n];
  2947. }
  2948. }
  2949. for (n in headers) {
  2950. req.setRequestHeader(n, headers[n])
  2951. }
  2952. if (req instanceof XMLHttpRequest && item.withCredentials !== undefined) {
  2953. req.withCredentials = item.withCredentials;
  2954. }
  2955. this._request = req;
  2956. return true;
  2957. };
  2958. /**
  2959. * A request has completed (or failed or canceled), and needs to be disposed.
  2960. * @method _clean
  2961. * @private
  2962. */
  2963. p._clean = function () {
  2964. clearTimeout(this._loadTimeout);
  2965. if (this._request.removeEventListener != null) {
  2966. this._request.removeEventListener("loadstart", this._handleLoadStartProxy);
  2967. this._request.removeEventListener("progress", this._handleProgressProxy);
  2968. this._request.removeEventListener("abort", this._handleAbortProxy);
  2969. this._request.removeEventListener("error", this._handleErrorProxy);
  2970. this._request.removeEventListener("timeout", this._handleTimeoutProxy);
  2971. this._request.removeEventListener("load", this._handleLoadProxy);
  2972. this._request.removeEventListener("readystatechange", this._handleReadyStateChangeProxy);
  2973. } else {
  2974. this._request.onloadstart = null;
  2975. this._request.onprogress = null;
  2976. this._request.onabort = null;
  2977. this._request.onerror = null;
  2978. this._request.ontimeout = null;
  2979. this._request.onload = null;
  2980. this._request.onreadystatechange = null;
  2981. }
  2982. };
  2983. p.toString = function () {
  2984. return "[PreloadJS XHRRequest]";
  2985. };
  2986. createjs.XHRRequest = createjs.promote(XHRRequest, "AbstractRequest");
  2987. }());
  2988. //##############################################################################
  2989. // SoundLoader.js
  2990. //##############################################################################
  2991. (function () {
  2992. "use strict";
  2993. // constructor
  2994. /**
  2995. * A loader for HTML audio files. PreloadJS can not load WebAudio files, as a WebAudio context is required, which
  2996. * should be created by either a library playing the sound (such as <a href="http://soundjs.com">SoundJS</a>, or an
  2997. * external framework that handles audio playback. To load content that can be played by WebAudio, use the
  2998. * {{#crossLink "BinaryLoader"}}{{/crossLink}}, and handle the audio context decoding manually.
  2999. * @class SoundLoader
  3000. * @param {LoadItem|Object} loadItem
  3001. * @param {Boolean} preferXHR
  3002. * @extends AbstractMediaLoader
  3003. * @constructor
  3004. */
  3005. function SoundLoader(loadItem, preferXHR) {
  3006. this.AbstractMediaLoader_constructor(loadItem, preferXHR, createjs.Types.SOUND);
  3007. // protected properties
  3008. if (createjs.DomUtils.isAudioTag(loadItem)) {
  3009. this._tag = loadItem;
  3010. } else if (createjs.DomUtils.isAudioTag(loadItem.src)) {
  3011. this._tag = loadItem;
  3012. } else if (createjs.DomUtils.isAudioTag(loadItem.tag)) {
  3013. this._tag = createjs.DomUtils.isAudioTag(loadItem) ? loadItem : loadItem.src;
  3014. }
  3015. if (this._tag != null) {
  3016. this._preferXHR = false;
  3017. }
  3018. };
  3019. var p = createjs.extend(SoundLoader, createjs.AbstractMediaLoader);
  3020. var s = SoundLoader;
  3021. // static methods
  3022. /**
  3023. * Determines if the loader can load a specific item. This loader can only load items that are of type
  3024. * {{#crossLink "Types/SOUND:property"}}{{/crossLink}}.
  3025. * @method canLoadItem
  3026. * @param {LoadItem|Object} item The LoadItem that a LoadQueue is trying to load.
  3027. * @returns {Boolean} Whether the loader can load the item.
  3028. * @static
  3029. */
  3030. s.canLoadItem = function (item) {
  3031. return item.type == createjs.Types.SOUND;
  3032. };
  3033. // protected methods
  3034. p._createTag = function (src) {
  3035. var tag = createjs.Elements.audio();
  3036. tag.autoplay = false;
  3037. tag.preload = "none";
  3038. //LM: Firefox fails when this the preload="none" for other tags, but it needs to be "none" to ensure PreloadJS works.
  3039. tag.src = src;
  3040. return tag;
  3041. };
  3042. createjs.SoundLoader = createjs.promote(SoundLoader, "AbstractMediaLoader");
  3043. }());
  3044. //##############################################################################
  3045. // AudioSprite.js
  3046. //##############################################################################
  3047. // NOTE this is "Class" is purely to document audioSprite Setup and usage.
  3048. /**
  3049. * <strong>Note: AudioSprite is not a class, but its usage is easily lost in the documentation, so it has been called
  3050. * out here for quick reference.</strong>
  3051. *
  3052. * Audio sprites are much like CSS sprites or image sprite sheets: multiple audio assets grouped into a single file.
  3053. * Audio sprites work around limitations in certain browsers, where only a single sound can be loaded and played at a
  3054. * time. We recommend at least 300ms of silence between audio clips to deal with HTML audio tag inaccuracy, and to prevent
  3055. * accidentally playing bits of the neighbouring clips.
  3056. *
  3057. * <strong>Benefits of Audio Sprites:</strong>
  3058. * <ul>
  3059. * <li>More robust support for older browsers and devices that only allow a single audio instance, such as iOS 5.</li>
  3060. * <li>They provide a work around for the Internet Explorer 9 audio tag limit, which restricts how many different
  3061. * sounds that could be loaded at once.</li>
  3062. * <li>Faster loading by only requiring a single network request for several sounds, especially on mobile devices
  3063. * where the network round trip for each file can add significant latency.</li>
  3064. * </ul>
  3065. *
  3066. * <strong>Drawbacks of Audio Sprites</strong>
  3067. * <ul>
  3068. * <li>No guarantee of smooth looping when using HTML or Flash audio. If you have a track that needs to loop
  3069. * smoothly and you are supporting non-web audio browsers, do not use audio sprites for that sound if you can avoid
  3070. * it.</li>
  3071. * <li>No guarantee that HTML audio will play back immediately, especially the first time. In some browsers
  3072. * (Chrome!), HTML audio will only load enough to play through at the current download speed – so we rely on the
  3073. * `canplaythrough` event to determine if the audio is loaded. Since audio sprites must jump ahead to play specific
  3074. * sounds, the audio may not yet have downloaded fully.</li>
  3075. * <li>Audio sprites share the same core source, so if you have a sprite with 5 sounds and are limited to 2
  3076. * concurrently playing instances, you can only play 2 of the sounds at the same time.</li>
  3077. * </ul>
  3078. *
  3079. * <h4>Example</h4>
  3080. *
  3081. * createjs.Sound.initializeDefaultPlugins();
  3082. * var assetsPath = "./assets/";
  3083. * var sounds = [{
  3084. * src:"MyAudioSprite.ogg", data: {
  3085. * audioSprite: [
  3086. * {id:"sound1", startTime:0, duration:500},
  3087. * {id:"sound2", startTime:1000, duration:400},
  3088. * {id:"sound3", startTime:1700, duration: 1000}
  3089. * ]}
  3090. * }
  3091. * ];
  3092. * createjs.Sound.alternateExtensions = ["mp3"];
  3093. * createjs.Sound.on("fileload", loadSound);
  3094. * createjs.Sound.registerSounds(sounds, assetsPath);
  3095. * // after load is complete
  3096. * createjs.Sound.play("sound2");
  3097. *
  3098. * You can also create audio sprites on the fly by setting the startTime and duration when creating an new AbstractSoundInstance.
  3099. *
  3100. * createjs.Sound.play("MyAudioSprite", {startTime: 1000, duration: 400});
  3101. *
  3102. * The excellent CreateJS community has created a tool to create audio sprites, available at
  3103. * <a href="https://github.com/tonistiigi/audiosprite" target="_blank">https://github.com/tonistiigi/audiosprite</a>,
  3104. * as well as a <a href="http://jsfiddle.net/bharat_battu/g8fFP/12/" target="_blank">jsfiddle</a> to convert the output
  3105. * to SoundJS format.
  3106. *
  3107. * @class AudioSprite
  3108. * @since 0.6.0
  3109. */
  3110. //##############################################################################
  3111. // PlayPropsConfig.js
  3112. //##############################################################################
  3113. (function () {
  3114. "use strict";
  3115. /**
  3116. * A class to store the optional play properties passed in {{#crossLink "Sound/play"}}{{/crossLink}} and
  3117. * {{#crossLink "AbstractSoundInstance/play"}}{{/crossLink}} calls.
  3118. *
  3119. * Optional Play Properties Include:
  3120. * <ul>
  3121. * <li>interrupt - How to interrupt any currently playing instances of audio with the same source,
  3122. * if the maximum number of instances of the sound are already playing. Values are defined as <code>INTERRUPT_TYPE</code>
  3123. * constants on the Sound class, with the default defined by {{#crossLink "Sound/defaultInterruptBehavior:property"}}{{/crossLink}}.</li>
  3124. * <li>delay - The amount of time to delay the start of audio playback, in milliseconds.</li>
  3125. * <li>offset - The offset from the start of the audio to begin playback, in milliseconds.</li>
  3126. * <li>loop - How many times the audio loops when it reaches the end of playback. The default is 0 (no
  3127. * loops), and -1 can be used for infinite playback.</li>
  3128. * <li>volume - The volume of the sound, between 0 and 1. Note that the master volume is applied
  3129. * against the individual volume.</li>
  3130. * <li>pan - The left-right pan of the sound (if supported), between -1 (left) and 1 (right).</li>
  3131. * <li>startTime - To create an audio sprite (with duration), the initial offset to start playback and loop from, in milliseconds.</li>
  3132. * <li>duration - To create an audio sprite (with startTime), the amount of time to play the clip for, in milliseconds.</li>
  3133. * </ul>
  3134. *
  3135. * <h4>Example</h4>
  3136. *
  3137. * var props = new createjs.PlayPropsConfig().set({interrupt: createjs.Sound.INTERRUPT_ANY, loop: -1, volume: 0.5})
  3138. * createjs.Sound.play("mySound", props);
  3139. * // OR
  3140. * mySoundInstance.play(props);
  3141. *
  3142. * @class PlayPropsConfig
  3143. * @constructor
  3144. * @since 0.6.1
  3145. */
  3146. // TODO think of a better name for this class
  3147. var PlayPropsConfig = function () {
  3148. // Public Properties
  3149. /**
  3150. * How to interrupt any currently playing instances of audio with the same source,
  3151. * if the maximum number of instances of the sound are already playing. Values are defined as
  3152. * <code>INTERRUPT_TYPE</code> constants on the Sound class, with the default defined by
  3153. * {{#crossLink "Sound/defaultInterruptBehavior:property"}}{{/crossLink}}.
  3154. * @property interrupt
  3155. * @type {string}
  3156. * @default null
  3157. */
  3158. this.interrupt = null;
  3159. /**
  3160. * The amount of time to delay the start of audio playback, in milliseconds.
  3161. * @property delay
  3162. * @type {Number}
  3163. * @default null
  3164. */
  3165. this.delay = null;
  3166. /**
  3167. * The offset from the start of the audio to begin playback, in milliseconds.
  3168. * @property offset
  3169. * @type {number}
  3170. * @default null
  3171. */
  3172. this.offset = null;
  3173. /**
  3174. * How many times the audio loops when it reaches the end of playback. The default is 0 (no
  3175. * loops), and -1 can be used for infinite playback.
  3176. * @property loop
  3177. * @type {number}
  3178. * @default null
  3179. */
  3180. this.loop = null;
  3181. /**
  3182. * The volume of the sound, between 0 and 1. Note that the master volume is applied
  3183. * against the individual volume.
  3184. * @property volume
  3185. * @type {number}
  3186. * @default null
  3187. */
  3188. this.volume = null;
  3189. /**
  3190. * The left-right pan of the sound (if supported), between -1 (left) and 1 (right).
  3191. * @property pan
  3192. * @type {number}
  3193. * @default null
  3194. */
  3195. this.pan = null;
  3196. /**
  3197. * Used to create an audio sprite (with duration), the initial offset to start playback and loop from, in milliseconds.
  3198. * @property startTime
  3199. * @type {number}
  3200. * @default null
  3201. */
  3202. this.startTime = null;
  3203. /**
  3204. * Used to create an audio sprite (with startTime), the amount of time to play the clip for, in milliseconds.
  3205. * @property duration
  3206. * @type {number}
  3207. * @default null
  3208. */
  3209. this.duration = null;
  3210. };
  3211. var p = PlayPropsConfig.prototype = {};
  3212. var s = PlayPropsConfig;
  3213. // Static Methods
  3214. /**
  3215. * Creates a PlayPropsConfig from another PlayPropsConfig or an Object.
  3216. *
  3217. * @method create
  3218. * @param {PlayPropsConfig|Object} value The play properties
  3219. * @returns {PlayPropsConfig}
  3220. * @static
  3221. */
  3222. s.create = function (value) {
  3223. if (typeof(value) === "string") {
  3224. // Handle the old API gracefully.
  3225. console && (console.warn || console.log)("Deprecated behaviour. Sound.play takes a configuration object instead of individual arguments. See docs for info.");
  3226. return new createjs.PlayPropsConfig().set({interrupt:value});
  3227. } else if (value == null || value instanceof s || value instanceof Object) {
  3228. return new createjs.PlayPropsConfig().set(value);
  3229. } else if (value == null) {
  3230. throw new Error("PlayProps configuration not recognized.");
  3231. }
  3232. };
  3233. // Public Methods
  3234. /**
  3235. * Provides a chainable shortcut method for setting a number of properties on the instance.
  3236. *
  3237. * <h4>Example</h4>
  3238. *
  3239. * var PlayPropsConfig = new createjs.PlayPropsConfig().set({loop:-1, volume:0.7});
  3240. *
  3241. * @method set
  3242. * @param {Object} props A generic object containing properties to copy to the PlayPropsConfig instance.
  3243. * @return {PlayPropsConfig} Returns the instance the method is called on (useful for chaining calls.)
  3244. */
  3245. p.set = function(props) {
  3246. if (props != null) {
  3247. for (var n in props) { this[n] = props[n]; }
  3248. }
  3249. return this;
  3250. };
  3251. p.toString = function() {
  3252. return "[PlayPropsConfig]";
  3253. };
  3254. createjs.PlayPropsConfig = s;
  3255. }());
  3256. //##############################################################################
  3257. // Sound.js
  3258. //##############################################################################
  3259. (function () {
  3260. "use strict";
  3261. /**
  3262. * The Sound class is the public API for creating sounds, controlling the overall sound levels, and managing plugins.
  3263. * All Sound APIs on this class are static.
  3264. *
  3265. * <b>Registering and Preloading</b><br />
  3266. * Before you can play a sound, it <b>must</b> be registered. You can do this with {{#crossLink "Sound/registerSound"}}{{/crossLink}},
  3267. * or register multiple sounds using {{#crossLink "Sound/registerSounds"}}{{/crossLink}}. If you don't register a
  3268. * sound prior to attempting to play it using {{#crossLink "Sound/play"}}{{/crossLink}} or create it using {{#crossLink "Sound/createInstance"}}{{/crossLink}},
  3269. * the sound source will be automatically registered but playback will fail as the source will not be ready. If you use
  3270. * <a href="http://preloadjs.com" target="_blank">PreloadJS</a>, registration is handled for you when the sound is
  3271. * preloaded. It is recommended to preload sounds either internally using the register functions or externally using
  3272. * PreloadJS so they are ready when you want to use them.
  3273. *
  3274. * <b>Playback</b><br />
  3275. * To play a sound once it's been registered and preloaded, use the {{#crossLink "Sound/play"}}{{/crossLink}} method.
  3276. * This method returns a {{#crossLink "AbstractSoundInstance"}}{{/crossLink}} which can be paused, resumed, muted, etc.
  3277. * Please see the {{#crossLink "AbstractSoundInstance"}}{{/crossLink}} documentation for more on the instance control APIs.
  3278. *
  3279. * <b>Plugins</b><br />
  3280. * By default, the {{#crossLink "WebAudioPlugin"}}{{/crossLink}} or the {{#crossLink "HTMLAudioPlugin"}}{{/crossLink}}
  3281. * are used (when available), although developers can change plugin priority or add new plugins (such as the
  3282. * provided {{#crossLink "FlashAudioPlugin"}}{{/crossLink}}). Please see the {{#crossLink "Sound"}}{{/crossLink}} API
  3283. * methods for more on the playback and plugin APIs. To install plugins, or specify a different plugin order, see
  3284. * {{#crossLink "Sound/installPlugins"}}{{/crossLink}}.
  3285. *
  3286. * <h4>Example</h4>
  3287. *
  3288. * createjs.FlashAudioPlugin.swfPath = "../src/soundjs/flashaudio";
  3289. * createjs.Sound.registerPlugins([createjs.WebAudioPlugin, createjs.FlashAudioPlugin]);
  3290. * createjs.Sound.alternateExtensions = ["mp3"];
  3291. * createjs.Sound.on("fileload", this.loadHandler, this);
  3292. * createjs.Sound.registerSound("path/to/mySound.ogg", "sound");
  3293. * function loadHandler(event) {
  3294. * // This is fired for each sound that is registered.
  3295. * var instance = createjs.Sound.play("sound"); // play using id. Could also use full source path or event.src.
  3296. * instance.on("complete", this.handleComplete, this);
  3297. * instance.volume = 0.5;
  3298. * }
  3299. *
  3300. * The maximum number of concurrently playing instances of the same sound can be specified in the "data" argument
  3301. * of {{#crossLink "Sound/registerSound"}}{{/crossLink}}. Note that if not specified, the active plugin will apply
  3302. * a default limit. Currently HTMLAudioPlugin sets a default limit of 2, while WebAudioPlugin and FlashAudioPlugin set a
  3303. * default limit of 100.
  3304. *
  3305. * createjs.Sound.registerSound("sound.mp3", "soundId", 4);
  3306. *
  3307. * Sound can be used as a plugin with PreloadJS to help preload audio properly. Audio preloaded with PreloadJS is
  3308. * automatically registered with the Sound class. When audio is not preloaded, Sound will do an automatic internal
  3309. * load. As a result, it may fail to play the first time play is called if the audio is not finished loading. Use
  3310. * the {{#crossLink "Sound/fileload:event"}}{{/crossLink}} event to determine when a sound has finished internally
  3311. * preloading. It is recommended that all audio is preloaded before it is played.
  3312. *
  3313. * var queue = new createjs.LoadQueue();
  3314. * queue.installPlugin(createjs.Sound);
  3315. *
  3316. * <b>Audio Sprites</b><br />
  3317. * SoundJS has added support for {{#crossLink "AudioSprite"}}{{/crossLink}}, available as of version 0.6.0.
  3318. * For those unfamiliar with audio sprites, they are much like CSS sprites or sprite sheets: multiple audio assets
  3319. * grouped into a single file.
  3320. *
  3321. * <h4>Example</h4>
  3322. *
  3323. * var assetsPath = "./assets/";
  3324. * var sounds = [{
  3325. * src:"MyAudioSprite.ogg", data: {
  3326. * audioSprite: [
  3327. * {id:"sound1", startTime:0, duration:500},
  3328. * {id:"sound2", startTime:1000, duration:400},
  3329. * {id:"sound3", startTime:1700, duration: 1000}
  3330. * ]}
  3331. * }
  3332. * ];
  3333. * createjs.Sound.alternateExtensions = ["mp3"];
  3334. * createjs.Sound.on("fileload", loadSound);
  3335. * createjs.Sound.registerSounds(sounds, assetsPath);
  3336. * // after load is complete
  3337. * createjs.Sound.play("sound2");
  3338. *
  3339. * <b>Mobile Playback</b><br />
  3340. * Devices running iOS require the WebAudio context to be "unlocked" by playing at least one sound inside of a user-
  3341. * initiated event (such as touch/click). Earlier versions of SoundJS included a "MobileSafe" sample, but this is no
  3342. * longer necessary as of SoundJS 0.6.2.
  3343. * <ul>
  3344. * <li>
  3345. * In SoundJS 0.4.1 and above, you can either initialize plugins or use the {{#crossLink "WebAudioPlugin/playEmptySound"}}{{/crossLink}}
  3346. * method in the call stack of a user input event to manually unlock the audio context.
  3347. * </li>
  3348. * <li>
  3349. * In SoundJS 0.6.2 and above, SoundJS will automatically listen for the first document-level "mousedown"
  3350. * and "touchend" event, and unlock WebAudio. This will continue to check these events until the WebAudio
  3351. * context becomes "unlocked" (changes from "suspended" to "running")
  3352. * </li>
  3353. * <li>
  3354. * Both the "mousedown" and "touchend" events can be used to unlock audio in iOS9+, the "touchstart" event
  3355. * will work in iOS8 and below. The "touchend" event will only work in iOS9 when the gesture is interpreted
  3356. * as a "click", so if the user long-presses the button, it will no longer work.
  3357. * </li>
  3358. * <li>
  3359. * When using the <a href="http://www.createjs.com/docs/easeljs/classes/Touch.html">EaselJS Touch class</a>,
  3360. * the "mousedown" event will not fire when a canvas is clicked, since MouseEvents are prevented, to ensure
  3361. * only touch events fire. To get around this, you can either rely on "touchend", or:
  3362. * <ol>
  3363. * <li>Set the `allowDefault` property on the Touch class constructor to `true` (defaults to `false`).</li>
  3364. * <li>Set the `preventSelection` property on the EaselJS `Stage` to `false`.</li>
  3365. * </ol>
  3366. * These settings may change how your application behaves, and are not recommended.
  3367. * </li>
  3368. * </ul>
  3369. *
  3370. * <b>Loading Alternate Paths and Extension-less Files</b><br />
  3371. * SoundJS supports loading alternate paths and extension-less files by passing an object instead of a string for
  3372. * the `src` property, which is a hash using the format `{extension:"path", extension2:"path2"}`. These labels are
  3373. * how SoundJS determines if the browser will support the sound. This also enables multiple formats to live in
  3374. * different folders, or on CDNs, which often has completely different filenames for each file.
  3375. *
  3376. * Priority is determined by the property order (first property is tried first). This is supported by both internal loading
  3377. * and loading with PreloadJS.
  3378. *
  3379. * <em>Note: an id is required for playback.</em>
  3380. *
  3381. * <h4>Example</h4>
  3382. *
  3383. * var sounds = {path:"./audioPath/",
  3384. * manifest: [
  3385. * {id: "cool", src: {mp3:"mp3/awesome.mp3", ogg:"noExtensionOggFile"}}
  3386. * ]};
  3387. *
  3388. * createjs.Sound.alternateExtensions = ["mp3"];
  3389. * createjs.Sound.addEventListener("fileload", handleLoad);
  3390. * createjs.Sound.registerSounds(sounds);
  3391. *
  3392. * <h3>Known Browser and OS issues</h3>
  3393. * <b>IE 9 HTML Audio limitations</b><br />
  3394. * <ul><li>There is a delay in applying volume changes to tags that occurs once playback is started. So if you have
  3395. * muted all sounds, they will all play during this delay until the mute applies internally. This happens regardless of
  3396. * when or how you apply the volume change, as the tag seems to need to play to apply it.</li>
  3397. * <li>MP3 encoding will not always work for audio tags, particularly in Internet Explorer. We've found default
  3398. * encoding with 64kbps works.</li>
  3399. * <li>Occasionally very short samples will get cut off.</li>
  3400. * <li>There is a limit to how many audio tags you can load and play at once, which appears to be determined by
  3401. * hardware and browser settings. See {{#crossLink "HTMLAudioPlugin.MAX_INSTANCES"}}{{/crossLink}} for a safe
  3402. * estimate.</li></ul>
  3403. *
  3404. * <b>Firefox 25 Web Audio limitations</b>
  3405. * <ul><li>mp3 audio files do not load properly on all windows machines, reported
  3406. * <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=929969" target="_blank">here</a>. </br>
  3407. * For this reason it is recommended to pass another FF supported type (ie ogg) first until this bug is resolved, if
  3408. * possible.</li></ul>
  3409. * <b>Safari limitations</b><br />
  3410. * <ul><li>Safari requires Quicktime to be installed for audio playback.</li></ul>
  3411. *
  3412. * <b>iOS 6 Web Audio limitations</b><br />
  3413. * <ul><li>Sound is initially locked, and must be unlocked via a user-initiated event. Please see the section on
  3414. * Mobile Playback above.</li>
  3415. * <li>A bug exists that will distort un-cached web audio when a video element is present in the DOM that has audio
  3416. * at a different sampleRate.</li>
  3417. * </ul>
  3418. *
  3419. * <b>Android HTML Audio limitations</b><br />
  3420. * <ul><li>We have no control over audio volume. Only the user can set volume on their device.</li>
  3421. * <li>We can only play audio inside a user event (touch/click). This currently means you cannot loop sound or use
  3422. * a delay.</li></ul>
  3423. *
  3424. * <b>Web Audio and PreloadJS</b><br />
  3425. * <ul><li>Web Audio must be loaded through XHR, therefore when used with PreloadJS, tag loading is not possible.
  3426. * This means that tag loading can not be used to avoid cross domain issues.</li><ul>
  3427. *
  3428. * @class Sound
  3429. * @static
  3430. * @uses EventDispatcher
  3431. */
  3432. function Sound() {
  3433. throw "Sound cannot be instantiated";
  3434. }
  3435. var s = Sound;
  3436. // Static Properties
  3437. /**
  3438. * The interrupt value to interrupt any currently playing instance with the same source, if the maximum number of
  3439. * instances of the sound are already playing.
  3440. * @property INTERRUPT_ANY
  3441. * @type {String}
  3442. * @default any
  3443. * @static
  3444. */
  3445. s.INTERRUPT_ANY = "any";
  3446. /**
  3447. * The interrupt value to interrupt the earliest currently playing instance with the same source that progressed the
  3448. * least distance in the audio track, if the maximum number of instances of the sound are already playing.
  3449. * @property INTERRUPT_EARLY
  3450. * @type {String}
  3451. * @default early
  3452. * @static
  3453. */
  3454. s.INTERRUPT_EARLY = "early";
  3455. /**
  3456. * The interrupt value to interrupt the currently playing instance with the same source that progressed the most
  3457. * distance in the audio track, if the maximum number of instances of the sound are already playing.
  3458. * @property INTERRUPT_LATE
  3459. * @type {String}
  3460. * @default late
  3461. * @static
  3462. */
  3463. s.INTERRUPT_LATE = "late";
  3464. /**
  3465. * The interrupt value to not interrupt any currently playing instances with the same source, if the maximum number of
  3466. * instances of the sound are already playing.
  3467. * @property INTERRUPT_NONE
  3468. * @type {String}
  3469. * @default none
  3470. * @static
  3471. */
  3472. s.INTERRUPT_NONE = "none";
  3473. /**
  3474. * Defines the playState of an instance that is still initializing.
  3475. * @property PLAY_INITED
  3476. * @type {String}
  3477. * @default playInited
  3478. * @static
  3479. */
  3480. s.PLAY_INITED = "playInited";
  3481. /**
  3482. * Defines the playState of an instance that is currently playing or paused.
  3483. * @property PLAY_SUCCEEDED
  3484. * @type {String}
  3485. * @default playSucceeded
  3486. * @static
  3487. */
  3488. s.PLAY_SUCCEEDED = "playSucceeded";
  3489. /**
  3490. * Defines the playState of an instance that was interrupted by another instance.
  3491. * @property PLAY_INTERRUPTED
  3492. * @type {String}
  3493. * @default playInterrupted
  3494. * @static
  3495. */
  3496. s.PLAY_INTERRUPTED = "playInterrupted";
  3497. /**
  3498. * Defines the playState of an instance that completed playback.
  3499. * @property PLAY_FINISHED
  3500. * @type {String}
  3501. * @default playFinished
  3502. * @static
  3503. */
  3504. s.PLAY_FINISHED = "playFinished";
  3505. /**
  3506. * Defines the playState of an instance that failed to play. This is usually caused by a lack of available channels
  3507. * when the interrupt mode was "INTERRUPT_NONE", the playback stalled, or the sound could not be found.
  3508. * @property PLAY_FAILED
  3509. * @type {String}
  3510. * @default playFailed
  3511. * @static
  3512. */
  3513. s.PLAY_FAILED = "playFailed";
  3514. /**
  3515. * A list of the default supported extensions that Sound will <i>try</i> to play. Plugins will check if the browser
  3516. * can play these types, so modifying this list before a plugin is initialized will allow the plugins to try to
  3517. * support additional media types.
  3518. *
  3519. * NOTE this does not currently work for {{#crossLink "FlashAudioPlugin"}}{{/crossLink}}.
  3520. *
  3521. * More details on file formats can be found at <a href="http://en.wikipedia.org/wiki/Audio_file_format" target="_blank">http://en.wikipedia.org/wiki/Audio_file_format</a>.<br />
  3522. * A very detailed list of file formats can be found at <a href="http://www.fileinfo.com/filetypes/audio" target="_blank">http://www.fileinfo.com/filetypes/audio</a>.
  3523. * @property SUPPORTED_EXTENSIONS
  3524. * @type {Array[String]}
  3525. * @default ["mp3", "ogg", "opus", "mpeg", "wav", "m4a", "mp4", "aiff", "wma", "mid"]
  3526. * @since 0.4.0
  3527. * @static
  3528. */
  3529. s.SUPPORTED_EXTENSIONS = ["mp3", "ogg", "opus", "mpeg", "wav", "m4a", "mp4", "aiff", "wma", "mid"];
  3530. /**
  3531. * Some extensions use another type of extension support to play (one of them is a codex). This allows you to map
  3532. * that support so plugins can accurately determine if an extension is supported. Adding to this list can help
  3533. * plugins determine more accurately if an extension is supported.
  3534. *
  3535. * A useful list of extensions for each format can be found at <a href="http://html5doctor.com/html5-audio-the-state-of-play/" target="_blank">http://html5doctor.com/html5-audio-the-state-of-play/</a>.
  3536. * @property EXTENSION_MAP
  3537. * @type {Object}
  3538. * @since 0.4.0
  3539. * @default {m4a:"mp4"}
  3540. * @static
  3541. */
  3542. s.EXTENSION_MAP = {
  3543. m4a:"mp4"
  3544. };
  3545. /**
  3546. * The RegExp pattern used to parse file URIs. This supports simple file names, as well as full domain URIs with
  3547. * query strings. The resulting match is: protocol:$1 domain:$2 path:$3 file:$4 extension:$5 query:$6.
  3548. * @property FILE_PATTERN
  3549. * @type {RegExp}
  3550. * @static
  3551. * @private
  3552. */
  3553. s.FILE_PATTERN = /^(?:(\w+:)\/{2}(\w+(?:\.\w+)*\/?))?([/.]*?(?:[^?]+)?\/)?((?:[^/?]+)\.(\w+))(?:\?(\S+)?)?$/;
  3554. // Class Public properties
  3555. /**
  3556. * Determines the default behavior for interrupting other currently playing instances with the same source, if the
  3557. * maximum number of instances of the sound are already playing. Currently the default is {{#crossLink "Sound/INTERRUPT_NONE:property"}}{{/crossLink}}
  3558. * but this can be set and will change playback behavior accordingly. This is only used when {{#crossLink "Sound/play"}}{{/crossLink}}
  3559. * is called without passing a value for interrupt.
  3560. * @property defaultInterruptBehavior
  3561. * @type {String}
  3562. * @default Sound.INTERRUPT_NONE, or "none"
  3563. * @static
  3564. * @since 0.4.0
  3565. */
  3566. s.defaultInterruptBehavior = s.INTERRUPT_NONE; // OJR does s.INTERRUPT_ANY make more sense as default? Needs game dev testing to see which case makes more sense.
  3567. /**
  3568. * An array of extensions to attempt to use when loading sound, if the default is unsupported by the active plugin.
  3569. * These are applied in order, so if you try to Load Thunder.ogg in a browser that does not support ogg, and your
  3570. * extensions array is ["mp3", "m4a", "wav"] it will check mp3 support, then m4a, then wav. The audio files need
  3571. * to exist in the same location, as only the extension is altered.
  3572. *
  3573. * Note that regardless of which file is loaded, you can call {{#crossLink "Sound/createInstance"}}{{/crossLink}}
  3574. * and {{#crossLink "Sound/play"}}{{/crossLink}} using the same id or full source path passed for loading.
  3575. *
  3576. * <h4>Example</h4>
  3577. *
  3578. * var sounds = [
  3579. * {src:"myPath/mySound.ogg", id:"example"},
  3580. * ];
  3581. * createjs.Sound.alternateExtensions = ["mp3"]; // now if ogg is not supported, SoundJS will try asset0.mp3
  3582. * createjs.Sound.on("fileload", handleLoad); // call handleLoad when each sound loads
  3583. * createjs.Sound.registerSounds(sounds, assetPath);
  3584. * // ...
  3585. * createjs.Sound.play("myPath/mySound.ogg"); // works regardless of what extension is supported. Note calling with ID is a better approach
  3586. *
  3587. * @property alternateExtensions
  3588. * @type {Array}
  3589. * @since 0.5.2
  3590. * @static
  3591. */
  3592. s.alternateExtensions = [];
  3593. /**
  3594. * The currently active plugin. If this is null, then no plugin could be initialized. If no plugin was specified,
  3595. * Sound attempts to apply the default plugins: {{#crossLink "WebAudioPlugin"}}{{/crossLink}}, followed by
  3596. * {{#crossLink "HTMLAudioPlugin"}}{{/crossLink}}.
  3597. * @property activePlugin
  3598. * @type {Object}
  3599. * @static
  3600. */
  3601. s.activePlugin = null;
  3602. // class getter / setter properties
  3603. /**
  3604. * Set the master volume of Sound. The master volume is multiplied against each sound's individual volume. For
  3605. * example, if master volume is 0.5 and a sound's volume is 0.5, the resulting volume is 0.25. To set individual
  3606. * sound volume, use AbstractSoundInstance {{#crossLink "AbstractSoundInstance/volume:property"}}{{/crossLink}}
  3607. * instead.
  3608. *
  3609. * <h4>Example</h4>
  3610. *
  3611. * createjs.Sound.volume = 0.5;
  3612. *
  3613. * @property volume
  3614. * @type {Number}
  3615. * @default 1
  3616. * @since 0.6.1
  3617. */
  3618. /**
  3619. * The internal volume level. Use {{#crossLink "Sound/volume:property"}}{{/crossLink}} to adjust the master volume.
  3620. * @property _masterVolume
  3621. * @type {number}
  3622. * @default 1
  3623. * @private
  3624. */
  3625. s._masterVolume = 1;
  3626. /**
  3627. * Use the {{#crossLink "Sound/volume:property"}}{{/crossLink}} property instead.
  3628. * @method _getMasterVolume
  3629. * @private
  3630. * @static
  3631. * @return {Number}
  3632. **/
  3633. s._getMasterVolume = function() {
  3634. return this._masterVolume;
  3635. };
  3636. // Sound.getMasterVolume is @deprecated. Remove for 1.1+
  3637. s.getVolume = createjs.deprecate(s._getMasterVolume, "Sound.getVolume");
  3638. /**
  3639. * Use the {{#crossLink "Sound/volume:property"}}{{/crossLink}} property instead.
  3640. * @method _setMasterVolume
  3641. * @static
  3642. * @private
  3643. **/
  3644. s._setMasterVolume = function(value) {
  3645. if (Number(value) == null) { return; }
  3646. value = Math.max(0, Math.min(1, value));
  3647. s._masterVolume = value;
  3648. if (!this.activePlugin || !this.activePlugin.setVolume || !this.activePlugin.setVolume(value)) {
  3649. var instances = this._instances;
  3650. for (var i = 0, l = instances.length; i < l; i++) {
  3651. instances[i].setMasterVolume(value);
  3652. }
  3653. }
  3654. };
  3655. // Sound.stMasterVolume is @deprecated. Remove for 1.1+
  3656. s.setVolume = createjs.deprecate(s._setMasterVolume, "Sound.setVolume");
  3657. /**
  3658. * Mute/Unmute all audio. Note that muted audio still plays at 0 volume. This global mute value is maintained
  3659. * separately and when set will override, but not change the mute property of individual instances. To mute an individual
  3660. * instance, use AbstractSoundInstance {{#crossLink "AbstractSoundInstance/muted:property"}}{{/crossLink}} instead.
  3661. *
  3662. * <h4>Example</h4>
  3663. *
  3664. * createjs.Sound.muted = true;
  3665. *
  3666. *
  3667. * @property muted
  3668. * @type {Boolean}
  3669. * @default false
  3670. * @since 0.6.1
  3671. */
  3672. s._masterMute = false;
  3673. /**
  3674. * Use the {{#crossLink "Sound/muted:property"}}{{/crossLink}} property instead.
  3675. * @method _getMute
  3676. * @returns {Boolean}
  3677. * @static
  3678. * @private
  3679. */
  3680. s._getMute = function () {
  3681. return this._masterMute;
  3682. };
  3683. // Sound.getMute is @deprecated. Remove for 1.1+
  3684. s.getMute = createjs.deprecate(s._getMute, "Sound.getMute");
  3685. /**
  3686. * Use the {{#crossLink "Sound/muted:property"}}{{/crossLink}} property instead.
  3687. * @method _setMute
  3688. * @param {Boolean} value The muted value
  3689. * @static
  3690. * @private
  3691. */
  3692. s._setMute = function (value) {
  3693. if (value == null) { return; }
  3694. this._masterMute = value;
  3695. if (!this.activePlugin || !this.activePlugin.setMute || !this.activePlugin.setMute(value)) {
  3696. var instances = this._instances;
  3697. for (var i = 0, l = instances.length; i < l; i++) {
  3698. instances[i].setMasterMute(value);
  3699. }
  3700. }
  3701. };
  3702. // Sound.setMute is @deprecated. Remove for 1.1+
  3703. s.setMute = createjs.deprecate(s._setMute, "Sound.setMute");
  3704. /**
  3705. * Get the active plugins capabilities, which help determine if a plugin can be used in the current environment,
  3706. * or if the plugin supports a specific feature. Capabilities include:
  3707. * <ul>
  3708. * <li><b>panning:</b> If the plugin can pan audio from left to right</li>
  3709. * <li><b>volume;</b> If the plugin can control audio volume.</li>
  3710. * <li><b>tracks:</b> The maximum number of audio tracks that can be played back at a time. This will be -1
  3711. * if there is no known limit.</li>
  3712. * <br />An entry for each file type in {{#crossLink "Sound/SUPPORTED_EXTENSIONS:property"}}{{/crossLink}}:
  3713. * <li><b>mp3:</b> If MP3 audio is supported.</li>
  3714. * <li><b>ogg:</b> If OGG audio is supported.</li>
  3715. * <li><b>wav:</b> If WAV audio is supported.</li>
  3716. * <li><b>mpeg:</b> If MPEG audio is supported.</li>
  3717. * <li><b>m4a:</b> If M4A audio is supported.</li>
  3718. * <li><b>mp4:</b> If MP4 audio is supported.</li>
  3719. * <li><b>aiff:</b> If aiff audio is supported.</li>
  3720. * <li><b>wma:</b> If wma audio is supported.</li>
  3721. * <li><b>mid:</b> If mid audio is supported.</li>
  3722. * </ul>
  3723. *
  3724. * You can get a specific capability of the active plugin using standard object notation
  3725. *
  3726. * <h4>Example</h4>
  3727. *
  3728. * var mp3 = createjs.Sound.capabilities.mp3;
  3729. *
  3730. * Note this property is read only.
  3731. *
  3732. * @property capabilities
  3733. * @type {Object}
  3734. * @static
  3735. * @readOnly
  3736. * @since 0.6.1
  3737. */
  3738. /**
  3739. * Use the {{#crossLink "Sound/capabilities:property"}}{{/crossLink}} property instead.
  3740. * @returns {null}
  3741. * @private
  3742. */
  3743. s._getCapabilities = function() {
  3744. if (s.activePlugin == null) { return null; }
  3745. return s.activePlugin._capabilities;
  3746. };
  3747. // Sound.getCapabilities is @deprecated. Remove for 1.1+
  3748. s.getCapabilities = createjs.deprecate(s._getCapabilities, "Sound.getCapabilities");
  3749. Object.defineProperties(s, {
  3750. volume: { get: s._getMasterVolume, set: s._setMasterVolume },
  3751. muted: { get: s._getMute, set: s._setMute },
  3752. capabilities: { get: s._getCapabilities }
  3753. });
  3754. // Class Private properties
  3755. /**
  3756. * Determines if the plugins have been registered. If false, the first call to {{#crossLink "play"}}{{/crossLink}} will instantiate the default
  3757. * plugins ({{#crossLink "WebAudioPlugin"}}{{/crossLink}}, followed by {{#crossLink "HTMLAudioPlugin"}}{{/crossLink}}).
  3758. * If plugins have been registered, but none are applicable, then sound playback will fail.
  3759. * @property _pluginsRegistered
  3760. * @type {Boolean}
  3761. * @default false
  3762. * @static
  3763. * @private
  3764. */
  3765. s._pluginsRegistered = false;
  3766. /**
  3767. * Used internally to assign unique IDs to each AbstractSoundInstance.
  3768. * @property _lastID
  3769. * @type {Number}
  3770. * @static
  3771. * @private
  3772. */
  3773. s._lastID = 0;
  3774. /**
  3775. * An array containing all currently playing instances. This allows Sound to control the volume, mute, and playback of
  3776. * all instances when using static APIs like {{#crossLink "Sound/stop"}}{{/crossLink}} and {{#crossLink "Sound/volume:property"}}{{/crossLink}}.
  3777. * When an instance has finished playback, it gets removed via the {{#crossLink "Sound/finishedPlaying"}}{{/crossLink}}
  3778. * method. If the user replays an instance, it gets added back in via the {{#crossLink "Sound/_beginPlaying"}}{{/crossLink}}
  3779. * method.
  3780. * @property _instances
  3781. * @type {Array}
  3782. * @private
  3783. * @static
  3784. */
  3785. s._instances = [];
  3786. /**
  3787. * An object hash storing objects with sound sources, startTime, and duration via there corresponding ID.
  3788. * @property _idHash
  3789. * @type {Object}
  3790. * @private
  3791. * @static
  3792. */
  3793. s._idHash = {};
  3794. /**
  3795. * An object hash that stores preloading sound sources via the parsed source that is passed to the plugin. Contains the
  3796. * source, id, and data that was passed in by the user. Parsed sources can contain multiple instances of source, id,
  3797. * and data.
  3798. * @property _preloadHash
  3799. * @type {Object}
  3800. * @private
  3801. * @static
  3802. */
  3803. s._preloadHash = {};
  3804. /**
  3805. * An object hash storing {{#crossLink "PlayPropsConfig"}}{{/crossLink}} via the parsed source that is passed as defaultPlayProps in
  3806. * {{#crossLink "Sound/registerSound"}}{{/crossLink}} and {{#crossLink "Sound/registerSounds"}}{{/crossLink}}.
  3807. * @property _defaultPlayPropsHash
  3808. * @type {Object}
  3809. * @private
  3810. * @static
  3811. * @since 0.6.1
  3812. */
  3813. s._defaultPlayPropsHash = {};
  3814. // EventDispatcher methods:
  3815. s.addEventListener = null;
  3816. s.removeEventListener = null;
  3817. s.removeAllEventListeners = null;
  3818. s.dispatchEvent = null;
  3819. s.hasEventListener = null;
  3820. s._listeners = null;
  3821. createjs.EventDispatcher.initialize(s); // inject EventDispatcher methods.
  3822. // Events
  3823. /**
  3824. * This event is fired when a file finishes loading internally. This event is fired for each loaded sound,
  3825. * so any handler methods should look up the <code>event.src</code> to handle a particular sound.
  3826. * @event fileload
  3827. * @param {Object} target The object that dispatched the event.
  3828. * @param {String} type The event type.
  3829. * @param {String} src The source of the sound that was loaded.
  3830. * @param {String} [id] The id passed in when the sound was registered. If one was not provided, it will be null.
  3831. * @param {Number|Object} [data] Any additional data associated with the item. If not provided, it will be undefined.
  3832. * @since 0.4.1
  3833. */
  3834. /**
  3835. * This event is fired when a file fails loading internally. This event is fired for each loaded sound,
  3836. * so any handler methods should look up the <code>event.src</code> to handle a particular sound.
  3837. * @event fileerror
  3838. * @param {Object} target The object that dispatched the event.
  3839. * @param {String} type The event type.
  3840. * @param {String} src The source of the sound that was loaded.
  3841. * @param {String} [id] The id passed in when the sound was registered. If one was not provided, it will be null.
  3842. * @param {Number|Object} [data] Any additional data associated with the item. If not provided, it will be undefined.
  3843. * @since 0.6.0
  3844. */
  3845. // Class Public Methods
  3846. /**
  3847. * Get the preload rules to allow Sound to be used as a plugin by <a href="http://preloadjs.com" target="_blank">PreloadJS</a>.
  3848. * Any load calls that have the matching type or extension will fire the callback method, and use the resulting
  3849. * object, which is potentially modified by Sound. This helps when determining the correct path, as well as
  3850. * registering the audio instance(s) with Sound. This method should not be called, except by PreloadJS.
  3851. * @method getPreloadHandlers
  3852. * @return {Object} An object containing:
  3853. * <ul><li>callback: A preload callback that is fired when a file is added to PreloadJS, which provides
  3854. * Sound a mechanism to modify the load parameters, select the correct file format, register the sound, etc.</li>
  3855. * <li>types: A list of file types that are supported by Sound (currently supports "sound").</li>
  3856. * <li>extensions: A list of file extensions that are supported by Sound (see {{#crossLink "Sound/SUPPORTED_EXTENSIONS:property"}}{{/crossLink}}).</li></ul>
  3857. * @static
  3858. * @private
  3859. */
  3860. s.getPreloadHandlers = function () {
  3861. return {
  3862. callback:createjs.proxy(s.initLoad, s),
  3863. types:["sound"],
  3864. extensions:s.SUPPORTED_EXTENSIONS
  3865. };
  3866. };
  3867. /**
  3868. * Used to dispatch fileload events from internal loading.
  3869. * @method _handleLoadComplete
  3870. * @param event A loader event.
  3871. * @private
  3872. * @static
  3873. * @since 0.6.0
  3874. */
  3875. s._handleLoadComplete = function(event) {
  3876. var src = event.target.getItem().src;
  3877. if (!s._preloadHash[src]) {return;}
  3878. for (var i = 0, l = s._preloadHash[src].length; i < l; i++) {
  3879. var item = s._preloadHash[src][i];
  3880. s._preloadHash[src][i] = true;
  3881. if (!s.hasEventListener("fileload")) { continue; }
  3882. var event = new createjs.Event("fileload");
  3883. event.src = item.src;
  3884. event.id = item.id;
  3885. event.data = item.data;
  3886. event.sprite = item.sprite;
  3887. s.dispatchEvent(event);
  3888. }
  3889. };
  3890. /**
  3891. * Used to dispatch error events from internal preloading.
  3892. * @param event
  3893. * @private
  3894. * @since 0.6.0
  3895. * @static
  3896. */
  3897. s._handleLoadError = function(event) {
  3898. var src = event.target.getItem().src;
  3899. if (!s._preloadHash[src]) {return;}
  3900. for (var i = 0, l = s._preloadHash[src].length; i < l; i++) {
  3901. var item = s._preloadHash[src][i];
  3902. s._preloadHash[src][i] = false;
  3903. if (!s.hasEventListener("fileerror")) { continue; }
  3904. var event = new createjs.Event("fileerror");
  3905. event.src = item.src;
  3906. event.id = item.id;
  3907. event.data = item.data;
  3908. event.sprite = item.sprite;
  3909. s.dispatchEvent(event);
  3910. }
  3911. };
  3912. /**
  3913. * Used by {{#crossLink "Sound/registerPlugins"}}{{/crossLink}} to register a Sound plugin.
  3914. *
  3915. * @method _registerPlugin
  3916. * @param {Object} plugin The plugin class to install.
  3917. * @return {Boolean} Whether the plugin was successfully initialized.
  3918. * @static
  3919. * @private
  3920. */
  3921. s._registerPlugin = function (plugin) {
  3922. // Note: Each plugin is passed in as a class reference, but we store the activePlugin as an instance
  3923. if (plugin.isSupported()) {
  3924. s.activePlugin = new plugin();
  3925. return true;
  3926. }
  3927. return false;
  3928. };
  3929. /**
  3930. * Register a list of Sound plugins, in order of precedence. To register a single plugin, pass a single element in the array.
  3931. *
  3932. * <h4>Example</h4>
  3933. *
  3934. * createjs.FlashAudioPlugin.swfPath = "../src/soundjs/flashaudio/";
  3935. * createjs.Sound.registerPlugins([createjs.WebAudioPlugin, createjs.HTMLAudioPlugin, createjs.FlashAudioPlugin]);
  3936. *
  3937. * @method registerPlugins
  3938. * @param {Array} plugins An array of plugins classes to install.
  3939. * @return {Boolean} Whether a plugin was successfully initialized.
  3940. * @static
  3941. */
  3942. s.registerPlugins = function (plugins) {
  3943. s._pluginsRegistered = true;
  3944. for (var i = 0, l = plugins.length; i < l; i++) {
  3945. if (s._registerPlugin(plugins[i])) {
  3946. return true;
  3947. }
  3948. }
  3949. return false;
  3950. };
  3951. /**
  3952. * Initialize the default plugins. This method is automatically called when any audio is played or registered before
  3953. * the user has manually registered plugins, and enables Sound to work without manual plugin setup. Currently, the
  3954. * default plugins are {{#crossLink "WebAudioPlugin"}}{{/crossLink}} followed by {{#crossLink "HTMLAudioPlugin"}}{{/crossLink}}.
  3955. *
  3956. * <h4>Example</h4>
  3957. *
  3958. * if (!createjs.initializeDefaultPlugins()) { return; }
  3959. *
  3960. * @method initializeDefaultPlugins
  3961. * @returns {Boolean} True if a plugin was initialized, false otherwise.
  3962. * @since 0.4.0
  3963. * @static
  3964. */
  3965. s.initializeDefaultPlugins = function () {
  3966. if (s.activePlugin != null) {return true;}
  3967. if (s._pluginsRegistered) {return false;}
  3968. if (s.registerPlugins([createjs.WebAudioPlugin, createjs.HTMLAudioPlugin])) {return true;}
  3969. return false;
  3970. };
  3971. /**
  3972. * Determines if Sound has been initialized, and a plugin has been activated.
  3973. *
  3974. * <h4>Example</h4>
  3975. * This example sets up a Flash fallback, but only if there is no plugin specified yet.
  3976. *
  3977. * if (!createjs.Sound.isReady()) {
  3978. * createjs.FlashAudioPlugin.swfPath = "../src/soundjs/flashaudio/";
  3979. * createjs.Sound.registerPlugins([createjs.WebAudioPlugin, createjs.HTMLAudioPlugin, createjs.FlashAudioPlugin]);
  3980. * }
  3981. *
  3982. * @method isReady
  3983. * @return {Boolean} If Sound has initialized a plugin.
  3984. * @static
  3985. */
  3986. s.isReady = function () {
  3987. return (s.activePlugin != null);
  3988. };
  3989. /**
  3990. * Process manifest items from <a href="http://preloadjs.com" target="_blank">PreloadJS</a>. This method is intended
  3991. * for usage by a plugin, and not for direct interaction.
  3992. * @method initLoad
  3993. * @param {Object} src The object to load.
  3994. * @return {Object|AbstractLoader} An instance of AbstractLoader.
  3995. * @private
  3996. * @static
  3997. */
  3998. s.initLoad = function (loadItem) {
  3999. if (loadItem.type == "video") { return true; } // Don't handle video. PreloadJS's plugin model is really aggressive.
  4000. return s._registerSound(loadItem);
  4001. };
  4002. /**
  4003. * Internal method for loading sounds. This should not be called directly.
  4004. *
  4005. * @method _registerSound
  4006. * @param {Object} src The object to load, containing src property and optionally containing id and data.
  4007. * @return {Object} An object with the modified values that were passed in, which defines the sound.
  4008. * Returns false if the source cannot be parsed or no plugins can be initialized.
  4009. * Returns true if the source is already loaded.
  4010. * @static
  4011. * @private
  4012. * @since 0.6.0
  4013. */
  4014. s._registerSound = function (loadItem) {
  4015. if (!s.initializeDefaultPlugins()) {return false;}
  4016. var details;
  4017. if (loadItem.src instanceof Object) {
  4018. details = s._parseSrc(loadItem.src);
  4019. details.src = loadItem.path + details.src;
  4020. } else {
  4021. details = s._parsePath(loadItem.src);
  4022. }
  4023. if (details == null) {return false;}
  4024. loadItem.src = details.src;
  4025. loadItem.type = "sound";
  4026. var data = loadItem.data;
  4027. var numChannels = null;
  4028. if (data != null) {
  4029. if (!isNaN(data.channels)) {
  4030. numChannels = parseInt(data.channels);
  4031. } else if (!isNaN(data)) {
  4032. numChannels = parseInt(data);
  4033. }
  4034. if(data.audioSprite) {
  4035. var sp;
  4036. for(var i = data.audioSprite.length; i--; ) {
  4037. sp = data.audioSprite[i];
  4038. s._idHash[sp.id] = {src: loadItem.src, startTime: parseInt(sp.startTime), duration: parseInt(sp.duration)};
  4039. if (sp.defaultPlayProps) {
  4040. s._defaultPlayPropsHash[sp.id] = createjs.PlayPropsConfig.create(sp.defaultPlayProps);
  4041. }
  4042. }
  4043. }
  4044. }
  4045. if (loadItem.id != null) {s._idHash[loadItem.id] = {src: loadItem.src}};
  4046. var loader = s.activePlugin.register(loadItem);
  4047. SoundChannel.create(loadItem.src, numChannels);
  4048. // return the number of instances to the user. This will also be returned in the load event.
  4049. if (data == null || !isNaN(data)) {
  4050. loadItem.data = numChannels || SoundChannel.maxPerChannel();
  4051. } else {
  4052. loadItem.data.channels = numChannels || SoundChannel.maxPerChannel();
  4053. }
  4054. if (loader.type) {loadItem.type = loader.type;}
  4055. if (loadItem.defaultPlayProps) {
  4056. s._defaultPlayPropsHash[loadItem.src] = createjs.PlayPropsConfig.create(loadItem.defaultPlayProps);
  4057. }
  4058. return loader;
  4059. };
  4060. /**
  4061. * Register an audio file for loading and future playback in Sound. This is automatically called when using
  4062. * <a href="http://preloadjs.com" target="_blank">PreloadJS</a>. It is recommended to register all sounds that
  4063. * need to be played back in order to properly prepare and preload them. Sound does internal preloading when required.
  4064. *
  4065. * <h4>Example</h4>
  4066. *
  4067. * createjs.Sound.alternateExtensions = ["mp3"];
  4068. * createjs.Sound.on("fileload", handleLoad); // add an event listener for when load is completed
  4069. * createjs.Sound.registerSound("myAudioPath/mySound.ogg", "myID", 3);
  4070. * createjs.Sound.registerSound({ogg:"path1/mySound.ogg", mp3:"path2/mySoundNoExtension"}, "myID", 3);
  4071. *
  4072. *
  4073. * @method registerSound
  4074. * @param {String | Object} src The source or an Object with a "src" property or an Object with multiple extension labeled src properties.
  4075. * @param {String} [id] An id specified by the user to play the sound later. Note id is required for when src is multiple extension labeled src properties.
  4076. * @param {Number | Object} [data] Data associated with the item. Sound uses the data parameter as the number of
  4077. * channels for an audio instance, however a "channels" property can be appended to the data object if it is used
  4078. * for other information. The audio channels will set a default based on plugin if no value is found.
  4079. * Sound also uses the data property to hold an {{#crossLink "AudioSprite"}}{{/crossLink}} array of objects in the following format {id, startTime, duration}.<br/>
  4080. * id used to play the sound later, in the same manner as a sound src with an id.<br/>
  4081. * startTime is the initial offset to start playback and loop from, in milliseconds.<br/>
  4082. * duration is the amount of time to play the clip for, in milliseconds.<br/>
  4083. * This allows Sound to support audio sprites that are played back by id.
  4084. * @param {string} basePath Set a path that will be prepended to src for loading.
  4085. * @param {Object | PlayPropsConfig} defaultPlayProps Optional Playback properties that will be set as the defaults on any new AbstractSoundInstance.
  4086. * See {{#crossLink "PlayPropsConfig"}}{{/crossLink}} for options.
  4087. * @return {Object} An object with the modified values that were passed in, which defines the sound.
  4088. * Returns false if the source cannot be parsed or no plugins can be initialized.
  4089. * Returns true if the source is already loaded.
  4090. * @static
  4091. * @since 0.4.0
  4092. */
  4093. s.registerSound = function (src, id, data, basePath, defaultPlayProps) {
  4094. var loadItem = {src: src, id: id, data:data, defaultPlayProps:defaultPlayProps};
  4095. if (src instanceof Object && src.src) {
  4096. basePath = id;
  4097. loadItem = src;
  4098. }
  4099. loadItem = createjs.LoadItem.create(loadItem);
  4100. loadItem.path = basePath;
  4101. if (basePath != null && !(loadItem.src instanceof Object)) {loadItem.src = basePath + loadItem.src;}
  4102. var loader = s._registerSound(loadItem);
  4103. if(!loader) {return false;}
  4104. if (!s._preloadHash[loadItem.src]) { s._preloadHash[loadItem.src] = [];}
  4105. s._preloadHash[loadItem.src].push(loadItem);
  4106. if (s._preloadHash[loadItem.src].length == 1) {
  4107. // OJR note this will disallow reloading a sound if loading fails or the source changes
  4108. loader.on("complete", this._handleLoadComplete, this);
  4109. loader.on("error", this._handleLoadError, this);
  4110. s.activePlugin.preload(loader);
  4111. } else {
  4112. if (s._preloadHash[loadItem.src][0] == true) {return true;}
  4113. }
  4114. return loadItem;
  4115. };
  4116. /**
  4117. * Register an array of audio files for loading and future playback in Sound. It is recommended to register all
  4118. * sounds that need to be played back in order to properly prepare and preload them. Sound does internal preloading
  4119. * when required.
  4120. *
  4121. * <h4>Example</h4>
  4122. *
  4123. * var assetPath = "./myAudioPath/";
  4124. * var sounds = [
  4125. * {src:"asset0.ogg", id:"example"},
  4126. * {src:"asset1.ogg", id:"1", data:6},
  4127. * {src:"asset2.mp3", id:"works"}
  4128. * {src:{mp3:"path1/asset3.mp3", ogg:"path2/asset3NoExtension"}, id:"better"}
  4129. * ];
  4130. * createjs.Sound.alternateExtensions = ["mp3"]; // if the passed extension is not supported, try this extension
  4131. * createjs.Sound.on("fileload", handleLoad); // call handleLoad when each sound loads
  4132. * createjs.Sound.registerSounds(sounds, assetPath);
  4133. *
  4134. * @method registerSounds
  4135. * @param {Array} sounds An array of objects to load. Objects are expected to be in the format needed for
  4136. * {{#crossLink "Sound/registerSound"}}{{/crossLink}}: <code>{src:srcURI, id:ID, data:Data}</code>
  4137. * with "id" and "data" being optional.
  4138. * You can also pass an object with path and manifest properties, where path is a basePath and manifest is an array of objects to load.
  4139. * Note id is required if src is an object with extension labeled src properties.
  4140. * @param {string} basePath Set a path that will be prepended to each src when loading. When creating, playing, or removing
  4141. * audio that was loaded with a basePath by src, the basePath must be included.
  4142. * @return {Object} An array of objects with the modified values that were passed in, which defines each sound.
  4143. * Like registerSound, it will return false for any values when the source cannot be parsed or if no plugins can be initialized.
  4144. * Also, it will return true for any values when the source is already loaded.
  4145. * @static
  4146. * @since 0.6.0
  4147. */
  4148. s.registerSounds = function (sounds, basePath) {
  4149. var returnValues = [];
  4150. if (sounds.path) {
  4151. if (!basePath) {
  4152. basePath = sounds.path;
  4153. } else {
  4154. basePath = basePath + sounds.path;
  4155. }
  4156. sounds = sounds.manifest;
  4157. // TODO document this feature
  4158. }
  4159. for (var i = 0, l = sounds.length; i < l; i++) {
  4160. returnValues[i] = createjs.Sound.registerSound(sounds[i].src, sounds[i].id, sounds[i].data, basePath, sounds[i].defaultPlayProps);
  4161. }
  4162. return returnValues;
  4163. };
  4164. /**
  4165. * Remove a sound that has been registered with {{#crossLink "Sound/registerSound"}}{{/crossLink}} or
  4166. * {{#crossLink "Sound/registerSounds"}}{{/crossLink}}.
  4167. * <br />Note this will stop playback on active instances playing this sound before deleting them.
  4168. * <br />Note if you passed in a basePath, you need to pass it or prepend it to the src here.
  4169. *
  4170. * <h4>Example</h4>
  4171. *
  4172. * createjs.Sound.removeSound("myID");
  4173. * createjs.Sound.removeSound("myAudioBasePath/mySound.ogg");
  4174. * createjs.Sound.removeSound("myPath/myOtherSound.mp3", "myBasePath/");
  4175. * createjs.Sound.removeSound({mp3:"musicNoExtension", ogg:"music.ogg"}, "myBasePath/");
  4176. *
  4177. * @method removeSound
  4178. * @param {String | Object} src The src or ID of the audio, or an Object with a "src" property, or an Object with multiple extension labeled src properties.
  4179. * @param {string} basePath Set a path that will be prepended to each src when removing.
  4180. * @return {Boolean} True if sound is successfully removed.
  4181. * @static
  4182. * @since 0.4.1
  4183. */
  4184. s.removeSound = function(src, basePath) {
  4185. if (s.activePlugin == null) {return false;}
  4186. if (src instanceof Object && src.src) {src = src.src;}
  4187. var details;
  4188. if (src instanceof Object) {
  4189. details = s._parseSrc(src);
  4190. } else {
  4191. src = s._getSrcById(src).src;
  4192. details = s._parsePath(src);
  4193. }
  4194. if (details == null) {return false;}
  4195. src = details.src;
  4196. if (basePath != null) {src = basePath + src;}
  4197. for(var prop in s._idHash){
  4198. if(s._idHash[prop].src == src) {
  4199. delete(s._idHash[prop]);
  4200. }
  4201. }
  4202. // clear from SoundChannel, which also stops and deletes all instances
  4203. SoundChannel.removeSrc(src);
  4204. delete(s._preloadHash[src]);
  4205. s.activePlugin.removeSound(src);
  4206. return true;
  4207. };
  4208. /**
  4209. * Remove an array of audio files that have been registered with {{#crossLink "Sound/registerSound"}}{{/crossLink}} or
  4210. * {{#crossLink "Sound/registerSounds"}}{{/crossLink}}.
  4211. * <br />Note this will stop playback on active instances playing this audio before deleting them.
  4212. * <br />Note if you passed in a basePath, you need to pass it or prepend it to the src here.
  4213. *
  4214. * <h4>Example</h4>
  4215. *
  4216. * assetPath = "./myPath/";
  4217. * var sounds = [
  4218. * {src:"asset0.ogg", id:"example"},
  4219. * {src:"asset1.ogg", id:"1", data:6},
  4220. * {src:"asset2.mp3", id:"works"}
  4221. * ];
  4222. * createjs.Sound.removeSounds(sounds, assetPath);
  4223. *
  4224. * @method removeSounds
  4225. * @param {Array} sounds An array of objects to remove. Objects are expected to be in the format needed for
  4226. * {{#crossLink "Sound/removeSound"}}{{/crossLink}}: <code>{srcOrID:srcURIorID}</code>.
  4227. * You can also pass an object with path and manifest properties, where path is a basePath and manifest is an array of objects to remove.
  4228. * @param {string} basePath Set a path that will be prepended to each src when removing.
  4229. * @return {Object} An array of Boolean values representing if the sounds with the same array index were
  4230. * successfully removed.
  4231. * @static
  4232. * @since 0.4.1
  4233. */
  4234. s.removeSounds = function (sounds, basePath) {
  4235. var returnValues = [];
  4236. if (sounds.path) {
  4237. if (!basePath) {
  4238. basePath = sounds.path;
  4239. } else {
  4240. basePath = basePath + sounds.path;
  4241. }
  4242. sounds = sounds.manifest;
  4243. }
  4244. for (var i = 0, l = sounds.length; i < l; i++) {
  4245. returnValues[i] = createjs.Sound.removeSound(sounds[i].src, basePath);
  4246. }
  4247. return returnValues;
  4248. };
  4249. /**
  4250. * Remove all sounds that have been registered with {{#crossLink "Sound/registerSound"}}{{/crossLink}} or
  4251. * {{#crossLink "Sound/registerSounds"}}{{/crossLink}}.
  4252. * <br />Note this will stop playback on all active sound instances before deleting them.
  4253. *
  4254. * <h4>Example</h4>
  4255. *
  4256. * createjs.Sound.removeAllSounds();
  4257. *
  4258. * @method removeAllSounds
  4259. * @static
  4260. * @since 0.4.1
  4261. */
  4262. s.removeAllSounds = function() {
  4263. s._idHash = {};
  4264. s._preloadHash = {};
  4265. SoundChannel.removeAll();
  4266. if (s.activePlugin) {s.activePlugin.removeAllSounds();}
  4267. };
  4268. /**
  4269. * Check if a source has been loaded by internal preloaders. This is necessary to ensure that sounds that are
  4270. * not completed preloading will not kick off a new internal preload if they are played.
  4271. *
  4272. * <h4>Example</h4>
  4273. *
  4274. * var mySound = "assetPath/asset0.ogg";
  4275. * if(createjs.Sound.loadComplete(mySound) {
  4276. * createjs.Sound.play(mySound);
  4277. * }
  4278. *
  4279. * @method loadComplete
  4280. * @param {String} src The src or id that is being loaded.
  4281. * @return {Boolean} If the src is already loaded.
  4282. * @since 0.4.0
  4283. * @static
  4284. */
  4285. s.loadComplete = function (src) {
  4286. if (!s.isReady()) { return false; }
  4287. var details = s._parsePath(src);
  4288. if (details) {
  4289. src = s._getSrcById(details.src).src;
  4290. } else {
  4291. src = s._getSrcById(src).src;
  4292. }
  4293. if(s._preloadHash[src] == undefined) {return false;}
  4294. return (s._preloadHash[src][0] == true); // src only loads once, so if it's true for the first it's true for all
  4295. };
  4296. /**
  4297. * Parse the path of a sound. Alternate extensions will be attempted in order if the
  4298. * current extension is not supported
  4299. * @method _parsePath
  4300. * @param {String} value The path to an audio source.
  4301. * @return {Object} A formatted object that can be registered with the {{#crossLink "Sound/activePlugin:property"}}{{/crossLink}}
  4302. * and returned to a preloader like <a href="http://preloadjs.com" target="_blank">PreloadJS</a>.
  4303. * @private
  4304. * @static
  4305. */
  4306. s._parsePath = function (value) {
  4307. if (typeof(value) != "string") {value = value.toString();}
  4308. var match = value.match(s.FILE_PATTERN);
  4309. if (match == null) {return false;}
  4310. var name = match[4];
  4311. var ext = match[5];
  4312. var c = s.capabilities;
  4313. var i = 0;
  4314. while (!c[ext]) {
  4315. ext = s.alternateExtensions[i++];
  4316. if (i > s.alternateExtensions.length) { return null;} // no extensions are supported
  4317. }
  4318. value = value.replace("."+match[5], "."+ext);
  4319. var ret = {name:name, src:value, extension:ext};
  4320. return ret;
  4321. };
  4322. /**
  4323. * Parse the path of a sound based on properties of src matching with supported extensions.
  4324. * Returns false if none of the properties are supported
  4325. * @method _parseSrc
  4326. * @param {Object} value The paths to an audio source, indexed by extension type.
  4327. * @return {Object} A formatted object that can be registered with the {{#crossLink "Sound/activePlugin:property"}}{{/crossLink}}
  4328. * and returned to a preloader like <a href="http://preloadjs.com" target="_blank">PreloadJS</a>.
  4329. * @private
  4330. * @static
  4331. */
  4332. s._parseSrc = function (value) {
  4333. var ret = {name:undefined, src:undefined, extension:undefined};
  4334. var c = s.capabilities;
  4335. for (var prop in value) {
  4336. if(value.hasOwnProperty(prop) && c[prop]) {
  4337. ret.src = value[prop];
  4338. ret.extension = prop;
  4339. break;
  4340. }
  4341. }
  4342. if (!ret.src) {return false;} // no matches
  4343. var i = ret.src.lastIndexOf("/");
  4344. if (i != -1) {
  4345. ret.name = ret.src.slice(i+1);
  4346. } else {
  4347. ret.name = ret.src;
  4348. }
  4349. return ret;
  4350. };
  4351. /* ---------------
  4352. Static API.
  4353. --------------- */
  4354. /**
  4355. * Play a sound and get a {{#crossLink "AbstractSoundInstance"}}{{/crossLink}} to control. If the sound fails to
  4356. * play, an AbstractSoundInstance will still be returned, and have a playState of {{#crossLink "Sound/PLAY_FAILED:property"}}{{/crossLink}}.
  4357. * Note that even on sounds with failed playback, you may still be able to call the {{#crossLink "AbstractSoundInstance/play"}}{{/crossLink}},
  4358. * method, since the failure could be due to lack of available channels. If the src does not have a supported
  4359. * extension or if there is no available plugin, a default AbstractSoundInstance will still be returned, which will
  4360. * not play any audio, but will not generate errors.
  4361. *
  4362. * <h4>Example</h4>
  4363. *
  4364. * createjs.Sound.on("fileload", handleLoad);
  4365. * createjs.Sound.registerSound("myAudioPath/mySound.mp3", "myID", 3);
  4366. * function handleLoad(event) {
  4367. * createjs.Sound.play("myID");
  4368. * // store off AbstractSoundInstance for controlling
  4369. * var myInstance = createjs.Sound.play("myID", {interrupt: createjs.Sound.INTERRUPT_ANY, loop:-1});
  4370. * }
  4371. *
  4372. * NOTE: To create an audio sprite that has not already been registered, both startTime and duration need to be set.
  4373. * This is only when creating a new audio sprite, not when playing using the id of an already registered audio sprite.
  4374. *
  4375. * @method play
  4376. * @param {String} src The src or ID of the audio.
  4377. * @param {Object | PlayPropsConfig} props A PlayPropsConfig instance, or an object that contains the parameters to
  4378. * play a sound. See the {{#crossLink "PlayPropsConfig"}}{{/crossLink}} for more info.
  4379. * @return {AbstractSoundInstance} A {{#crossLink "AbstractSoundInstance"}}{{/crossLink}} that can be controlled
  4380. * after it is created.
  4381. * @static
  4382. */
  4383. s.play = function (src, props) {
  4384. var playProps = createjs.PlayPropsConfig.create(props);
  4385. var instance = s.createInstance(src, playProps.startTime, playProps.duration);
  4386. var ok = s._playInstance(instance, playProps);
  4387. if (!ok) {instance._playFailed();}
  4388. return instance;
  4389. };
  4390. /**
  4391. * Creates a {{#crossLink "AbstractSoundInstance"}}{{/crossLink}} using the passed in src. If the src does not have a
  4392. * supported extension or if there is no available plugin, a default AbstractSoundInstance will be returned that can be
  4393. * called safely but does nothing.
  4394. *
  4395. * <h4>Example</h4>
  4396. *
  4397. * var myInstance = null;
  4398. * createjs.Sound.on("fileload", handleLoad);
  4399. * createjs.Sound.registerSound("myAudioPath/mySound.mp3", "myID", 3);
  4400. * function handleLoad(event) {
  4401. * myInstance = createjs.Sound.createInstance("myID");
  4402. * // alternately we could call the following
  4403. * myInstance = createjs.Sound.createInstance("myAudioPath/mySound.mp3");
  4404. * }
  4405. *
  4406. * NOTE to create an audio sprite that has not already been registered, both startTime and duration need to be set.
  4407. * This is only when creating a new audio sprite, not when playing using the id of an already registered audio sprite.
  4408. *
  4409. * @method createInstance
  4410. * @param {String} src The src or ID of the audio.
  4411. * @param {Number} [startTime=null] To create an audio sprite (with duration), the initial offset to start playback and loop from, in milliseconds.
  4412. * @param {Number} [duration=null] To create an audio sprite (with startTime), the amount of time to play the clip for, in milliseconds.
  4413. * @return {AbstractSoundInstance} A {{#crossLink "AbstractSoundInstance"}}{{/crossLink}} that can be controlled after it is created.
  4414. * Unsupported extensions will return the default AbstractSoundInstance.
  4415. * @since 0.4.0
  4416. * @static
  4417. */
  4418. s.createInstance = function (src, startTime, duration) {
  4419. if (!s.initializeDefaultPlugins()) { return new createjs.DefaultSoundInstance(src, startTime, duration); }
  4420. var defaultPlayProps = s._defaultPlayPropsHash[src]; // for audio sprites, which create and store defaults by id
  4421. src = s._getSrcById(src);
  4422. var details = s._parsePath(src.src);
  4423. var instance = null;
  4424. if (details != null && details.src != null) {
  4425. SoundChannel.create(details.src);
  4426. if (startTime == null) { startTime = src.startTime; }
  4427. instance = s.activePlugin.create(details.src, startTime, duration || src.duration);
  4428. defaultPlayProps = defaultPlayProps || s._defaultPlayPropsHash[details.src];
  4429. if (defaultPlayProps) {
  4430. instance.applyPlayProps(defaultPlayProps);
  4431. }
  4432. } else {
  4433. instance = new createjs.DefaultSoundInstance(src, startTime, duration);
  4434. }
  4435. instance.uniqueId = s._lastID++;
  4436. return instance;
  4437. };
  4438. /**
  4439. * Stop all audio (global stop). Stopped audio is reset, and not paused. To play audio that has been stopped,
  4440. * call AbstractSoundInstance {{#crossLink "AbstractSoundInstance/play"}}{{/crossLink}}.
  4441. *
  4442. * <h4>Example</h4>
  4443. *
  4444. * createjs.Sound.stop();
  4445. *
  4446. * @method stop
  4447. * @static
  4448. */
  4449. s.stop = function () {
  4450. var instances = this._instances;
  4451. for (var i = instances.length; i--; ) {
  4452. instances[i].stop(); // NOTE stop removes instance from this._instances
  4453. }
  4454. };
  4455. /**
  4456. * Set the default playback properties for all new SoundInstances of the passed in src or ID.
  4457. * See {{#crossLink "PlayPropsConfig"}}{{/crossLink}} for available properties.
  4458. *
  4459. * @method setDefaultPlayProps
  4460. * @param {String} src The src or ID used to register the audio.
  4461. * @param {Object | PlayPropsConfig} playProps The playback properties you would like to set.
  4462. * @since 0.6.1
  4463. */
  4464. s.setDefaultPlayProps = function(src, playProps) {
  4465. src = s._getSrcById(src);
  4466. s._defaultPlayPropsHash[s._parsePath(src.src).src] = createjs.PlayPropsConfig.create(playProps);
  4467. };
  4468. /**
  4469. * Get the default playback properties for the passed in src or ID. These properties are applied to all
  4470. * new SoundInstances. Returns null if default does not exist.
  4471. *
  4472. * @method getDefaultPlayProps
  4473. * @param {String} src The src or ID used to register the audio.
  4474. * @returns {PlayPropsConfig} returns an existing PlayPropsConfig or null if one does not exist
  4475. * @since 0.6.1
  4476. */
  4477. s.getDefaultPlayProps = function(src) {
  4478. src = s._getSrcById(src);
  4479. return s._defaultPlayPropsHash[s._parsePath(src.src).src];
  4480. };
  4481. /* ---------------
  4482. Internal methods
  4483. --------------- */
  4484. /**
  4485. * Play an instance. This is called by the static API, as well as from plugins. This allows the core class to
  4486. * control delays.
  4487. * @method _playInstance
  4488. * @param {AbstractSoundInstance} instance The {{#crossLink "AbstractSoundInstance"}}{{/crossLink}} to start playing.
  4489. * @param {PlayPropsConfig} playProps A PlayPropsConfig object.
  4490. * @return {Boolean} If the sound can start playing. Sounds that fail immediately will return false. Sounds that
  4491. * have a delay will return true, but may still fail to play.
  4492. * @private
  4493. * @static
  4494. */
  4495. s._playInstance = function (instance, playProps) {
  4496. var defaultPlayProps = s._defaultPlayPropsHash[instance.src] || {};
  4497. if (playProps.interrupt == null) {playProps.interrupt = defaultPlayProps.interrupt || s.defaultInterruptBehavior};
  4498. if (playProps.delay == null) {playProps.delay = defaultPlayProps.delay || 0;}
  4499. if (playProps.offset == null) {playProps.offset = instance.position;}
  4500. if (playProps.loop == null) {playProps.loop = instance.loop;}
  4501. if (playProps.volume == null) {playProps.volume = instance.volume;}
  4502. if (playProps.pan == null) {playProps.pan = instance.pan;}
  4503. if (playProps.delay == 0) {
  4504. var ok = s._beginPlaying(instance, playProps);
  4505. if (!ok) {return false;}
  4506. } else {
  4507. //Note that we can't pass arguments to proxy OR setTimeout (IE only), so just wrap the function call.
  4508. // OJR WebAudio may want to handle this differently, so it might make sense to move this functionality into the plugins in the future
  4509. var delayTimeoutId = setTimeout(function () {
  4510. s._beginPlaying(instance, playProps);
  4511. }, playProps.delay);
  4512. instance.delayTimeoutId = delayTimeoutId;
  4513. }
  4514. this._instances.push(instance);
  4515. return true;
  4516. };
  4517. /**
  4518. * Begin playback. This is called immediately or after delay by {{#crossLink "Sound/playInstance"}}{{/crossLink}}.
  4519. * @method _beginPlaying
  4520. * @param {AbstractSoundInstance} instance A {{#crossLink "AbstractSoundInstance"}}{{/crossLink}} to begin playback.
  4521. * @param {PlayPropsConfig} playProps A PlayPropsConfig object.
  4522. * @return {Boolean} If the sound can start playing. If there are no available channels, or the instance fails to
  4523. * start, this will return false.
  4524. * @private
  4525. * @static
  4526. */
  4527. s._beginPlaying = function (instance, playProps) {
  4528. if (!SoundChannel.add(instance, playProps.interrupt)) {
  4529. return false;
  4530. }
  4531. var result = instance._beginPlaying(playProps);
  4532. if (!result) {
  4533. var index = createjs.indexOf(this._instances, instance);
  4534. if (index > -1) {this._instances.splice(index, 1);}
  4535. return false;
  4536. }
  4537. return true;
  4538. };
  4539. /**
  4540. * Get the source of a sound via the ID passed in with a register call. If no ID is found the value is returned
  4541. * instead.
  4542. * @method _getSrcById
  4543. * @param {String} value The ID the sound was registered with.
  4544. * @return {String} The source of the sound if it has been registered with this ID or the value that was passed in.
  4545. * @private
  4546. * @static
  4547. */
  4548. s._getSrcById = function (value) {
  4549. return s._idHash[value] || {src: value};
  4550. };
  4551. /**
  4552. * A sound has completed playback, been interrupted, failed, or been stopped. This method removes the instance from
  4553. * Sound management. It will be added again, if the sound re-plays. Note that this method is called from the
  4554. * instances themselves.
  4555. * @method _playFinished
  4556. * @param {AbstractSoundInstance} instance The instance that finished playback.
  4557. * @private
  4558. * @static
  4559. */
  4560. s._playFinished = function (instance) {
  4561. SoundChannel.remove(instance);
  4562. var index = createjs.indexOf(this._instances, instance);
  4563. if (index > -1) {this._instances.splice(index, 1);} // OJR this will always be > -1, there is no way for an instance to exist without being added to this._instances
  4564. };
  4565. createjs.Sound = Sound;
  4566. /**
  4567. * An internal class that manages the number of active {{#crossLink "AbstractSoundInstance"}}{{/crossLink}} instances for
  4568. * each sound type. This method is only used internally by the {{#crossLink "Sound"}}{{/crossLink}} class.
  4569. *
  4570. * The number of sounds is artificially limited by Sound in order to prevent over-saturation of a
  4571. * single sound, as well as to stay within hardware limitations, although the latter may disappear with better
  4572. * browser support.
  4573. *
  4574. * When a sound is played, this class ensures that there is an available instance, or interrupts an appropriate
  4575. * sound that is already playing.
  4576. * #class SoundChannel
  4577. * @param {String} src The source of the instances
  4578. * @param {Number} [max=1] The number of instances allowed
  4579. * @constructor
  4580. * @protected
  4581. */
  4582. function SoundChannel(src, max) {
  4583. this.init(src, max);
  4584. }
  4585. /* ------------
  4586. Static API
  4587. ------------ */
  4588. /**
  4589. * A hash of channel instances indexed by source.
  4590. * #property channels
  4591. * @type {Object}
  4592. * @static
  4593. */
  4594. SoundChannel.channels = {};
  4595. /**
  4596. * Create a sound channel. Note that if the sound channel already exists, this will fail.
  4597. * #method create
  4598. * @param {String} src The source for the channel
  4599. * @param {Number} max The maximum amount this channel holds. The default is {{#crossLink "SoundChannel.maxDefault"}}{{/crossLink}}.
  4600. * @return {Boolean} If the channels were created.
  4601. * @static
  4602. */
  4603. SoundChannel.create = function (src, max) {
  4604. var channel = SoundChannel.get(src);
  4605. if (channel == null) {
  4606. SoundChannel.channels[src] = new SoundChannel(src, max);
  4607. return true;
  4608. }
  4609. return false;
  4610. };
  4611. /**
  4612. * Delete a sound channel, stop and delete all related instances. Note that if the sound channel does not exist, this will fail.
  4613. * #method remove
  4614. * @param {String} src The source for the channel
  4615. * @return {Boolean} If the channels were deleted.
  4616. * @static
  4617. */
  4618. SoundChannel.removeSrc = function (src) {
  4619. var channel = SoundChannel.get(src);
  4620. if (channel == null) {return false;}
  4621. channel._removeAll(); // this stops and removes all active instances
  4622. delete(SoundChannel.channels[src]);
  4623. return true;
  4624. };
  4625. /**
  4626. * Delete all sound channels, stop and delete all related instances.
  4627. * #method removeAll
  4628. * @static
  4629. */
  4630. SoundChannel.removeAll = function () {
  4631. for(var channel in SoundChannel.channels) {
  4632. SoundChannel.channels[channel]._removeAll(); // this stops and removes all active instances
  4633. }
  4634. SoundChannel.channels = {};
  4635. };
  4636. /**
  4637. * Add an instance to a sound channel.
  4638. * #method add
  4639. * @param {AbstractSoundInstance} instance The instance to add to the channel
  4640. * @param {String} interrupt The interrupt value to use. Please see the {{#crossLink "Sound/play"}}{{/crossLink}}
  4641. * for details on interrupt modes.
  4642. * @return {Boolean} The success of the method call. If the channel is full, it will return false.
  4643. * @static
  4644. */
  4645. SoundChannel.add = function (instance, interrupt) {
  4646. var channel = SoundChannel.get(instance.src);
  4647. if (channel == null) {return false;}
  4648. return channel._add(instance, interrupt);
  4649. };
  4650. /**
  4651. * Remove an instance from the channel.
  4652. * #method remove
  4653. * @param {AbstractSoundInstance} instance The instance to remove from the channel
  4654. * @return The success of the method call. If there is no channel, it will return false.
  4655. * @static
  4656. */
  4657. SoundChannel.remove = function (instance) {
  4658. var channel = SoundChannel.get(instance.src);
  4659. if (channel == null) {return false;}
  4660. channel._remove(instance);
  4661. return true;
  4662. };
  4663. /**
  4664. * Get the maximum number of sounds you can have in a channel.
  4665. * #method maxPerChannel
  4666. * @return {Number} The maximum number of sounds you can have in a channel.
  4667. */
  4668. SoundChannel.maxPerChannel = function () {
  4669. return p.maxDefault;
  4670. };
  4671. /**
  4672. * Get a channel instance by its src.
  4673. * #method get
  4674. * @param {String} src The src to use to look up the channel
  4675. * @static
  4676. */
  4677. SoundChannel.get = function (src) {
  4678. return SoundChannel.channels[src];
  4679. };
  4680. var p = SoundChannel.prototype;
  4681. p.constructor = SoundChannel;
  4682. /**
  4683. * The source of the channel.
  4684. * #property src
  4685. * @type {String}
  4686. */
  4687. p.src = null;
  4688. /**
  4689. * The maximum number of instances in this channel. -1 indicates no limit
  4690. * #property max
  4691. * @type {Number}
  4692. */
  4693. p.max = null;
  4694. /**
  4695. * The default value to set for max, if it isn't passed in. Also used if -1 is passed.
  4696. * #property maxDefault
  4697. * @type {Number}
  4698. * @default 100
  4699. * @since 0.4.0
  4700. */
  4701. p.maxDefault = 100;
  4702. /**
  4703. * The current number of active instances.
  4704. * #property length
  4705. * @type {Number}
  4706. */
  4707. p.length = 0;
  4708. /**
  4709. * Initialize the channel.
  4710. * #method init
  4711. * @param {String} src The source of the channel
  4712. * @param {Number} max The maximum number of instances in the channel
  4713. * @protected
  4714. */
  4715. p.init = function (src, max) {
  4716. this.src = src;
  4717. this.max = max || this.maxDefault;
  4718. if (this.max == -1) {this.max = this.maxDefault;}
  4719. this._instances = [];
  4720. };
  4721. /**
  4722. * Get an instance by index.
  4723. * #method get
  4724. * @param {Number} index The index to return.
  4725. * @return {AbstractSoundInstance} The AbstractSoundInstance at a specific instance.
  4726. */
  4727. p._get = function (index) {
  4728. return this._instances[index];
  4729. };
  4730. /**
  4731. * Add a new instance to the channel.
  4732. * #method add
  4733. * @param {AbstractSoundInstance} instance The instance to add.
  4734. * @return {Boolean} The success of the method call. If the channel is full, it will return false.
  4735. */
  4736. p._add = function (instance, interrupt) {
  4737. if (!this._getSlot(interrupt, instance)) {return false;}
  4738. this._instances.push(instance);
  4739. this.length++;
  4740. return true;
  4741. };
  4742. /**
  4743. * Remove an instance from the channel, either when it has finished playing, or it has been interrupted.
  4744. * #method remove
  4745. * @param {AbstractSoundInstance} instance The instance to remove
  4746. * @return {Boolean} The success of the remove call. If the instance is not found in this channel, it will
  4747. * return false.
  4748. */
  4749. p._remove = function (instance) {
  4750. var index = createjs.indexOf(this._instances, instance);
  4751. if (index == -1) {return false;}
  4752. this._instances.splice(index, 1);
  4753. this.length--;
  4754. return true;
  4755. };
  4756. /**
  4757. * Stop playback and remove all instances from the channel. Usually in response to a delete call.
  4758. * #method removeAll
  4759. */
  4760. p._removeAll = function () {
  4761. // Note that stop() removes the item from the list
  4762. for (var i=this.length-1; i>=0; i--) {
  4763. this._instances[i].stop();
  4764. }
  4765. };
  4766. /**
  4767. * Get an available slot depending on interrupt value and if slots are available.
  4768. * #method getSlot
  4769. * @param {String} interrupt The interrupt value to use.
  4770. * @param {AbstractSoundInstance} instance The sound instance that will go in the channel if successful.
  4771. * @return {Boolean} Determines if there is an available slot. Depending on the interrupt mode, if there are no slots,
  4772. * an existing AbstractSoundInstance may be interrupted. If there are no slots, this method returns false.
  4773. */
  4774. p._getSlot = function (interrupt, instance) {
  4775. var target, replacement;
  4776. if (interrupt != Sound.INTERRUPT_NONE) {
  4777. // First replacement candidate
  4778. replacement = this._get(0);
  4779. if (replacement == null) {
  4780. return true;
  4781. }
  4782. }
  4783. for (var i = 0, l = this.max; i < l; i++) {
  4784. target = this._get(i);
  4785. // Available Space
  4786. if (target == null) {
  4787. return true;
  4788. }
  4789. // Audio is complete or not playing
  4790. if (target.playState == Sound.PLAY_FINISHED ||
  4791. target.playState == Sound.PLAY_INTERRUPTED ||
  4792. target.playState == Sound.PLAY_FAILED) {
  4793. replacement = target;
  4794. break;
  4795. }
  4796. if (interrupt == Sound.INTERRUPT_NONE) {
  4797. continue;
  4798. }
  4799. // Audio is a better candidate than the current target, according to playhead
  4800. if ((interrupt == Sound.INTERRUPT_EARLY && target.position < replacement.position) ||
  4801. (interrupt == Sound.INTERRUPT_LATE && target.position > replacement.position)) {
  4802. replacement = target;
  4803. }
  4804. }
  4805. if (replacement != null) {
  4806. replacement._interrupt();
  4807. this._remove(replacement);
  4808. return true;
  4809. }
  4810. return false;
  4811. };
  4812. p.toString = function () {
  4813. return "[Sound SoundChannel]";
  4814. };
  4815. // do not add SoundChannel to namespace
  4816. }());
  4817. //##############################################################################
  4818. // AbstractSoundInstance.js
  4819. //##############################################################################
  4820. /**
  4821. * A AbstractSoundInstance is created when any calls to the Sound API method {{#crossLink "Sound/play"}}{{/crossLink}} or
  4822. * {{#crossLink "Sound/createInstance"}}{{/crossLink}} are made. The AbstractSoundInstance is returned by the active plugin
  4823. * for control by the user.
  4824. *
  4825. * <h4>Example</h4>
  4826. *
  4827. * var myInstance = createjs.Sound.play("myAssetPath/mySrcFile.mp3");
  4828. *
  4829. * A number of additional parameters provide a quick way to determine how a sound is played. Please see the Sound
  4830. * API method {{#crossLink "Sound/play"}}{{/crossLink}} for a list of arguments.
  4831. *
  4832. * Once a AbstractSoundInstance is created, a reference can be stored that can be used to control the audio directly through
  4833. * the AbstractSoundInstance. If the reference is not stored, the AbstractSoundInstance will play out its audio (and any loops), and
  4834. * is then de-referenced from the {{#crossLink "Sound"}}{{/crossLink}} class so that it can be cleaned up. If audio
  4835. * playback has completed, a simple call to the {{#crossLink "AbstractSoundInstance/play"}}{{/crossLink}} instance method
  4836. * will rebuild the references the Sound class need to control it.
  4837. *
  4838. * var myInstance = createjs.Sound.play("myAssetPath/mySrcFile.mp3", {loop:2});
  4839. * myInstance.on("loop", handleLoop);
  4840. * function handleLoop(event) {
  4841. * myInstance.volume = myInstance.volume * 0.5;
  4842. * }
  4843. *
  4844. * Events are dispatched from the instance to notify when the sound has completed, looped, or when playback fails
  4845. *
  4846. * var myInstance = createjs.Sound.play("myAssetPath/mySrcFile.mp3");
  4847. * myInstance.on("complete", handleComplete);
  4848. * myInstance.on("loop", handleLoop);
  4849. * myInstance.on("failed", handleFailed);
  4850. *
  4851. *
  4852. * @class AbstractSoundInstance
  4853. * @param {String} src The path to and file name of the sound.
  4854. * @param {Number} startTime Audio sprite property used to apply an offset, in milliseconds.
  4855. * @param {Number} duration Audio sprite property used to set the time the clip plays for, in milliseconds.
  4856. * @param {Object} playbackResource Any resource needed by plugin to support audio playback.
  4857. * @extends EventDispatcher
  4858. * @constructor
  4859. */
  4860. (function () {
  4861. "use strict";
  4862. // Constructor:
  4863. var AbstractSoundInstance = function (src, startTime, duration, playbackResource) {
  4864. this.EventDispatcher_constructor();
  4865. // public properties:
  4866. /**
  4867. * The source of the sound.
  4868. * @property src
  4869. * @type {String}
  4870. * @default null
  4871. */
  4872. this.src = src;
  4873. /**
  4874. * The unique ID of the instance. This is set by {{#crossLink "Sound"}}{{/crossLink}}.
  4875. * @property uniqueId
  4876. * @type {String} | Number
  4877. * @default -1
  4878. */
  4879. this.uniqueId = -1;
  4880. /**
  4881. * The play state of the sound. Play states are defined as constants on {{#crossLink "Sound"}}{{/crossLink}}.
  4882. * @property playState
  4883. * @type {String}
  4884. * @default null
  4885. */
  4886. this.playState = null;
  4887. /**
  4888. * A Timeout created by {{#crossLink "Sound"}}{{/crossLink}} when this AbstractSoundInstance is played with a delay.
  4889. * This allows AbstractSoundInstance to remove the delay if stop, pause, or cleanup are called before playback begins.
  4890. * @property delayTimeoutId
  4891. * @type {timeoutVariable}
  4892. * @default null
  4893. * @protected
  4894. * @since 0.4.0
  4895. */
  4896. this.delayTimeoutId = null;
  4897. // TODO consider moving delay into AbstractSoundInstance so it can be handled by plugins
  4898. // private properties
  4899. // Getter / Setter Properties
  4900. // OJR TODO find original reason that we didn't use defined functions. I think it was performance related
  4901. /**
  4902. * The volume of the sound, between 0 and 1.
  4903. *
  4904. * The actual output volume of a sound can be calculated using:
  4905. * <code>myInstance.volume * createjs.Sound._getVolume();</code>
  4906. *
  4907. * @property volume
  4908. * @type {Number}
  4909. * @default 1
  4910. */
  4911. this._volume = 1;
  4912. Object.defineProperty(this, "volume", {
  4913. get: this._getVolume,
  4914. set: this._setVolume
  4915. });
  4916. this.getVolume = createjs.deprecate(this._getVolume, "AbstractSoundInstance.getVolume");
  4917. this.setVolume = createjs.deprecate(this._setVolume, "AbstractSoundInstance.setVolume");
  4918. /**
  4919. * The pan of the sound, between -1 (left) and 1 (right). Note that pan is not supported by HTML Audio.
  4920. *
  4921. * Note in WebAudioPlugin this only gives us the "x" value of what is actually 3D audio
  4922. * @property pan
  4923. * @type {Number}
  4924. * @default 0
  4925. */
  4926. this._pan = 0;
  4927. Object.defineProperty(this, "pan", {
  4928. get: this._getPan,
  4929. set: this._setPan
  4930. });
  4931. this.getPan = createjs.deprecate(this._getPan, "AbstractSoundInstance.getPan");
  4932. this.setPan = createjs.deprecate(this._setPan, "AbstractSoundInstance.setPan");
  4933. /**
  4934. * Audio sprite property used to determine the starting offset.
  4935. * @property startTime
  4936. * @type {Number}
  4937. * @default 0
  4938. * @since 0.6.1
  4939. */
  4940. this._startTime = Math.max(0, startTime || 0);
  4941. Object.defineProperty(this, "startTime", {
  4942. get: this._getStartTime,
  4943. set: this._setStartTime
  4944. });
  4945. this.getStartTime = createjs.deprecate(this._getStartTime, "AbstractSoundInstance.getStartTime");
  4946. this.setStartTime = createjs.deprecate(this._setStartTime, "AbstractSoundInstance.setStartTime");
  4947. /**
  4948. * Sets or gets the length of the audio clip, value is in milliseconds.
  4949. *
  4950. * @property duration
  4951. * @type {Number}
  4952. * @default 0
  4953. * @since 0.6.0
  4954. */
  4955. this._duration = Math.max(0, duration || 0);
  4956. Object.defineProperty(this, "duration", {
  4957. get: this._getDuration,
  4958. set: this._setDuration
  4959. });
  4960. this.getDuration = createjs.deprecate(this._getDuration, "AbstractSoundInstance.getDuration");
  4961. this.setDuration = createjs.deprecate(this._setDuration, "AbstractSoundInstance.setDuration");
  4962. /**
  4963. * Object that holds plugin specific resource need for audio playback.
  4964. * This is set internally by the plugin. For example, WebAudioPlugin will set an array buffer,
  4965. * HTMLAudioPlugin will set a tag, FlashAudioPlugin will set a flash reference.
  4966. *
  4967. * @property playbackResource
  4968. * @type {Object}
  4969. * @default null
  4970. */
  4971. this._playbackResource = null;
  4972. Object.defineProperty(this, "playbackResource", {
  4973. get: this._getPlaybackResource,
  4974. set: this._setPlaybackResource
  4975. });
  4976. if(playbackResource !== false && playbackResource !== true) { this._setPlaybackResource(playbackResource); }
  4977. this.getPlaybackResource = createjs.deprecate(this._getPlaybackResource, "AbstractSoundInstance.getPlaybackResource");
  4978. this.setPlaybackResource = createjs.deprecate(this._setPlaybackResource, "AbstractSoundInstance.setPlaybackResource");
  4979. /**
  4980. * The position of the playhead in milliseconds. This can be set while a sound is playing, paused, or stopped.
  4981. *
  4982. * @property position
  4983. * @type {Number}
  4984. * @default 0
  4985. * @since 0.6.0
  4986. */
  4987. this._position = 0;
  4988. Object.defineProperty(this, "position", {
  4989. get: this._getPosition,
  4990. set: this._setPosition
  4991. });
  4992. this.getPosition = createjs.deprecate(this._getPosition, "AbstractSoundInstance.getPosition");
  4993. this.setPosition = createjs.deprecate(this._setPosition, "AbstractSoundInstance.setPosition");
  4994. /**
  4995. * The number of play loops remaining. Negative values will loop infinitely.
  4996. *
  4997. * @property loop
  4998. * @type {Number}
  4999. * @default 0
  5000. * @public
  5001. * @since 0.6.0
  5002. */
  5003. this._loop = 0;
  5004. Object.defineProperty(this, "loop", {
  5005. get: this._getLoop,
  5006. set: this._setLoop
  5007. });
  5008. this.getLoop = createjs.deprecate(this._getLoop, "AbstractSoundInstance.getLoop");
  5009. this.setLoop = createjs.deprecate(this._setLoop, "AbstractSoundInstance.setLoop");
  5010. /**
  5011. * Mutes or unmutes the current audio instance.
  5012. *
  5013. * @property muted
  5014. * @type {Boolean}
  5015. * @default false
  5016. * @since 0.6.0
  5017. */
  5018. this._muted = false;
  5019. Object.defineProperty(this, "muted", {
  5020. get: this._getMuted,
  5021. set: this._setMuted
  5022. });
  5023. this.getMuted = createjs.deprecate(this._getMuted, "AbstractSoundInstance.getMuted");
  5024. this.setMuted = createjs.deprecate(this._setMuted, "AbstractSoundInstance.setMuted");
  5025. /**
  5026. * Pauses or resumes the current audio instance.
  5027. *
  5028. * @property paused
  5029. * @type {Boolean}
  5030. */
  5031. this._paused = false;
  5032. Object.defineProperty(this, "paused", {
  5033. get: this._getPaused,
  5034. set: this._setPaused
  5035. });
  5036. this.getPaused = createjs.deprecate(this._getPaused, "AbstractSoundInstance.getPaused");
  5037. this.setPaused = createjs.deprecate(this._setPaused, "AbstractSoundInstance.setPaused");
  5038. // Events
  5039. /**
  5040. * The event that is fired when playback has started successfully.
  5041. * @event succeeded
  5042. * @param {Object} target The object that dispatched the event.
  5043. * @param {String} type The event type.
  5044. * @since 0.4.0
  5045. */
  5046. /**
  5047. * The event that is fired when playback is interrupted. This happens when another sound with the same
  5048. * src property is played using an interrupt value that causes this instance to stop playing.
  5049. * @event interrupted
  5050. * @param {Object} target The object that dispatched the event.
  5051. * @param {String} type The event type.
  5052. * @since 0.4.0
  5053. */
  5054. /**
  5055. * The event that is fired when playback has failed. This happens when there are too many channels with the same
  5056. * src property already playing (and the interrupt value doesn't cause an interrupt of another instance), or
  5057. * the sound could not be played, perhaps due to a 404 error.
  5058. * @event failed
  5059. * @param {Object} target The object that dispatched the event.
  5060. * @param {String} type The event type.
  5061. * @since 0.4.0
  5062. */
  5063. /**
  5064. * The event that is fired when a sound has completed playing but has loops remaining.
  5065. * @event loop
  5066. * @param {Object} target The object that dispatched the event.
  5067. * @param {String} type The event type.
  5068. * @since 0.4.0
  5069. */
  5070. /**
  5071. * The event that is fired when playback completes. This means that the sound has finished playing in its
  5072. * entirety, including its loop iterations.
  5073. * @event complete
  5074. * @param {Object} target The object that dispatched the event.
  5075. * @param {String} type The event type.
  5076. * @since 0.4.0
  5077. */
  5078. };
  5079. var p = createjs.extend(AbstractSoundInstance, createjs.EventDispatcher);
  5080. // Public Methods:
  5081. /**
  5082. * Play an instance. This method is intended to be called on SoundInstances that already exist (created
  5083. * with the Sound API {{#crossLink "Sound/createInstance"}}{{/crossLink}} or {{#crossLink "Sound/play"}}{{/crossLink}}).
  5084. *
  5085. * <h4>Example</h4>
  5086. *
  5087. * var myInstance = createjs.Sound.createInstance(mySrc);
  5088. * myInstance.play({interrupt:createjs.Sound.INTERRUPT_ANY, loop:2, pan:0.5});
  5089. *
  5090. * Note that if this sound is already playing, this call will still set the passed in parameters.
  5091. * <b>Parameters Deprecated</b><br />
  5092. * The parameters for this method are deprecated in favor of a single parameter that is an Object or {{#crossLink "PlayPropsConfig"}}{{/crossLink}}.
  5093. *
  5094. * @method play
  5095. * @param {Object | PlayPropsConfig} props A PlayPropsConfig instance, or an object that contains the parameters to
  5096. * play a sound. See the {{#crossLink "PlayPropsConfig"}}{{/crossLink}} for more info.
  5097. * @return {AbstractSoundInstance} A reference to itself, intended for chaining calls.
  5098. */
  5099. p.play = function (props) {
  5100. var playProps = createjs.PlayPropsConfig.create(props);
  5101. if (this.playState == createjs.Sound.PLAY_SUCCEEDED) {
  5102. this.applyPlayProps(playProps);
  5103. if (this._paused) { this._setPaused(false); }
  5104. return;
  5105. }
  5106. this._cleanUp();
  5107. createjs.Sound._playInstance(this, playProps); // make this an event dispatch??
  5108. return this;
  5109. };
  5110. /**
  5111. * Stop playback of the instance. Stopped sounds will reset their position to 0, and calls to {{#crossLink "AbstractSoundInstance/resume"}}{{/crossLink}}
  5112. * will fail. To start playback again, call {{#crossLink "AbstractSoundInstance/play"}}{{/crossLink}}.
  5113. *
  5114. * If you don't want to lose your position use yourSoundInstance.paused = true instead. {{#crossLink "AbstractSoundInstance/paused"}}{{/crossLink}}.
  5115. *
  5116. * <h4>Example</h4>
  5117. *
  5118. * myInstance.stop();
  5119. *
  5120. * @method stop
  5121. * @return {AbstractSoundInstance} A reference to itself, intended for chaining calls.
  5122. */
  5123. p.stop = function () {
  5124. this._position = 0;
  5125. this._paused = false;
  5126. this._handleStop();
  5127. this._cleanUp();
  5128. this.playState = createjs.Sound.PLAY_FINISHED;
  5129. return this;
  5130. };
  5131. /**
  5132. * Remove all external references and resources from AbstractSoundInstance. Note this is irreversible and AbstractSoundInstance will no longer work
  5133. * @method destroy
  5134. * @since 0.6.0
  5135. */
  5136. p.destroy = function() {
  5137. this._cleanUp();
  5138. this.src = null;
  5139. this.playbackResource = null;
  5140. this.removeAllEventListeners();
  5141. };
  5142. /**
  5143. * Takes an PlayPropsConfig or Object with the same properties and sets them on this instance.
  5144. * @method applyPlayProps
  5145. * @param {PlayPropsConfig | Object} playProps A PlayPropsConfig or object containing the same properties.
  5146. * @since 0.6.1
  5147. * @return {AbstractSoundInstance} A reference to itself, intended for chaining calls.
  5148. */
  5149. p.applyPlayProps = function(playProps) {
  5150. if (playProps.offset != null) { this._setPosition(playProps.offset) }
  5151. if (playProps.loop != null) { this._setLoop(playProps.loop); }
  5152. if (playProps.volume != null) { this._setVolume(playProps.volume); }
  5153. if (playProps.pan != null) { this._setPan(playProps.pan); }
  5154. if (playProps.startTime != null) {
  5155. this._setStartTime(playProps.startTime);
  5156. this._setDuration(playProps.duration);
  5157. }
  5158. return this;
  5159. };
  5160. p.toString = function () {
  5161. return "[AbstractSoundInstance]";
  5162. };
  5163. // get/set methods that allow support for IE8
  5164. /**
  5165. * Please use {{#crossLink "AbstractSoundInstance/paused:property"}}{{/crossLink}} directly as a property.
  5166. * @method _getPaused
  5167. * @protected
  5168. * @return {boolean} If the instance is currently paused
  5169. * @since 0.6.0
  5170. */
  5171. p._getPaused = function() {
  5172. return this._paused;
  5173. };
  5174. /**
  5175. * Please use {{#crossLink "AbstractSoundInstance/paused:property"}}{{/crossLink}} directly as a property
  5176. * @method _setPaused
  5177. * @protected
  5178. * @param {boolean} value
  5179. * @since 0.6.0
  5180. * @return {AbstractSoundInstance} A reference to itself, intended for chaining calls.
  5181. */
  5182. p._setPaused = function (value) {
  5183. if ((value !== true && value !== false) || this._paused == value) {return;}
  5184. if (value == true && this.playState != createjs.Sound.PLAY_SUCCEEDED) {return;}
  5185. this._paused = value;
  5186. if(value) {
  5187. this._pause();
  5188. } else {
  5189. this._resume();
  5190. }
  5191. clearTimeout(this.delayTimeoutId);
  5192. return this;
  5193. };
  5194. /**
  5195. * Please use {{#crossLink "AbstractSoundInstance/volume:property"}}{{/crossLink}} directly as a property
  5196. * @method _setVolume
  5197. * @protected
  5198. * @param {Number} value The volume to set, between 0 and 1.
  5199. * @return {AbstractSoundInstance} A reference to itself, intended for chaining calls.
  5200. */
  5201. p._setVolume = function (value) {
  5202. if (value == this._volume) { return this; }
  5203. this._volume = Math.max(0, Math.min(1, value));
  5204. if (!this._muted) {
  5205. this._updateVolume();
  5206. }
  5207. return this;
  5208. };
  5209. /**
  5210. * Please use {{#crossLink "AbstractSoundInstance/volume:property"}}{{/crossLink}} directly as a property
  5211. * @method _getVolume
  5212. * @protected
  5213. * @return {Number} The current volume of the sound instance.
  5214. */
  5215. p._getVolume = function () {
  5216. return this._volume;
  5217. };
  5218. /**
  5219. * Please use {{#crossLink "AbstractSoundInstance/muted:property"}}{{/crossLink}} directly as a property
  5220. * @method _setMuted
  5221. * @protected
  5222. * @param {Boolean} value If the sound should be muted.
  5223. * @return {AbstractSoundInstance} A reference to itself, intended for chaining calls.
  5224. * @since 0.6.0
  5225. */
  5226. p._setMuted = function (value) {
  5227. if (value !== true && value !== false) {return;}
  5228. this._muted = value;
  5229. this._updateVolume();
  5230. return this;
  5231. };
  5232. /**
  5233. * Please use {{#crossLink "AbstractSoundInstance/muted:property"}}{{/crossLink}} directly as a property
  5234. * @method _getMuted
  5235. * @protected
  5236. * @return {Boolean} If the sound is muted.
  5237. * @since 0.6.0
  5238. */
  5239. p._getMuted = function () {
  5240. return this._muted;
  5241. };
  5242. /**
  5243. * Please use {{#crossLink "AbstractSoundInstance/pan:property"}}{{/crossLink}} directly as a property
  5244. * @method _setPan
  5245. * @protected
  5246. * @param {Number} value The pan value, between -1 (left) and 1 (right).
  5247. * @return {AbstractSoundInstance} Returns reference to itself for chaining calls
  5248. */
  5249. p._setPan = function (value) {
  5250. if(value == this._pan) { return this; }
  5251. this._pan = Math.max(-1, Math.min(1, value));
  5252. this._updatePan();
  5253. return this;
  5254. };
  5255. /**
  5256. * Please use {{#crossLink "AbstractSoundInstance/pan:property"}}{{/crossLink}} directly as a property
  5257. * @method _getPan
  5258. * @protected
  5259. * @return {Number} The value of the pan, between -1 (left) and 1 (right).
  5260. */
  5261. p._getPan = function () {
  5262. return this._pan;
  5263. };
  5264. /**
  5265. * Please use {{#crossLink "AbstractSoundInstance/position:property"}}{{/crossLink}} directly as a property
  5266. * @method _getPosition
  5267. * @protected
  5268. * @return {Number} The position of the playhead in the sound, in milliseconds.
  5269. */
  5270. p._getPosition = function () {
  5271. if (!this._paused && this.playState == createjs.Sound.PLAY_SUCCEEDED) {
  5272. this._position = this._calculateCurrentPosition();
  5273. }
  5274. return this._position;
  5275. };
  5276. /**
  5277. * Please use {{#crossLink "AbstractSoundInstance/position:property"}}{{/crossLink}} directly as a property
  5278. * @method _setPosition
  5279. * @protected
  5280. * @param {Number} value The position to place the playhead, in milliseconds.
  5281. * @return {AbstractSoundInstance} Returns reference to itself for chaining calls
  5282. */
  5283. p._setPosition = function (value) {
  5284. this._position = Math.max(0, value);
  5285. if (this.playState == createjs.Sound.PLAY_SUCCEEDED) {
  5286. this._updatePosition();
  5287. }
  5288. return this;
  5289. };
  5290. /**
  5291. * Please use {{#crossLink "AbstractSoundInstance/startTime:property"}}{{/crossLink}} directly as a property
  5292. * @method _getStartTime
  5293. * @protected
  5294. * @return {Number} The startTime of the sound instance in milliseconds.
  5295. */
  5296. p._getStartTime = function () {
  5297. return this._startTime;
  5298. };
  5299. /**
  5300. * Please use {{#crossLink "AbstractSoundInstance/startTime:property"}}{{/crossLink}} directly as a property
  5301. * @method _setStartTime
  5302. * @protected
  5303. * @param {number} value The new startTime time in milli seconds.
  5304. * @return {AbstractSoundInstance} Returns reference to itself for chaining calls
  5305. */
  5306. p._setStartTime = function (value) {
  5307. if (value == this._startTime) { return this; }
  5308. this._startTime = Math.max(0, value || 0);
  5309. this._updateStartTime();
  5310. return this;
  5311. };
  5312. /**
  5313. * Please use {{#crossLink "AbstractSoundInstance/duration:property"}}{{/crossLink}} directly as a property
  5314. * @method _getDuration
  5315. * @protected
  5316. * @return {Number} The duration of the sound instance in milliseconds.
  5317. */
  5318. p._getDuration = function () {
  5319. return this._duration;
  5320. };
  5321. /**
  5322. * Please use {{#crossLink "AbstractSoundInstance/duration:property"}}{{/crossLink}} directly as a property
  5323. * @method _setDuration
  5324. * @protected
  5325. * @param {number} value The new duration time in milli seconds.
  5326. * @return {AbstractSoundInstance} Returns reference to itself for chaining calls
  5327. * @since 0.6.0
  5328. */
  5329. p._setDuration = function (value) {
  5330. if (value == this._duration) { return this; }
  5331. this._duration = Math.max(0, value || 0);
  5332. this._updateDuration();
  5333. return this;
  5334. };
  5335. /**
  5336. * Please use {{#crossLink "AbstractSoundInstance/playbackResource:property"}}{{/crossLink}} directly as a property
  5337. * @method _setPlaybackResource
  5338. * @protected
  5339. * @param {Object} value The new playback resource.
  5340. * @return {AbstractSoundInstance} Returns reference to itself for chaining calls
  5341. * @since 0.6.0
  5342. **/
  5343. p._setPlaybackResource = function (value) {
  5344. this._playbackResource = value;
  5345. if (this._duration == 0 && this._playbackResource) { this._setDurationFromSource(); }
  5346. return this;
  5347. };
  5348. /**
  5349. * Please use {{#crossLink "AbstractSoundInstance/playbackResource:property"}}{{/crossLink}} directly as a property
  5350. * @method _getPlaybackResource
  5351. * @protected
  5352. * @param {Object} value The new playback resource.
  5353. * @return {Object} playback resource used for playing audio
  5354. * @since 0.6.0
  5355. **/
  5356. p._getPlaybackResource = function () {
  5357. return this._playbackResource;
  5358. };
  5359. /**
  5360. * Please use {{#crossLink "AbstractSoundInstance/loop:property"}}{{/crossLink}} directly as a property
  5361. * @method _getLoop
  5362. * @protected
  5363. * @return {number}
  5364. * @since 0.6.0
  5365. **/
  5366. p._getLoop = function () {
  5367. return this._loop;
  5368. };
  5369. /**
  5370. * Please use {{#crossLink "AbstractSoundInstance/loop:property"}}{{/crossLink}} directly as a property
  5371. * @method _setLoop
  5372. * @protected
  5373. * @param {number} value The number of times to loop after play.
  5374. * @since 0.6.0
  5375. */
  5376. p._setLoop = function (value) {
  5377. if(this._playbackResource != null) {
  5378. // remove looping
  5379. if (this._loop != 0 && value == 0) {
  5380. this._removeLooping(value);
  5381. }
  5382. // add looping
  5383. else if (this._loop == 0 && value != 0) {
  5384. this._addLooping(value);
  5385. }
  5386. }
  5387. this._loop = value;
  5388. };
  5389. // Private Methods:
  5390. /**
  5391. * A helper method that dispatches all events for AbstractSoundInstance.
  5392. * @method _sendEvent
  5393. * @param {String} type The event type
  5394. * @protected
  5395. */
  5396. p._sendEvent = function (type) {
  5397. var event = new createjs.Event(type);
  5398. this.dispatchEvent(event);
  5399. };
  5400. /**
  5401. * Clean up the instance. Remove references and clean up any additional properties such as timers.
  5402. * @method _cleanUp
  5403. * @protected
  5404. */
  5405. p._cleanUp = function () {
  5406. clearTimeout(this.delayTimeoutId); // clear timeout that plays delayed sound
  5407. this._handleCleanUp();
  5408. this._paused = false;
  5409. createjs.Sound._playFinished(this); // TODO change to an event
  5410. };
  5411. /**
  5412. * The sound has been interrupted.
  5413. * @method _interrupt
  5414. * @protected
  5415. */
  5416. p._interrupt = function () {
  5417. this._cleanUp();
  5418. this.playState = createjs.Sound.PLAY_INTERRUPTED;
  5419. this._sendEvent("interrupted");
  5420. };
  5421. /**
  5422. * Called by the Sound class when the audio is ready to play (delay has completed). Starts sound playing if the
  5423. * src is loaded, otherwise playback will fail.
  5424. * @method _beginPlaying
  5425. * @param {PlayPropsConfig} playProps A PlayPropsConfig object.
  5426. * @return {Boolean} If playback succeeded.
  5427. * @protected
  5428. */
  5429. // OJR FlashAudioSoundInstance overwrites
  5430. p._beginPlaying = function (playProps) {
  5431. this._setPosition(playProps.offset);
  5432. this._setLoop(playProps.loop);
  5433. this._setVolume(playProps.volume);
  5434. this._setPan(playProps.pan);
  5435. if (playProps.startTime != null) {
  5436. this._setStartTime(playProps.startTime);
  5437. this._setDuration(playProps.duration);
  5438. }
  5439. if (this._playbackResource != null && this._position < this._duration) {
  5440. this._paused = false;
  5441. this._handleSoundReady();
  5442. this.playState = createjs.Sound.PLAY_SUCCEEDED;
  5443. this._sendEvent("succeeded");
  5444. return true;
  5445. } else {
  5446. this._playFailed();
  5447. return false;
  5448. }
  5449. };
  5450. /**
  5451. * Play has failed, which can happen for a variety of reasons.
  5452. * Cleans up instance and dispatches failed event
  5453. * @method _playFailed
  5454. * @private
  5455. */
  5456. p._playFailed = function () {
  5457. this._cleanUp();
  5458. this.playState = createjs.Sound.PLAY_FAILED;
  5459. this._sendEvent("failed");
  5460. };
  5461. /**
  5462. * Audio has finished playing. Manually loop it if required.
  5463. * @method _handleSoundComplete
  5464. * @param event
  5465. * @protected
  5466. */
  5467. p._handleSoundComplete = function (event) {
  5468. this._position = 0; // have to set this as it can be set by pause during playback
  5469. if (this._loop != 0) {
  5470. this._loop--; // NOTE this introduces a theoretical limit on loops = float max size x 2 - 1
  5471. this._handleLoop();
  5472. this._sendEvent("loop");
  5473. return;
  5474. }
  5475. this._cleanUp();
  5476. this.playState = createjs.Sound.PLAY_FINISHED;
  5477. this._sendEvent("complete");
  5478. };
  5479. // Plugin specific code
  5480. /**
  5481. * Handles starting playback when the sound is ready for playing.
  5482. * @method _handleSoundReady
  5483. * @protected
  5484. */
  5485. p._handleSoundReady = function () {
  5486. // plugin specific code
  5487. };
  5488. /**
  5489. * Internal function used to update the volume based on the instance volume, master volume, instance mute value,
  5490. * and master mute value.
  5491. * @method _updateVolume
  5492. * @protected
  5493. */
  5494. p._updateVolume = function () {
  5495. // plugin specific code
  5496. };
  5497. /**
  5498. * Internal function used to update the pan
  5499. * @method _updatePan
  5500. * @protected
  5501. * @since 0.6.0
  5502. */
  5503. p._updatePan = function () {
  5504. // plugin specific code
  5505. };
  5506. /**
  5507. * Internal function used to update the startTime of the audio.
  5508. * @method _updateStartTime
  5509. * @protected
  5510. * @since 0.6.1
  5511. */
  5512. p._updateStartTime = function () {
  5513. // plugin specific code
  5514. };
  5515. /**
  5516. * Internal function used to update the duration of the audio.
  5517. * @method _updateDuration
  5518. * @protected
  5519. * @since 0.6.0
  5520. */
  5521. p._updateDuration = function () {
  5522. // plugin specific code
  5523. };
  5524. /**
  5525. * Internal function used to get the duration of the audio from the source we'll be playing.
  5526. * @method _updateDuration
  5527. * @protected
  5528. * @since 0.6.0
  5529. */
  5530. p._setDurationFromSource = function () {
  5531. // plugin specific code
  5532. };
  5533. /**
  5534. * Internal function that calculates the current position of the playhead and sets this._position to that value
  5535. * @method _calculateCurrentPosition
  5536. * @protected
  5537. * @since 0.6.0
  5538. */
  5539. p._calculateCurrentPosition = function () {
  5540. // plugin specific code that sets this.position
  5541. };
  5542. /**
  5543. * Internal function used to update the position of the playhead.
  5544. * @method _updatePosition
  5545. * @protected
  5546. * @since 0.6.0
  5547. */
  5548. p._updatePosition = function () {
  5549. // plugin specific code
  5550. };
  5551. /**
  5552. * Internal function called when looping is removed during playback.
  5553. * @method _removeLooping
  5554. * @param {number} value The number of times to loop after play.
  5555. * @protected
  5556. * @since 0.6.0
  5557. */
  5558. p._removeLooping = function (value) {
  5559. // plugin specific code
  5560. };
  5561. /**
  5562. * Internal function called when looping is added during playback.
  5563. * @method _addLooping
  5564. * @param {number} value The number of times to loop after play.
  5565. * @protected
  5566. * @since 0.6.0
  5567. */
  5568. p._addLooping = function (value) {
  5569. // plugin specific code
  5570. };
  5571. /**
  5572. * Internal function called when pausing playback
  5573. * @method _pause
  5574. * @protected
  5575. * @since 0.6.0
  5576. */
  5577. p._pause = function () {
  5578. // plugin specific code
  5579. };
  5580. /**
  5581. * Internal function called when resuming playback
  5582. * @method _resume
  5583. * @protected
  5584. * @since 0.6.0
  5585. */
  5586. p._resume = function () {
  5587. // plugin specific code
  5588. };
  5589. /**
  5590. * Internal function called when stopping playback
  5591. * @method _handleStop
  5592. * @protected
  5593. * @since 0.6.0
  5594. */
  5595. p._handleStop = function() {
  5596. // plugin specific code
  5597. };
  5598. /**
  5599. * Internal function called when AbstractSoundInstance is being cleaned up
  5600. * @method _handleCleanUp
  5601. * @protected
  5602. * @since 0.6.0
  5603. */
  5604. p._handleCleanUp = function() {
  5605. // plugin specific code
  5606. };
  5607. /**
  5608. * Internal function called when AbstractSoundInstance has played to end and is looping
  5609. * @method _handleLoop
  5610. * @protected
  5611. * @since 0.6.0
  5612. */
  5613. p._handleLoop = function () {
  5614. // plugin specific code
  5615. };
  5616. createjs.AbstractSoundInstance = createjs.promote(AbstractSoundInstance, "EventDispatcher");
  5617. createjs.DefaultSoundInstance = createjs.AbstractSoundInstance; // used when no plugin is supported
  5618. }());
  5619. //##############################################################################
  5620. // AbstractPlugin.js
  5621. //##############################################################################
  5622. (function () {
  5623. "use strict";
  5624. // constructor:
  5625. /**
  5626. * A default plugin class used as a base for all other plugins.
  5627. * @class AbstractPlugin
  5628. * @constructor
  5629. * @since 0.6.0
  5630. */
  5631. var AbstractPlugin = function () {
  5632. // private properties:
  5633. /**
  5634. * The capabilities of the plugin.
  5635. * method and is used internally.
  5636. * @property _capabilities
  5637. * @type {Object}
  5638. * @default null
  5639. * @protected
  5640. * @static
  5641. */
  5642. this._capabilities = null;
  5643. /**
  5644. * Object hash indexed by the source URI of all created loaders, used to properly destroy them if sources are removed.
  5645. * @type {Object}
  5646. * @protected
  5647. */
  5648. this._loaders = {};
  5649. /**
  5650. * Object hash indexed by the source URI of each file to indicate if an audio source has begun loading,
  5651. * is currently loading, or has completed loading. Can be used to store non boolean data after loading
  5652. * is complete (for example arrayBuffers for web audio).
  5653. * @property _audioSources
  5654. * @type {Object}
  5655. * @protected
  5656. */
  5657. this._audioSources = {};
  5658. /**
  5659. * Object hash indexed by the source URI of all created SoundInstances, updates the playbackResource if it loads after they are created,
  5660. * and properly destroy them if sources are removed
  5661. * @type {Object}
  5662. * @protected
  5663. */
  5664. this._soundInstances = {};
  5665. /**
  5666. * The internal master volume value of the plugin.
  5667. * @property _volume
  5668. * @type {Number}
  5669. * @default 1
  5670. * @protected
  5671. */
  5672. this._volume = 1;
  5673. /**
  5674. * A reference to a loader class used by a plugin that must be set.
  5675. * @type {Object}
  5676. * @protected
  5677. */
  5678. this._loaderClass;
  5679. /**
  5680. * A reference to an AbstractSoundInstance class used by a plugin that must be set.
  5681. * @type {Object}
  5682. * @protected;
  5683. */
  5684. this._soundInstanceClass;
  5685. };
  5686. var p = AbstractPlugin.prototype;
  5687. // Static Properties:
  5688. // NOTE THESE PROPERTIES NEED TO BE ADDED TO EACH PLUGIN
  5689. /**
  5690. * The capabilities of the plugin. This is generated via the _generateCapabilities method and is used internally.
  5691. * @property _capabilities
  5692. * @type {Object}
  5693. * @default null
  5694. * @private
  5695. * @static
  5696. */
  5697. AbstractPlugin._capabilities = null;
  5698. /**
  5699. * Determine if the plugin can be used in the current browser/OS.
  5700. * @method isSupported
  5701. * @return {Boolean} If the plugin can be initialized.
  5702. * @static
  5703. */
  5704. AbstractPlugin.isSupported = function () {
  5705. return true;
  5706. };
  5707. // public methods:
  5708. /**
  5709. * Pre-register a sound for preloading and setup. This is called by {{#crossLink "Sound"}}{{/crossLink}}.
  5710. * Note all plugins provide a <code>Loader</code> instance, which <a href="http://preloadjs.com" target="_blank">PreloadJS</a>
  5711. * can use to assist with preloading.
  5712. * @method register
  5713. * @param {String} loadItem An Object containing the source of the audio
  5714. * Note that not every plugin will manage this value.
  5715. * @return {Object} A result object, containing a "tag" for preloading purposes.
  5716. */
  5717. p.register = function (loadItem) {
  5718. var loader = this._loaders[loadItem.src];
  5719. if(loader && !loader.canceled) {return this._loaders[loadItem.src];} // already loading/loaded this, so don't load twice
  5720. // OJR potential issue that we won't be firing loaded event, might need to trigger if this is already loaded?
  5721. this._audioSources[loadItem.src] = true;
  5722. this._soundInstances[loadItem.src] = [];
  5723. loader = new this._loaderClass(loadItem);
  5724. loader.on("complete", this._handlePreloadComplete, this);
  5725. this._loaders[loadItem.src] = loader;
  5726. return loader;
  5727. };
  5728. // note sound calls register before calling preload
  5729. /**
  5730. * Internally preload a sound.
  5731. * @method preload
  5732. * @param {Loader} loader The sound URI to load.
  5733. */
  5734. p.preload = function (loader) {
  5735. loader.on("error", this._handlePreloadError, this);
  5736. loader.load();
  5737. };
  5738. /**
  5739. * Checks if preloading has started for a specific source. If the source is found, we can assume it is loading,
  5740. * or has already finished loading.
  5741. * @method isPreloadStarted
  5742. * @param {String} src The sound URI to check.
  5743. * @return {Boolean}
  5744. */
  5745. p.isPreloadStarted = function (src) {
  5746. return (this._audioSources[src] != null);
  5747. };
  5748. /**
  5749. * Checks if preloading has finished for a specific source.
  5750. * @method isPreloadComplete
  5751. * @param {String} src The sound URI to load.
  5752. * @return {Boolean}
  5753. */
  5754. p.isPreloadComplete = function (src) {
  5755. return (!(this._audioSources[src] == null || this._audioSources[src] == true));
  5756. };
  5757. /**
  5758. * Remove a sound added using {{#crossLink "WebAudioPlugin/register"}}{{/crossLink}}. Note this does not cancel a preload.
  5759. * @method removeSound
  5760. * @param {String} src The sound URI to unload.
  5761. */
  5762. p.removeSound = function (src) {
  5763. if (!this._soundInstances[src]) { return; }
  5764. for (var i = this._soundInstances[src].length; i--; ) {
  5765. var item = this._soundInstances[src][i];
  5766. item.destroy();
  5767. }
  5768. delete(this._soundInstances[src]);
  5769. delete(this._audioSources[src]);
  5770. if(this._loaders[src]) { this._loaders[src].destroy(); }
  5771. delete(this._loaders[src]);
  5772. };
  5773. /**
  5774. * Remove all sounds added using {{#crossLink "WebAudioPlugin/register"}}{{/crossLink}}. Note this does not cancel a preload.
  5775. * @method removeAllSounds
  5776. * @param {String} src The sound URI to unload.
  5777. */
  5778. p.removeAllSounds = function () {
  5779. for(var key in this._audioSources) {
  5780. this.removeSound(key);
  5781. }
  5782. };
  5783. /**
  5784. * Create a sound instance. If the sound has not been preloaded, it is internally preloaded here.
  5785. * @method create
  5786. * @param {String} src The sound source to use.
  5787. * @param {Number} startTime Audio sprite property used to apply an offset, in milliseconds.
  5788. * @param {Number} duration Audio sprite property used to set the time the clip plays for, in milliseconds.
  5789. * @return {AbstractSoundInstance} A sound instance for playback and control.
  5790. */
  5791. p.create = function (src, startTime, duration) {
  5792. if (!this.isPreloadStarted(src)) {
  5793. this.preload(this.register(src));
  5794. }
  5795. var si = new this._soundInstanceClass(src, startTime, duration, this._audioSources[src]);
  5796. if(this._soundInstances[src]){
  5797. this._soundInstances[src].push(si);
  5798. }
  5799. // Plugins that don't have a setVolume should implement a setMasterVolune/setMasterMute
  5800. // So we have to check that here.
  5801. si.setMasterVolume && si.setMasterVolume(createjs.Sound.volume);
  5802. si.setMasterMute && si.setMasterMute(createjs.Sound.muted);
  5803. return si;
  5804. };
  5805. // if a plugin does not support volume and mute, it should set these to null
  5806. /**
  5807. * Set the master volume of the plugin, which affects all SoundInstances.
  5808. * @method setVolume
  5809. * @param {Number} value The volume to set, between 0 and 1.
  5810. * @return {Boolean} If the plugin processes the setVolume call (true). The Sound class will affect all the
  5811. * instances manually otherwise.
  5812. */
  5813. p.setVolume = function (value) {
  5814. this._volume = value;
  5815. this._updateVolume();
  5816. return true;
  5817. };
  5818. /**
  5819. * Get the master volume of the plugin, which affects all SoundInstances.
  5820. * @method getVolume
  5821. * @return {Number} The volume level, between 0 and 1.
  5822. */
  5823. p.getVolume = function () {
  5824. return this._volume;
  5825. };
  5826. /**
  5827. * Mute all sounds via the plugin.
  5828. * @method setMute
  5829. * @param {Boolean} value If all sound should be muted or not. Note that plugin-level muting just looks up
  5830. * the mute value of Sound {{#crossLink "Sound/muted:property"}}{{/crossLink}}, so this property is not used here.
  5831. * @return {Boolean} If the mute call succeeds.
  5832. */
  5833. p.setMute = function (value) {
  5834. this._updateVolume();
  5835. return true;
  5836. };
  5837. // plugins should overwrite this method
  5838. p.toString = function () {
  5839. return "[AbstractPlugin]";
  5840. };
  5841. // private methods:
  5842. /**
  5843. * Handles internal preload completion.
  5844. * @method _handlePreloadComplete
  5845. * @param event
  5846. * @protected
  5847. */
  5848. p._handlePreloadComplete = function (event) {
  5849. var src = event.target.getItem().src;
  5850. this._audioSources[src] = event.result;
  5851. for (var i = 0, l = this._soundInstances[src].length; i < l; i++) {
  5852. var item = this._soundInstances[src][i];
  5853. item.playbackResource = this._audioSources[src];
  5854. // ToDo consider adding play call here if playstate == playfailed
  5855. this._soundInstances[src] = null;
  5856. }
  5857. };
  5858. /**
  5859. * Handles internal preload errors
  5860. * @method _handlePreloadError
  5861. * @param event
  5862. * @protected
  5863. */
  5864. p._handlePreloadError = function(event) {
  5865. //delete(this._audioSources[src]);
  5866. };
  5867. /**
  5868. * Set the gain value for master audio. Should not be called externally.
  5869. * @method _updateVolume
  5870. * @protected
  5871. */
  5872. p._updateVolume = function () {
  5873. // Plugin Specific code
  5874. };
  5875. createjs.AbstractPlugin = AbstractPlugin;
  5876. }());
  5877. //##############################################################################
  5878. // WebAudioLoader.js
  5879. //##############################################################################
  5880. (function () {
  5881. "use strict";
  5882. /**
  5883. * Loader provides a mechanism to preload Web Audio content via PreloadJS or internally. Instances are returned to
  5884. * the preloader, and the load method is called when the asset needs to be requested.
  5885. *
  5886. * @class WebAudioLoader
  5887. * @param {String} loadItem The item to be loaded
  5888. * @extends XHRRequest
  5889. * @protected
  5890. */
  5891. function Loader(loadItem) {
  5892. this.AbstractLoader_constructor(loadItem, true, createjs.Types.SOUND);
  5893. };
  5894. var p = createjs.extend(Loader, createjs.AbstractLoader);
  5895. /**
  5896. * web audio context required for decoding audio
  5897. * @property context
  5898. * @type {AudioContext}
  5899. * @static
  5900. */
  5901. Loader.context = null;
  5902. // public methods
  5903. p.toString = function () {
  5904. return "[WebAudioLoader]";
  5905. };
  5906. // private methods
  5907. p._createRequest = function() {
  5908. this._request = new createjs.XHRRequest(this._item, false);
  5909. this._request.setResponseType("arraybuffer");
  5910. };
  5911. p._sendComplete = function (event) {
  5912. // OJR we leave this wrapped in Loader because we need to reference src and the handler only receives a single argument, the decodedAudio
  5913. Loader.context.decodeAudioData(this._rawResult,
  5914. createjs.proxy(this._handleAudioDecoded, this),
  5915. createjs.proxy(this._sendError, this));
  5916. };
  5917. /**
  5918. * The audio has been decoded.
  5919. * @method handleAudioDecoded
  5920. * @param decoded
  5921. * @protected
  5922. */
  5923. p._handleAudioDecoded = function (decodedAudio) {
  5924. this._result = decodedAudio;
  5925. this.AbstractLoader__sendComplete();
  5926. };
  5927. createjs.WebAudioLoader = createjs.promote(Loader, "AbstractLoader");
  5928. }());
  5929. //##############################################################################
  5930. // WebAudioSoundInstance.js
  5931. //##############################################################################
  5932. /**
  5933. * WebAudioSoundInstance extends the base api of {{#crossLink "AbstractSoundInstance"}}{{/crossLink}} and is used by
  5934. * {{#crossLink "WebAudioPlugin"}}{{/crossLink}}.
  5935. *
  5936. * WebAudioSoundInstance exposes audioNodes for advanced users.
  5937. *
  5938. * @param {String} src The path to and file name of the sound.
  5939. * @param {Number} startTime Audio sprite property used to apply an offset, in milliseconds.
  5940. * @param {Number} duration Audio sprite property used to set the time the clip plays for, in milliseconds.
  5941. * @param {Object} playbackResource Any resource needed by plugin to support audio playback.
  5942. * @class WebAudioSoundInstance
  5943. * @extends AbstractSoundInstance
  5944. * @constructor
  5945. */
  5946. (function () {
  5947. "use strict";
  5948. function WebAudioSoundInstance(src, startTime, duration, playbackResource) {
  5949. this.AbstractSoundInstance_constructor(src, startTime, duration, playbackResource);
  5950. // public properties
  5951. /**
  5952. * NOTE this is only intended for use by advanced users.
  5953. * <br />GainNode for controlling <code>WebAudioSoundInstance</code> volume. Connected to the {{#crossLink "WebAudioSoundInstance/destinationNode:property"}}{{/crossLink}}.
  5954. * @property gainNode
  5955. * @type {AudioGainNode}
  5956. * @since 0.4.0
  5957. *
  5958. */
  5959. this.gainNode = s.context.createGain();
  5960. /**
  5961. * NOTE this is only intended for use by advanced users.
  5962. * <br />A panNode allowing left and right audio channel panning only. Connected to WebAudioSoundInstance {{#crossLink "WebAudioSoundInstance/gainNode:property"}}{{/crossLink}}.
  5963. * @property panNode
  5964. * @type {AudioPannerNode}
  5965. * @since 0.4.0
  5966. */
  5967. this.panNode = s.context.createPanner();
  5968. this.panNode.panningModel = s._panningModel;
  5969. this.panNode.connect(this.gainNode);
  5970. this._updatePan();
  5971. /**
  5972. * NOTE this is only intended for use by advanced users.
  5973. * <br />sourceNode is the audio source. Connected to WebAudioSoundInstance {{#crossLink "WebAudioSoundInstance/panNode:property"}}{{/crossLink}}.
  5974. * @property sourceNode
  5975. * @type {AudioNode}
  5976. * @since 0.4.0
  5977. *
  5978. */
  5979. this.sourceNode = null;
  5980. // private properties
  5981. /**
  5982. * Timeout that is created internally to handle sound playing to completion.
  5983. * Stored so we can remove it when stop, pause, or cleanup are called
  5984. * @property _soundCompleteTimeout
  5985. * @type {timeoutVariable}
  5986. * @default null
  5987. * @protected
  5988. * @since 0.4.0
  5989. */
  5990. this._soundCompleteTimeout = null;
  5991. /**
  5992. * NOTE this is only intended for use by very advanced users.
  5993. * _sourceNodeNext is the audio source for the next loop, inserted in a look ahead approach to allow for smooth
  5994. * looping. Connected to {{#crossLink "WebAudioSoundInstance/gainNode:property"}}{{/crossLink}}.
  5995. * @property _sourceNodeNext
  5996. * @type {AudioNode}
  5997. * @default null
  5998. * @protected
  5999. * @since 0.4.1
  6000. *
  6001. */
  6002. this._sourceNodeNext = null;
  6003. /**
  6004. * Time audio started playback, in seconds. Used to handle set position, get position, and resuming from paused.
  6005. * @property _playbackStartTime
  6006. * @type {Number}
  6007. * @default 0
  6008. * @protected
  6009. * @since 0.4.0
  6010. */
  6011. this._playbackStartTime = 0;
  6012. // Proxies, make removing listeners easier.
  6013. this._endedHandler = createjs.proxy(this._handleSoundComplete, this);
  6014. };
  6015. var p = createjs.extend(WebAudioSoundInstance, createjs.AbstractSoundInstance);
  6016. var s = WebAudioSoundInstance;
  6017. /**
  6018. * Note this is only intended for use by advanced users.
  6019. * <br />Audio context used to create nodes. This is and needs to be the same context used by {{#crossLink "WebAudioPlugin"}}{{/crossLink}}.
  6020. * @property context
  6021. * @type {AudioContext}
  6022. * @static
  6023. * @since 0.6.0
  6024. */
  6025. s.context = null;
  6026. /**
  6027. * Note this is only intended for use by advanced users.
  6028. * <br />The scratch buffer that will be assigned to the buffer property of a source node on close.
  6029. * This is and should be the same scratch buffer referenced by {{#crossLink "WebAudioPlugin"}}{{/crossLink}}.
  6030. * @property _scratchBuffer
  6031. * @type {AudioBufferSourceNode}
  6032. * @static
  6033. */
  6034. s._scratchBuffer = null;
  6035. /**
  6036. * Note this is only intended for use by advanced users.
  6037. * <br /> Audio node from WebAudioPlugin that sequences to <code>context.destination</code>
  6038. * @property destinationNode
  6039. * @type {AudioNode}
  6040. * @static
  6041. * @since 0.6.0
  6042. */
  6043. s.destinationNode = null;
  6044. /**
  6045. * Value to set panning model to equal power for WebAudioSoundInstance. Can be "equalpower" or 0 depending on browser implementation.
  6046. * @property _panningModel
  6047. * @type {Number / String}
  6048. * @protected
  6049. * @static
  6050. * @since 0.6.0
  6051. */
  6052. s._panningModel = "equalpower";
  6053. // Public methods
  6054. p.destroy = function() {
  6055. this.AbstractSoundInstance_destroy();
  6056. this.panNode.disconnect(0);
  6057. this.panNode = null;
  6058. this.gainNode.disconnect(0);
  6059. this.gainNode = null;
  6060. };
  6061. p.toString = function () {
  6062. return "[WebAudioSoundInstance]";
  6063. };
  6064. // Private Methods
  6065. p._updatePan = function() {
  6066. this.panNode.setPosition(this._pan, 0, -0.5);
  6067. // z need to be -0.5 otherwise the sound only plays in left, right, or center
  6068. };
  6069. p._removeLooping = function(value) {
  6070. this._sourceNodeNext = this._cleanUpAudioNode(this._sourceNodeNext);
  6071. };
  6072. p._addLooping = function(value) {
  6073. if (this.playState != createjs.Sound.PLAY_SUCCEEDED) { return; }
  6074. this._sourceNodeNext = this._createAndPlayAudioNode(this._playbackStartTime, 0);
  6075. };
  6076. p._setDurationFromSource = function () {
  6077. this._duration = this.playbackResource.duration * 1000;
  6078. };
  6079. p._handleCleanUp = function () {
  6080. if (this.sourceNode && this.playState == createjs.Sound.PLAY_SUCCEEDED) {
  6081. this.sourceNode = this._cleanUpAudioNode(this.sourceNode);
  6082. this._sourceNodeNext = this._cleanUpAudioNode(this._sourceNodeNext);
  6083. }
  6084. if (this.gainNode.numberOfOutputs != 0) {this.gainNode.disconnect(0);}
  6085. // OJR there appears to be a bug that this doesn't always work in webkit (Chrome and Safari). According to the documentation, this should work.
  6086. clearTimeout(this._soundCompleteTimeout);
  6087. this._playbackStartTime = 0; // This is used by _getPosition
  6088. };
  6089. /**
  6090. * Turn off and disconnect an audioNode, then set reference to null to release it for garbage collection
  6091. * @method _cleanUpAudioNode
  6092. * @param audioNode
  6093. * @return {audioNode}
  6094. * @protected
  6095. * @since 0.4.1
  6096. */
  6097. p._cleanUpAudioNode = function(audioNode) {
  6098. if(audioNode) {
  6099. audioNode.stop(0);
  6100. audioNode.disconnect(0);
  6101. // necessary to prevent leak on iOS Safari 7-9. will throw in almost all other
  6102. // browser implementations.
  6103. if ( createjs.BrowserDetect.isIOS ) {
  6104. try { audioNode.buffer = s._scratchBuffer; } catch(e) {}
  6105. }
  6106. audioNode = null;
  6107. }
  6108. return audioNode;
  6109. };
  6110. p._handleSoundReady = function (event) {
  6111. this.gainNode.connect(s.destinationNode); // this line can cause a memory leak. Nodes need to be disconnected from the audioDestination or any sequence that leads to it.
  6112. var dur = this._duration * 0.001,
  6113. pos = Math.min(Math.max(0, this._position) * 0.001, dur);
  6114. this.sourceNode = this._createAndPlayAudioNode((s.context.currentTime - dur), pos);
  6115. this._playbackStartTime = this.sourceNode.startTime - pos;
  6116. this._soundCompleteTimeout = setTimeout(this._endedHandler, (dur - pos) * 1000);
  6117. if(this._loop != 0) {
  6118. this._sourceNodeNext = this._createAndPlayAudioNode(this._playbackStartTime, 0);
  6119. }
  6120. };
  6121. /**
  6122. * Creates an audio node using the current src and context, connects it to the gain node, and starts playback.
  6123. * @method _createAndPlayAudioNode
  6124. * @param {Number} startTime The time to add this to the web audio context, in seconds.
  6125. * @param {Number} offset The amount of time into the src audio to start playback, in seconds.
  6126. * @return {audioNode}
  6127. * @protected
  6128. * @since 0.4.1
  6129. */
  6130. p._createAndPlayAudioNode = function(startTime, offset) {
  6131. var audioNode = s.context.createBufferSource();
  6132. audioNode.buffer = this.playbackResource;
  6133. audioNode.connect(this.panNode);
  6134. var dur = this._duration * 0.001;
  6135. audioNode.startTime = startTime + dur;
  6136. audioNode.start(audioNode.startTime, offset+(this._startTime*0.001), dur - offset);
  6137. return audioNode;
  6138. };
  6139. p._pause = function () {
  6140. this._position = (s.context.currentTime - this._playbackStartTime) * 1000; // * 1000 to give milliseconds, lets us restart at same point
  6141. this.sourceNode = this._cleanUpAudioNode(this.sourceNode);
  6142. this._sourceNodeNext = this._cleanUpAudioNode(this._sourceNodeNext);
  6143. if (this.gainNode.numberOfOutputs != 0) {this.gainNode.disconnect(0);}
  6144. clearTimeout(this._soundCompleteTimeout);
  6145. };
  6146. p._resume = function () {
  6147. this._handleSoundReady();
  6148. };
  6149. /*
  6150. p._handleStop = function () {
  6151. // web audio does not need to do anything extra
  6152. };
  6153. */
  6154. p._updateVolume = function () {
  6155. var newVolume = this._muted ? 0 : this._volume;
  6156. if (newVolume != this.gainNode.gain.value) {
  6157. this.gainNode.gain.value = newVolume;
  6158. }
  6159. };
  6160. p._calculateCurrentPosition = function () {
  6161. return ((s.context.currentTime - this._playbackStartTime) * 1000); // pos in seconds * 1000 to give milliseconds
  6162. };
  6163. p._updatePosition = function () {
  6164. this.sourceNode = this._cleanUpAudioNode(this.sourceNode);
  6165. this._sourceNodeNext = this._cleanUpAudioNode(this._sourceNodeNext);
  6166. clearTimeout(this._soundCompleteTimeout);
  6167. if (!this._paused) {this._handleSoundReady();}
  6168. };
  6169. // OJR we are using a look ahead approach to ensure smooth looping.
  6170. // We add _sourceNodeNext to the audio context so that it starts playing even if this callback is delayed.
  6171. // This technique is described here: http://www.html5rocks.com/en/tutorials/audio/scheduling/
  6172. // NOTE the cost of this is that our audio loop may not always match the loop event timing precisely.
  6173. p._handleLoop = function () {
  6174. this._cleanUpAudioNode(this.sourceNode);
  6175. this.sourceNode = this._sourceNodeNext;
  6176. this._playbackStartTime = this.sourceNode.startTime;
  6177. this._sourceNodeNext = this._createAndPlayAudioNode(this._playbackStartTime, 0);
  6178. this._soundCompleteTimeout = setTimeout(this._endedHandler, this._duration);
  6179. };
  6180. p._updateDuration = function () {
  6181. if(this.playState == createjs.Sound.PLAY_SUCCEEDED) {
  6182. this._pause();
  6183. this._resume();
  6184. }
  6185. };
  6186. createjs.WebAudioSoundInstance = createjs.promote(WebAudioSoundInstance, "AbstractSoundInstance");
  6187. }());
  6188. //##############################################################################
  6189. // WebAudioPlugin.js
  6190. //##############################################################################
  6191. (function () {
  6192. "use strict";
  6193. /**
  6194. * Play sounds using Web Audio in the browser. The WebAudioPlugin is currently the default plugin, and will be used
  6195. * anywhere that it is supported. To change plugin priority, check out the Sound API
  6196. * {{#crossLink "Sound/registerPlugins"}}{{/crossLink}} method.
  6197. * <h4>Known Browser and OS issues for Web Audio</h4>
  6198. * <b>Firefox 25</b>
  6199. * <li>
  6200. * mp3 audio files do not load properly on all windows machines, reported <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=929969" target="_blank">here</a>.
  6201. * <br />For this reason it is recommended to pass another FireFox-supported type (i.e. ogg) as the default
  6202. * extension, until this bug is resolved
  6203. * </li>
  6204. *
  6205. * <b>Webkit (Chrome and Safari)</b>
  6206. * <li>
  6207. * AudioNode.disconnect does not always seem to work. This can cause the file size to grow over time if you
  6208. * are playing a lot of audio files.
  6209. * </li>
  6210. *
  6211. * <b>iOS 6 limitations</b>
  6212. * <ul>
  6213. * <li>
  6214. * Sound is initially muted and will only unmute through play being called inside a user initiated event
  6215. * (touch/click). Please read the mobile playback notes in the the {{#crossLink "Sound"}}{{/crossLink}}
  6216. * class for a full overview of the limitations, and how to get around them.
  6217. * </li>
  6218. * <li>
  6219. * A bug exists that will distort un-cached audio when a video element is present in the DOM. You can avoid
  6220. * this bug by ensuring the audio and video audio share the same sample rate.
  6221. * </li>
  6222. * </ul>
  6223. * @class WebAudioPlugin
  6224. * @extends AbstractPlugin
  6225. * @constructor
  6226. * @since 0.4.0
  6227. */
  6228. function WebAudioPlugin() {
  6229. this.AbstractPlugin_constructor();
  6230. // Private Properties
  6231. /**
  6232. * Value to set panning model to equal power for WebAudioSoundInstance. Can be "equalpower" or 0 depending on browser implementation.
  6233. * @property _panningModel
  6234. * @type {Number / String}
  6235. * @protected
  6236. */
  6237. this._panningModel = s._panningModel;;
  6238. /**
  6239. * The web audio context, which WebAudio uses to play audio. All nodes that interact with the WebAudioPlugin
  6240. * need to be created within this context.
  6241. * @property context
  6242. * @type {AudioContext}
  6243. */
  6244. this.context = s.context;
  6245. /**
  6246. * A DynamicsCompressorNode, which is used to improve sound quality and prevent audio distortion.
  6247. * It is connected to <code>context.destination</code>.
  6248. *
  6249. * Can be accessed by advanced users through createjs.Sound.activePlugin.dynamicsCompressorNode.
  6250. * @property dynamicsCompressorNode
  6251. * @type {AudioNode}
  6252. */
  6253. this.dynamicsCompressorNode = this.context.createDynamicsCompressor();
  6254. this.dynamicsCompressorNode.connect(this.context.destination);
  6255. /**
  6256. * A GainNode for controlling master volume. It is connected to {{#crossLink "WebAudioPlugin/dynamicsCompressorNode:property"}}{{/crossLink}}.
  6257. *
  6258. * Can be accessed by advanced users through createjs.Sound.activePlugin.gainNode.
  6259. * @property gainNode
  6260. * @type {AudioGainNode}
  6261. */
  6262. this.gainNode = this.context.createGain();
  6263. this.gainNode.connect(this.dynamicsCompressorNode);
  6264. createjs.WebAudioSoundInstance.destinationNode = this.gainNode;
  6265. this._capabilities = s._capabilities;
  6266. this._loaderClass = createjs.WebAudioLoader;
  6267. this._soundInstanceClass = createjs.WebAudioSoundInstance;
  6268. this._addPropsToClasses();
  6269. }
  6270. var p = createjs.extend(WebAudioPlugin, createjs.AbstractPlugin);
  6271. // Static Properties
  6272. var s = WebAudioPlugin;
  6273. /**
  6274. * The capabilities of the plugin. This is generated via the {{#crossLink "WebAudioPlugin/_generateCapabilities:method"}}{{/crossLink}}
  6275. * method and is used internally.
  6276. * @property _capabilities
  6277. * @type {Object}
  6278. * @default null
  6279. * @private
  6280. * @static
  6281. */
  6282. s._capabilities = null;
  6283. /**
  6284. * Value to set panning model to equal power for WebAudioSoundInstance. Can be "equalpower" or 0 depending on browser implementation.
  6285. * @property _panningModel
  6286. * @type {Number / String}
  6287. * @private
  6288. * @static
  6289. */
  6290. s._panningModel = "equalpower";
  6291. /**
  6292. * The web audio context, which WebAudio uses to play audio. All nodes that interact with the WebAudioPlugin
  6293. * need to be created within this context.
  6294. *
  6295. * Advanced users can set this to an existing context, but <b>must</b> do so before they call
  6296. * {{#crossLink "Sound/registerPlugins"}}{{/crossLink}} or {{#crossLink "Sound/initializeDefaultPlugins"}}{{/crossLink}}.
  6297. *
  6298. * @property context
  6299. * @type {AudioContext}
  6300. * @static
  6301. */
  6302. s.context = null;
  6303. /**
  6304. * The scratch buffer that will be assigned to the buffer property of a source node on close.
  6305. * Works around an iOS Safari bug: https://github.com/CreateJS/SoundJS/issues/102
  6306. *
  6307. * Advanced users can set this to an existing source node, but <b>must</b> do so before they call
  6308. * {{#crossLink "Sound/registerPlugins"}}{{/crossLink}} or {{#crossLink "Sound/initializeDefaultPlugins"}}{{/crossLink}}.
  6309. *
  6310. * @property _scratchBuffer
  6311. * @type {AudioBuffer}
  6312. * @private
  6313. * @static
  6314. */
  6315. s._scratchBuffer = null;
  6316. /**
  6317. * Indicated whether audio on iOS has been unlocked, which requires a touchend/mousedown event that plays an
  6318. * empty sound.
  6319. * @property _unlocked
  6320. * @type {boolean}
  6321. * @since 0.6.2
  6322. * @private
  6323. */
  6324. s._unlocked = false;
  6325. /**
  6326. * The default sample rate used when checking for iOS compatibility. See {{#crossLink "WebAudioPlugin/_createAudioContext"}}{{/crossLink}}.
  6327. * @property DEFAULT_SAMPLE_REATE
  6328. * @type {number}
  6329. * @default 44100
  6330. * @static
  6331. */
  6332. s.DEFAULT_SAMPLE_RATE = 44100;
  6333. // Static Public Methods
  6334. /**
  6335. * Determine if the plugin can be used in the current browser/OS.
  6336. * @method isSupported
  6337. * @return {Boolean} If the plugin can be initialized.
  6338. * @static
  6339. */
  6340. s.isSupported = function () {
  6341. // check if this is some kind of mobile device, Web Audio works with local protocol under PhoneGap and it is unlikely someone is trying to run a local file
  6342. var isMobilePhoneGap = createjs.BrowserDetect.isIOS || createjs.BrowserDetect.isAndroid || createjs.BrowserDetect.isBlackberry;
  6343. // OJR isMobile may be redundant with _isFileXHRSupported available. Consider removing.
  6344. if (location.protocol == "file:" && !isMobilePhoneGap && !this._isFileXHRSupported()) { return false; } // Web Audio requires XHR, which is not usually available locally
  6345. s._generateCapabilities();
  6346. if (s.context == null) {return false;}
  6347. return true;
  6348. };
  6349. /**
  6350. * Plays an empty sound in the web audio context. This is used to enable web audio on iOS devices, as they
  6351. * require the first sound to be played inside of a user initiated event (touch/click). This is called when
  6352. * {{#crossLink "WebAudioPlugin"}}{{/crossLink}} is initialized (by Sound {{#crossLink "Sound/initializeDefaultPlugins"}}{{/crossLink}}
  6353. * for example).
  6354. *
  6355. * <h4>Example</h4>
  6356. *
  6357. * function handleTouch(event) {
  6358. * createjs.WebAudioPlugin.playEmptySound();
  6359. * }
  6360. *
  6361. * @method playEmptySound
  6362. * @static
  6363. * @since 0.4.1
  6364. */
  6365. s.playEmptySound = function() {
  6366. if (s.context == null) {return;}
  6367. var source = s.context.createBufferSource();
  6368. source.buffer = s._scratchBuffer;
  6369. source.connect(s.context.destination);
  6370. source.start(0, 0, 0);
  6371. };
  6372. // Static Private Methods
  6373. /**
  6374. * Determine if XHR is supported, which is necessary for web audio.
  6375. * @method _isFileXHRSupported
  6376. * @return {Boolean} If XHR is supported.
  6377. * @since 0.4.2
  6378. * @private
  6379. * @static
  6380. */
  6381. s._isFileXHRSupported = function() {
  6382. // it's much easier to detect when something goes wrong, so let's start optimistically
  6383. var supported = true;
  6384. var xhr = new XMLHttpRequest();
  6385. try {
  6386. xhr.open("GET", "WebAudioPluginTest.fail", false); // loading non-existant file triggers 404 only if it could load (synchronous call)
  6387. } catch (error) {
  6388. // catch errors in cases where the onerror is passed by
  6389. supported = false;
  6390. return supported;
  6391. }
  6392. xhr.onerror = function() { supported = false; }; // cause irrelevant
  6393. // with security turned off, we can get empty success results, which is actually a failed read (status code 0?)
  6394. xhr.onload = function() { supported = this.status == 404 || (this.status == 200 || (this.status == 0 && this.response != "")); };
  6395. try {
  6396. xhr.send();
  6397. } catch (error) {
  6398. // catch errors in cases where the onerror is passed by
  6399. supported = false;
  6400. }
  6401. return supported;
  6402. };
  6403. /**
  6404. * Determine the capabilities of the plugin. Used internally. Please see the Sound API {{#crossLink "Sound/capabilities:property"}}{{/crossLink}}
  6405. * method for an overview of plugin capabilities.
  6406. * @method _generateCapabilities
  6407. * @static
  6408. * @private
  6409. */
  6410. s._generateCapabilities = function () {
  6411. if (s._capabilities != null) {return;}
  6412. // Web Audio can be in any formats supported by the audio element, from http://www.w3.org/TR/webaudio/#AudioContext-section
  6413. var t = document.createElement("audio");
  6414. if (t.canPlayType == null) {return null;}
  6415. if (s.context == null) {
  6416. s.context = s._createAudioContext();
  6417. if (s.context == null) { return null; }
  6418. }
  6419. if (s._scratchBuffer == null) {
  6420. s._scratchBuffer = s.context.createBuffer(1, 1, 22050);
  6421. }
  6422. s._compatibilitySetUp();
  6423. // Listen for document level clicks to unlock WebAudio on iOS. See the _unlock method.
  6424. if ("ontouchstart" in window && s.context.state != "running") {
  6425. s._unlock(); // When played inside of a touch event, this will enable audio on iOS immediately.
  6426. document.addEventListener("mousedown", s._unlock, true);
  6427. document.addEventListener("touchstart", s._unlock, true);
  6428. document.addEventListener("touchend", s._unlock, true);
  6429. }
  6430. s._capabilities = {
  6431. panning:true,
  6432. volume:true,
  6433. tracks:-1
  6434. };
  6435. // determine which extensions our browser supports for this plugin by iterating through Sound.SUPPORTED_EXTENSIONS
  6436. var supportedExtensions = createjs.Sound.SUPPORTED_EXTENSIONS;
  6437. var extensionMap = createjs.Sound.EXTENSION_MAP;
  6438. for (var i = 0, l = supportedExtensions.length; i < l; i++) {
  6439. var ext = supportedExtensions[i];
  6440. var playType = extensionMap[ext] || ext;
  6441. s._capabilities[ext] = (t.canPlayType("audio/" + ext) != "no" && t.canPlayType("audio/" + ext) != "") || (t.canPlayType("audio/" + playType) != "no" && t.canPlayType("audio/" + playType) != "");
  6442. } // OJR another way to do this might be canPlayType:"m4a", codex: mp4
  6443. // 0=no output, 1=mono, 2=stereo, 4=surround, 6=5.1 surround.
  6444. // See http://www.w3.org/TR/webaudio/#AudioChannelSplitter for more details on channels.
  6445. if (s.context.destination.numberOfChannels < 2) {
  6446. s._capabilities.panning = false;
  6447. }
  6448. };
  6449. /**
  6450. * Create an audio context for the sound.
  6451. *
  6452. * This method handles both vendor prefixes (specifically webkit support), as well as a case on iOS where
  6453. * audio played with a different sample rate may play garbled when first started. The default sample rate is
  6454. * 44,100, however it can be changed using the {{#crossLink "WebAudioPlugin/DEFAULT_SAMPLE_RATE:property"}}{{/crossLink}}.
  6455. * @method _createAudioContext
  6456. * @return {AudioContext | webkitAudioContext}
  6457. * @private
  6458. * @static
  6459. * @since 1.0.0
  6460. */
  6461. s._createAudioContext = function() {
  6462. // Slightly modified version of https://github.com/Jam3/ios-safe-audio-context
  6463. // Resolves issues with first-run contexts playing garbled on iOS.
  6464. var AudioCtor = (window.AudioContext || window.webkitAudioContext);
  6465. if (AudioCtor == null) { return null; }
  6466. var context = new AudioCtor();
  6467. // Check if hack is necessary. Only occurs in iOS6+ devices
  6468. // and only when you first boot the iPhone, or play a audio/video
  6469. // with a different sample rate
  6470. if (/(iPhone|iPad)/i.test(navigator.userAgent)
  6471. && context.sampleRate !== s.DEFAULT_SAMPLE_RATE) {
  6472. var buffer = context.createBuffer(1, 1, s.DEFAULT_SAMPLE_RATE),
  6473. dummy = context.createBufferSource();
  6474. dummy.buffer = buffer;
  6475. dummy.connect(context.destination);
  6476. dummy.start(0);
  6477. dummy.disconnect();
  6478. context.close() // dispose old context
  6479. context = new AudioCtor();
  6480. }
  6481. return context;
  6482. }
  6483. /**
  6484. * Set up compatibility if only deprecated web audio calls are supported.
  6485. * See http://www.w3.org/TR/webaudio/#DeprecationNotes
  6486. * Needed so we can support new browsers that don't support deprecated calls (Firefox) as well as old browsers that
  6487. * don't support new calls.
  6488. *
  6489. * @method _compatibilitySetUp
  6490. * @static
  6491. * @private
  6492. * @since 0.4.2
  6493. */
  6494. s._compatibilitySetUp = function() {
  6495. s._panningModel = "equalpower";
  6496. //assume that if one new call is supported, they all are
  6497. if (s.context.createGain) { return; }
  6498. // simple name change, functionality the same
  6499. s.context.createGain = s.context.createGainNode;
  6500. // source node, add to prototype
  6501. var audioNode = s.context.createBufferSource();
  6502. audioNode.__proto__.start = audioNode.__proto__.noteGrainOn; // note that noteGrainOn requires all 3 parameters
  6503. audioNode.__proto__.stop = audioNode.__proto__.noteOff;
  6504. // panningModel
  6505. s._panningModel = 0;
  6506. };
  6507. /**
  6508. * Try to unlock audio on iOS. This is triggered from either WebAudio plugin setup (which will work if inside of
  6509. * a `mousedown` or `touchend` event stack), or the first document touchend/mousedown event. If it fails (touchend
  6510. * will fail if the user presses for too long, indicating a scroll event instead of a click event.
  6511. *
  6512. * Note that earlier versions of iOS supported `touchstart` for this, but iOS9 removed this functionality. Adding
  6513. * a `touchstart` event to support older platforms may preclude a `mousedown` even from getting fired on iOS9, so we
  6514. * stick with `mousedown` and `touchend`.
  6515. * @method _unlock
  6516. * @since 0.6.2
  6517. * @private
  6518. */
  6519. s._unlock = function() {
  6520. if (s._unlocked) { return; }
  6521. s.playEmptySound();
  6522. if (s.context.state == "running") {
  6523. document.removeEventListener("mousedown", s._unlock, true);
  6524. document.removeEventListener("touchend", s._unlock, true);
  6525. document.removeEventListener("touchstart", s._unlock, true);
  6526. s._unlocked = true;
  6527. }
  6528. };
  6529. // Public Methods
  6530. p.toString = function () {
  6531. return "[WebAudioPlugin]";
  6532. };
  6533. // Private Methods
  6534. /**
  6535. * Set up needed properties on supported classes WebAudioSoundInstance and WebAudioLoader.
  6536. * @method _addPropsToClasses
  6537. * @static
  6538. * @protected
  6539. * @since 0.6.0
  6540. */
  6541. p._addPropsToClasses = function() {
  6542. var c = this._soundInstanceClass;
  6543. c.context = this.context;
  6544. c._scratchBuffer = s._scratchBuffer;
  6545. c.destinationNode = this.gainNode;
  6546. c._panningModel = this._panningModel;
  6547. this._loaderClass.context = this.context;
  6548. };
  6549. /**
  6550. * Set the gain value for master audio. Should not be called externally.
  6551. * @method _updateVolume
  6552. * @protected
  6553. */
  6554. p._updateVolume = function () {
  6555. var newVolume = createjs.Sound._masterMute ? 0 : this._volume;
  6556. if (newVolume != this.gainNode.gain.value) {
  6557. this.gainNode.gain.value = newVolume;
  6558. }
  6559. };
  6560. createjs.WebAudioPlugin = createjs.promote(WebAudioPlugin, "AbstractPlugin");
  6561. }());
  6562. //##############################################################################
  6563. // HTMLAudioTagPool.js
  6564. //##############################################################################
  6565. (function () {
  6566. "use strict";
  6567. /**
  6568. * HTMLAudioTagPool is an object pool for HTMLAudio tag instances.
  6569. * @class HTMLAudioTagPool
  6570. * @param {String} src The source of the channel.
  6571. * @protected
  6572. */
  6573. function HTMLAudioTagPool() {
  6574. throw "HTMLAudioTagPool cannot be instantiated";
  6575. }
  6576. var s = HTMLAudioTagPool;
  6577. // Static Properties
  6578. /**
  6579. * A hash lookup of each base audio tag, indexed by the audio source.
  6580. * @property _tags
  6581. * @type {{}}
  6582. * @static
  6583. * @private
  6584. */
  6585. s._tags = {};
  6586. /**
  6587. * An object pool for html audio tags
  6588. * @property _tagPool
  6589. * @type {TagPool}
  6590. * @static
  6591. * @private
  6592. */
  6593. s._tagPool = new TagPool();
  6594. /**
  6595. * A hash lookup of if a base audio tag is available, indexed by the audio source
  6596. * @property _tagsUsed
  6597. * @type {{}}
  6598. * @private
  6599. * @static
  6600. */
  6601. s._tagUsed = {};
  6602. // Static Methods
  6603. /**
  6604. * Get an audio tag with the given source.
  6605. * @method get
  6606. * @param {String} src The source file used by the audio tag.
  6607. * @static
  6608. */
  6609. s.get = function (src) {
  6610. var t = s._tags[src];
  6611. if (t == null) {
  6612. // create new base tag
  6613. t = s._tags[src] = s._tagPool.get();
  6614. t.src = src;
  6615. } else {
  6616. // get base or pool
  6617. if (s._tagUsed[src]) {
  6618. t = s._tagPool.get();
  6619. t.src = src;
  6620. } else {
  6621. s._tagUsed[src] = true;
  6622. }
  6623. }
  6624. return t;
  6625. };
  6626. /**
  6627. * Return an audio tag to the pool.
  6628. * @method set
  6629. * @param {String} src The source file used by the audio tag.
  6630. * @param {HTMLElement} tag Audio tag to set.
  6631. * @static
  6632. */
  6633. s.set = function (src, tag) {
  6634. // check if this is base, if yes set boolean if not return to pool
  6635. if(tag == s._tags[src]) {
  6636. s._tagUsed[src] = false;
  6637. } else {
  6638. s._tagPool.set(tag);
  6639. }
  6640. };
  6641. /**
  6642. * Delete stored tag reference and return them to pool. Note that if the tag reference does not exist, this will fail.
  6643. * @method remove
  6644. * @param {String} src The source for the tag
  6645. * @return {Boolean} If the TagPool was deleted.
  6646. * @static
  6647. */
  6648. s.remove = function (src) {
  6649. var tag = s._tags[src];
  6650. if (tag == null) {return false;}
  6651. s._tagPool.set(tag);
  6652. delete(s._tags[src]);
  6653. delete(s._tagUsed[src]);
  6654. return true;
  6655. };
  6656. /**
  6657. * Gets the duration of the src audio in milliseconds
  6658. * @method getDuration
  6659. * @param {String} src The source file used by the audio tag.
  6660. * @return {Number} Duration of src in milliseconds
  6661. * @static
  6662. */
  6663. s.getDuration= function (src) {
  6664. var t = s._tags[src];
  6665. if (t == null || !t.duration) {return 0;} // OJR duration is NaN if loading has not completed
  6666. return t.duration * 1000;
  6667. };
  6668. createjs.HTMLAudioTagPool = HTMLAudioTagPool;
  6669. // ************************************************************************************************************
  6670. /**
  6671. * The TagPool is an object pool for HTMLAudio tag instances.
  6672. * #class TagPool
  6673. * @param {String} src The source of the channel.
  6674. * @protected
  6675. */
  6676. function TagPool(src) {
  6677. // Public Properties
  6678. /**
  6679. * A list of all available tags in the pool.
  6680. * #property tags
  6681. * @type {Array}
  6682. * @protected
  6683. */
  6684. this._tags = [];
  6685. };
  6686. var p = TagPool.prototype;
  6687. p.constructor = TagPool;
  6688. // Public Methods
  6689. /**
  6690. * Get an HTMLAudioElement for immediate playback. This takes it out of the pool.
  6691. * #method get
  6692. * @return {HTMLAudioElement} An HTML audio tag.
  6693. */
  6694. p.get = function () {
  6695. var tag;
  6696. if (this._tags.length == 0) {
  6697. tag = this._createTag();
  6698. } else {
  6699. tag = this._tags.pop();
  6700. }
  6701. if (tag.parentNode == null) {document.body.appendChild(tag);}
  6702. return tag;
  6703. };
  6704. /**
  6705. * Put an HTMLAudioElement back in the pool for use.
  6706. * #method set
  6707. * @param {HTMLAudioElement} tag HTML audio tag
  6708. */
  6709. p.set = function (tag) {
  6710. // OJR this first step seems unnecessary
  6711. var index = createjs.indexOf(this._tags, tag);
  6712. if (index == -1) {
  6713. this._tags.src = null;
  6714. this._tags.push(tag);
  6715. }
  6716. };
  6717. p.toString = function () {
  6718. return "[TagPool]";
  6719. };
  6720. // Private Methods
  6721. /**
  6722. * Create an HTML audio tag.
  6723. * #method _createTag
  6724. * @param {String} src The source file to set for the audio tag.
  6725. * @return {HTMLElement} Returns an HTML audio tag.
  6726. * @protected
  6727. */
  6728. p._createTag = function () {
  6729. var tag = document.createElement("audio");
  6730. tag.autoplay = false;
  6731. tag.preload = "none";
  6732. //LM: Firefox fails when this the preload="none" for other tags, but it needs to be "none" to ensure PreloadJS works.
  6733. return tag;
  6734. };
  6735. }());
  6736. //##############################################################################
  6737. // HTMLAudioSoundInstance.js
  6738. //##############################################################################
  6739. (function () {
  6740. "use strict";
  6741. /**
  6742. * HTMLAudioSoundInstance extends the base api of {{#crossLink "AbstractSoundInstance"}}{{/crossLink}} and is used by
  6743. * {{#crossLink "HTMLAudioPlugin"}}{{/crossLink}}.
  6744. *
  6745. * @param {String} src The path to and file name of the sound.
  6746. * @param {Number} startTime Audio sprite property used to apply an offset, in milliseconds.
  6747. * @param {Number} duration Audio sprite property used to set the time the clip plays for, in milliseconds.
  6748. * @param {Object} playbackResource Any resource needed by plugin to support audio playback.
  6749. * @class HTMLAudioSoundInstance
  6750. * @extends AbstractSoundInstance
  6751. * @constructor
  6752. */
  6753. function HTMLAudioSoundInstance(src, startTime, duration, playbackResource) {
  6754. this.AbstractSoundInstance_constructor(src, startTime, duration, playbackResource);
  6755. // Private Properties
  6756. this._audioSpriteStopTime = null;
  6757. this._delayTimeoutId = null;
  6758. // Proxies, make removing listeners easier.
  6759. this._endedHandler = createjs.proxy(this._handleSoundComplete, this);
  6760. this._readyHandler = createjs.proxy(this._handleTagReady, this);
  6761. this._stalledHandler = createjs.proxy(this._playFailed, this);
  6762. this._audioSpriteEndHandler = createjs.proxy(this._handleAudioSpriteLoop, this);
  6763. this._loopHandler = createjs.proxy(this._handleSoundComplete, this);
  6764. if (duration) {
  6765. this._audioSpriteStopTime = (startTime + duration) * 0.001;
  6766. } else {
  6767. this._duration = createjs.HTMLAudioTagPool.getDuration(this.src);
  6768. }
  6769. }
  6770. var p = createjs.extend(HTMLAudioSoundInstance, createjs.AbstractSoundInstance);
  6771. // Public Methods
  6772. /**
  6773. * Called by {{#crossLink "Sound"}}{{/crossLink}} when plugin does not handle master volume.
  6774. * undoc'd because it is not meant to be used outside of Sound
  6775. * #method setMasterVolume
  6776. * @param value
  6777. */
  6778. p.setMasterVolume = function (value) {
  6779. this._updateVolume();
  6780. };
  6781. /**
  6782. * Called by {{#crossLink "Sound"}}{{/crossLink}} when plugin does not handle master mute.
  6783. * undoc'd because it is not meant to be used outside of Sound
  6784. * #method setMasterMute
  6785. * @param value
  6786. */
  6787. p.setMasterMute = function (isMuted) {
  6788. this._updateVolume();
  6789. };
  6790. p.toString = function () {
  6791. return "[HTMLAudioSoundInstance]";
  6792. };
  6793. //Private Methods
  6794. p._removeLooping = function() {
  6795. if(this._playbackResource == null) {return;}
  6796. this._playbackResource.loop = false;
  6797. this._playbackResource.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_SEEKED, this._loopHandler, false);
  6798. };
  6799. p._addLooping = function() {
  6800. if(this._playbackResource == null || this._audioSpriteStopTime) {return;}
  6801. this._playbackResource.addEventListener(createjs.HTMLAudioPlugin._AUDIO_SEEKED, this._loopHandler, false);
  6802. this._playbackResource.loop = true;
  6803. };
  6804. p._handleCleanUp = function () {
  6805. var tag = this._playbackResource;
  6806. if (tag != null) {
  6807. tag.pause();
  6808. tag.loop = false;
  6809. tag.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_ENDED, this._endedHandler, false);
  6810. tag.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_READY, this._readyHandler, false);
  6811. tag.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_STALLED, this._stalledHandler, false);
  6812. tag.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_SEEKED, this._loopHandler, false);
  6813. tag.removeEventListener(createjs.HTMLAudioPlugin._TIME_UPDATE, this._audioSpriteEndHandler, false);
  6814. try {
  6815. tag.currentTime = this._startTime;
  6816. } catch (e) {
  6817. } // Reset Position
  6818. createjs.HTMLAudioTagPool.set(this.src, tag);
  6819. this._playbackResource = null;
  6820. }
  6821. };
  6822. p._beginPlaying = function (playProps) {
  6823. this._playbackResource = createjs.HTMLAudioTagPool.get(this.src);
  6824. return this.AbstractSoundInstance__beginPlaying(playProps);
  6825. };
  6826. p._handleSoundReady = function (event) {
  6827. if (this._playbackResource.readyState !== 4) {
  6828. var tag = this._playbackResource;
  6829. tag.addEventListener(createjs.HTMLAudioPlugin._AUDIO_READY, this._readyHandler, false);
  6830. tag.addEventListener(createjs.HTMLAudioPlugin._AUDIO_STALLED, this._stalledHandler, false);
  6831. tag.preload = "auto"; // This is necessary for Firefox, as it won't ever "load" until this is set.
  6832. tag.load();
  6833. return;
  6834. }
  6835. this._updateVolume();
  6836. this._playbackResource.currentTime = (this._startTime + this._position) * 0.001;
  6837. if (this._audioSpriteStopTime) {
  6838. this._playbackResource.addEventListener(createjs.HTMLAudioPlugin._TIME_UPDATE, this._audioSpriteEndHandler, false);
  6839. } else {
  6840. this._playbackResource.addEventListener(createjs.HTMLAudioPlugin._AUDIO_ENDED, this._endedHandler, false);
  6841. if(this._loop != 0) {
  6842. this._playbackResource.addEventListener(createjs.HTMLAudioPlugin._AUDIO_SEEKED, this._loopHandler, false);
  6843. this._playbackResource.loop = true;
  6844. }
  6845. }
  6846. this._playbackResource.play();
  6847. };
  6848. /**
  6849. * Used to handle when a tag is not ready for immediate playback when it is returned from the HTMLAudioTagPool.
  6850. * @method _handleTagReady
  6851. * @param event
  6852. * @protected
  6853. */
  6854. p._handleTagReady = function (event) {
  6855. this._playbackResource.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_READY, this._readyHandler, false);
  6856. this._playbackResource.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_STALLED, this._stalledHandler, false);
  6857. this._handleSoundReady();
  6858. };
  6859. p._pause = function () {
  6860. this._playbackResource.pause();
  6861. };
  6862. p._resume = function () {
  6863. this._playbackResource.play();
  6864. };
  6865. p._updateVolume = function () {
  6866. if (this._playbackResource != null) {
  6867. var newVolume = (this._muted || createjs.Sound._masterMute) ? 0 : this._volume * createjs.Sound._masterVolume;
  6868. if (newVolume != this._playbackResource.volume) {this._playbackResource.volume = newVolume;}
  6869. }
  6870. };
  6871. p._calculateCurrentPosition = function() {
  6872. return (this._playbackResource.currentTime * 1000) - this._startTime;
  6873. };
  6874. p._updatePosition = function() {
  6875. this._playbackResource.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_SEEKED, this._loopHandler, false);
  6876. this._playbackResource.addEventListener(createjs.HTMLAudioPlugin._AUDIO_SEEKED, this._handleSetPositionSeek, false);
  6877. try {
  6878. this._playbackResource.currentTime = (this._position + this._startTime) * 0.001;
  6879. } catch (error) { // Out of range
  6880. this._handleSetPositionSeek(null);
  6881. }
  6882. };
  6883. /**
  6884. * Used to enable setting position, as we need to wait for that seek to be done before we add back our loop handling seek listener
  6885. * @method _handleSetPositionSeek
  6886. * @param event
  6887. * @protected
  6888. */
  6889. p._handleSetPositionSeek = function(event) {
  6890. if (this._playbackResource == null) { return; }
  6891. this._playbackResource.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_SEEKED, this._handleSetPositionSeek, false);
  6892. this._playbackResource.addEventListener(createjs.HTMLAudioPlugin._AUDIO_SEEKED, this._loopHandler, false);
  6893. };
  6894. /**
  6895. * Timer used to loop audio sprites.
  6896. * NOTE because of the inaccuracies in the timeupdate event (15 - 250ms) and in setting the tag to the desired timed
  6897. * (up to 300ms), it is strongly recommended not to loop audio sprites with HTML Audio if smooth looping is desired
  6898. *
  6899. * @method _handleAudioSpriteLoop
  6900. * @param event
  6901. * @private
  6902. */
  6903. p._handleAudioSpriteLoop = function (event) {
  6904. if(this._playbackResource.currentTime <= this._audioSpriteStopTime) {return;}
  6905. this._playbackResource.pause();
  6906. if(this._loop == 0) {
  6907. this._handleSoundComplete(null);
  6908. } else {
  6909. this._position = 0;
  6910. this._loop--;
  6911. this._playbackResource.currentTime = this._startTime * 0.001;
  6912. if(!this._paused) {this._playbackResource.play();}
  6913. this._sendEvent("loop");
  6914. }
  6915. };
  6916. // NOTE with this approach audio will loop as reliably as the browser allows
  6917. // but we could end up sending the loop event after next loop playback begins
  6918. p._handleLoop = function (event) {
  6919. if(this._loop == 0) {
  6920. this._playbackResource.loop = false;
  6921. this._playbackResource.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_SEEKED, this._loopHandler, false);
  6922. }
  6923. };
  6924. p._updateStartTime = function () {
  6925. this._audioSpriteStopTime = (this._startTime + this._duration) * 0.001;
  6926. if(this.playState == createjs.Sound.PLAY_SUCCEEDED) {
  6927. this._playbackResource.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_ENDED, this._endedHandler, false);
  6928. this._playbackResource.addEventListener(createjs.HTMLAudioPlugin._TIME_UPDATE, this._audioSpriteEndHandler, false);
  6929. }
  6930. };
  6931. p._updateDuration = function () {
  6932. this._audioSpriteStopTime = (this._startTime + this._duration) * 0.001;
  6933. if(this.playState == createjs.Sound.PLAY_SUCCEEDED) {
  6934. this._playbackResource.removeEventListener(createjs.HTMLAudioPlugin._AUDIO_ENDED, this._endedHandler, false);
  6935. this._playbackResource.addEventListener(createjs.HTMLAudioPlugin._TIME_UPDATE, this._audioSpriteEndHandler, false);
  6936. }
  6937. };
  6938. p._setDurationFromSource = function () {
  6939. this._duration = createjs.HTMLAudioTagPool.getDuration(this.src);
  6940. this._playbackResource = null;
  6941. };
  6942. createjs.HTMLAudioSoundInstance = createjs.promote(HTMLAudioSoundInstance, "AbstractSoundInstance");
  6943. }());
  6944. //##############################################################################
  6945. // HTMLAudioPlugin.js
  6946. //##############################################################################
  6947. (function () {
  6948. "use strict";
  6949. /**
  6950. * Play sounds using HTML &lt;audio&gt; tags in the browser. This plugin is the second priority plugin installed
  6951. * by default, after the {{#crossLink "WebAudioPlugin"}}{{/crossLink}}. For older browsers that do not support html
  6952. * audio, include and install the {{#crossLink "FlashAudioPlugin"}}{{/crossLink}}.
  6953. *
  6954. * <h4>Known Browser and OS issues for HTML Audio</h4>
  6955. * <b>All browsers</b><br />
  6956. * Testing has shown in all browsers there is a limit to how many audio tag instances you are allowed. If you exceed
  6957. * this limit, you can expect to see unpredictable results. Please use {{#crossLink "Sound.MAX_INSTANCES"}}{{/crossLink}} as
  6958. * a guide to how many total audio tags you can safely use in all browsers. This issue is primarily limited to IE9.
  6959. *
  6960. * <b>IE html limitations</b><br />
  6961. * <ul><li>There is a delay in applying volume changes to tags that occurs once playback is started. So if you have
  6962. * muted all sounds, they will all play during this delay until the mute applies internally. This happens regardless of
  6963. * when or how you apply the volume change, as the tag seems to need to play to apply it.</li>
  6964. * <li>MP3 encoding will not always work for audio tags if it's not default. We've found default encoding with
  6965. * 64kbps works.</li>
  6966. * <li>Occasionally very short samples will get cut off.</li>
  6967. * <li>There is a limit to how many audio tags you can load or play at once, which appears to be determined by
  6968. * hardware and browser settings. See {{#crossLink "HTMLAudioPlugin.MAX_INSTANCES"}}{{/crossLink}} for a safe estimate.
  6969. * Note that audio sprites can be used as a solution to this issue.</li></ul>
  6970. *
  6971. * <b>Safari limitations</b><br />
  6972. * <ul><li>Safari requires Quicktime to be installed for audio playback.</li></ul>
  6973. *
  6974. * <b>iOS 6 limitations</b><br />
  6975. * <ul><li>can only have one &lt;audio&gt; tag</li>
  6976. * <li>can not preload or autoplay the audio</li>
  6977. * <li>can not cache the audio</li>
  6978. * <li>can not play the audio except inside a user initiated event.</li>
  6979. * <li>Note it is recommended to use {{#crossLink "WebAudioPlugin"}}{{/crossLink}} for iOS (6+)</li>
  6980. * <li>audio sprites can be used to mitigate some of these issues and are strongly recommended on iOS</li>
  6981. * </ul>
  6982. *
  6983. * <b>Android Native Browser limitations</b><br />
  6984. * <ul><li>We have no control over audio volume. Only the user can set volume on their device.</li>
  6985. * <li>We can only play audio inside a user event (touch/click). This currently means you cannot loop sound or use a delay.</li></ul>
  6986. * <b> Android Chrome 26.0.1410.58 specific limitations</b><br />
  6987. * <ul> <li>Can only play 1 sound at a time.</li>
  6988. * <li>Sound is not cached.</li>
  6989. * <li>Sound can only be loaded in a user initiated touch/click event.</li>
  6990. * <li>There is a delay before a sound is played, presumably while the src is loaded.</li>
  6991. * </ul>
  6992. *
  6993. * See {{#crossLink "Sound"}}{{/crossLink}} for general notes on known issues.
  6994. *
  6995. * @class HTMLAudioPlugin
  6996. * @extends AbstractPlugin
  6997. * @constructor
  6998. */
  6999. function HTMLAudioPlugin() {
  7000. this.AbstractPlugin_constructor();
  7001. // Public Properties
  7002. this._capabilities = s._capabilities;
  7003. this._loaderClass = createjs.SoundLoader;
  7004. this._soundInstanceClass = createjs.HTMLAudioSoundInstance;
  7005. }
  7006. var p = createjs.extend(HTMLAudioPlugin, createjs.AbstractPlugin);
  7007. var s = HTMLAudioPlugin;
  7008. // Static Properties
  7009. /**
  7010. * The maximum number of instances that can be loaded or played. This is a browser limitation, primarily limited to IE9.
  7011. * The actual number varies from browser to browser (and is largely hardware dependant), but this is a safe estimate.
  7012. * Audio sprites work around this limitation.
  7013. * @property MAX_INSTANCES
  7014. * @type {Number}
  7015. * @default 30
  7016. * @static
  7017. */
  7018. s.MAX_INSTANCES = 30;
  7019. /**
  7020. * Event constant for the "canPlayThrough" event for cleaner code.
  7021. * @property _AUDIO_READY
  7022. * @type {String}
  7023. * @default canplaythrough
  7024. * @static
  7025. * @private
  7026. */
  7027. s._AUDIO_READY = "canplaythrough";
  7028. /**
  7029. * Event constant for the "ended" event for cleaner code.
  7030. * @property _AUDIO_ENDED
  7031. * @type {String}
  7032. * @default ended
  7033. * @static
  7034. * @private
  7035. */
  7036. s._AUDIO_ENDED = "ended";
  7037. /**
  7038. * Event constant for the "seeked" event for cleaner code. We utilize this event for maintaining loop events.
  7039. * @property _AUDIO_SEEKED
  7040. * @type {String}
  7041. * @default seeked
  7042. * @static
  7043. * @private
  7044. */
  7045. s._AUDIO_SEEKED = "seeked";
  7046. /**
  7047. * Event constant for the "stalled" event for cleaner code.
  7048. * @property _AUDIO_STALLED
  7049. * @type {String}
  7050. * @default stalled
  7051. * @static
  7052. * @private
  7053. */
  7054. s._AUDIO_STALLED = "stalled";
  7055. /**
  7056. * Event constant for the "timeupdate" event for cleaner code. Utilized for looping audio sprites.
  7057. * This event callsback ever 15 to 250ms and can be dropped by the browser for performance.
  7058. * @property _TIME_UPDATE
  7059. * @type {String}
  7060. * @default timeupdate
  7061. * @static
  7062. * @private
  7063. */
  7064. s._TIME_UPDATE = "timeupdate";
  7065. /**
  7066. * The capabilities of the plugin. This is generated via the {{#crossLink "HTMLAudioPlugin/_generateCapabilities"}}{{/crossLink}}
  7067. * method. Please see the Sound {{#crossLink "Sound/capabilities:property"}}{{/crossLink}} method for an overview of all
  7068. * of the available properties.
  7069. * @property _capabilities
  7070. * @type {Object}
  7071. * @private
  7072. * @static
  7073. */
  7074. s._capabilities = null;
  7075. // Static Methods
  7076. /**
  7077. * Determine if the plugin can be used in the current browser/OS. Note that HTML audio is available in most modern
  7078. * browsers, but is disabled in iOS because of its limitations.
  7079. * @method isSupported
  7080. * @return {Boolean} If the plugin can be initialized.
  7081. * @static
  7082. */
  7083. s.isSupported = function () {
  7084. s._generateCapabilities();
  7085. return (s._capabilities != null);
  7086. };
  7087. /**
  7088. * Determine the capabilities of the plugin. Used internally. Please see the Sound API {{#crossLink "Sound/capabilities:property"}}{{/crossLink}}
  7089. * method for an overview of plugin capabilities.
  7090. * @method _generateCapabilities
  7091. * @static
  7092. * @private
  7093. */
  7094. s._generateCapabilities = function () {
  7095. if (s._capabilities != null) {return;}
  7096. var t = document.createElement("audio");
  7097. if (t.canPlayType == null) {return null;}
  7098. s._capabilities = {
  7099. panning:false,
  7100. volume:true,
  7101. tracks:-1
  7102. };
  7103. // determine which extensions our browser supports for this plugin by iterating through Sound.SUPPORTED_EXTENSIONS
  7104. var supportedExtensions = createjs.Sound.SUPPORTED_EXTENSIONS;
  7105. var extensionMap = createjs.Sound.EXTENSION_MAP;
  7106. for (var i = 0, l = supportedExtensions.length; i < l; i++) {
  7107. var ext = supportedExtensions[i];
  7108. var playType = extensionMap[ext] || ext;
  7109. s._capabilities[ext] = (t.canPlayType("audio/" + ext) != "no" && t.canPlayType("audio/" + ext) != "") || (t.canPlayType("audio/" + playType) != "no" && t.canPlayType("audio/" + playType) != "");
  7110. } // OJR another way to do this might be canPlayType:"m4a", codex: mp4
  7111. };
  7112. // public methods
  7113. p.register = function (loadItem) {
  7114. var tag = createjs.HTMLAudioTagPool.get(loadItem.src);
  7115. var loader = this.AbstractPlugin_register(loadItem);
  7116. loader.setTag(tag);
  7117. return loader;
  7118. };
  7119. p.removeSound = function (src) {
  7120. this.AbstractPlugin_removeSound(src);
  7121. createjs.HTMLAudioTagPool.remove(src);
  7122. };
  7123. p.create = function (src, startTime, duration) {
  7124. var si = this.AbstractPlugin_create(src, startTime, duration);
  7125. si.playbackResource = null;
  7126. return si;
  7127. };
  7128. p.toString = function () {
  7129. return "[HTMLAudioPlugin]";
  7130. };
  7131. // plugin does not support these
  7132. p.setVolume = p.getVolume = p.setMute = null;
  7133. createjs.HTMLAudioPlugin = createjs.promote(HTMLAudioPlugin, "AbstractPlugin");
  7134. }());
  7135. export default createjs