wavesurfer.js 213 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655
  1. /*!
  2. * wavesurfer.js 6.1.0 (2022-03-31)
  3. * https://wavesurfer-js.org
  4. * @license BSD-3-Clause
  5. */
  6. (function webpackUniversalModuleDefinition(root, factory) {
  7. if(typeof exports === 'object' && typeof module === 'object')
  8. module.exports = factory();
  9. else if(typeof define === 'function' && define.amd)
  10. define("WaveSurfer", [], factory);
  11. else if(typeof exports === 'object')
  12. exports["WaveSurfer"] = factory();
  13. else
  14. root["WaveSurfer"] = factory();
  15. })(self, function() {
  16. return /******/ (() => { // webpackBootstrap
  17. /******/ var __webpack_modules__ = ({
  18. /***/ "./src/drawer.canvasentry.js":
  19. /*!***********************************!*\
  20. !*** ./src/drawer.canvasentry.js ***!
  21. \***********************************/
  22. /***/ ((module, exports, __webpack_require__) => {
  23. "use strict";
  24. Object.defineProperty(exports, "__esModule", ({
  25. value: true
  26. }));
  27. exports["default"] = void 0;
  28. var _style = _interopRequireDefault(__webpack_require__(/*! ./util/style */ "./src/util/style.js"));
  29. var _getId = _interopRequireDefault(__webpack_require__(/*! ./util/get-id */ "./src/util/get-id.js"));
  30. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  31. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  32. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  33. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  34. /**
  35. * The `CanvasEntry` class represents an element consisting of a wave `canvas`
  36. * and an (optional) progress wave `canvas`.
  37. *
  38. * The `MultiCanvas` renderer uses one or more `CanvasEntry` instances to
  39. * render a waveform, depending on the zoom level.
  40. */
  41. var CanvasEntry = /*#__PURE__*/function () {
  42. function CanvasEntry() {
  43. _classCallCheck(this, CanvasEntry);
  44. /**
  45. * The wave node
  46. *
  47. * @type {HTMLCanvasElement}
  48. */
  49. this.wave = null;
  50. /**
  51. * The wave canvas rendering context
  52. *
  53. * @type {CanvasRenderingContext2D}
  54. */
  55. this.waveCtx = null;
  56. /**
  57. * The (optional) progress wave node
  58. *
  59. * @type {HTMLCanvasElement}
  60. */
  61. this.progress = null;
  62. /**
  63. * The (optional) progress wave canvas rendering context
  64. *
  65. * @type {CanvasRenderingContext2D}
  66. */
  67. this.progressCtx = null;
  68. /**
  69. * Start of the area the canvas should render, between 0 and 1
  70. *
  71. * @type {number}
  72. */
  73. this.start = 0;
  74. /**
  75. * End of the area the canvas should render, between 0 and 1
  76. *
  77. * @type {number}
  78. */
  79. this.end = 1;
  80. /**
  81. * Unique identifier for this entry
  82. *
  83. * @type {string}
  84. */
  85. this.id = (0, _getId.default)(typeof this.constructor.name !== 'undefined' ? this.constructor.name.toLowerCase() + '_' : 'canvasentry_');
  86. /**
  87. * Canvas 2d context attributes
  88. *
  89. * @type {object}
  90. */
  91. this.canvasContextAttributes = {};
  92. }
  93. /**
  94. * Store the wave canvas element and create the 2D rendering context
  95. *
  96. * @param {HTMLCanvasElement} element The wave `canvas` element.
  97. */
  98. _createClass(CanvasEntry, [{
  99. key: "initWave",
  100. value: function initWave(element) {
  101. this.wave = element;
  102. this.waveCtx = this.wave.getContext('2d', this.canvasContextAttributes);
  103. }
  104. /**
  105. * Store the progress wave canvas element and create the 2D rendering
  106. * context
  107. *
  108. * @param {HTMLCanvasElement} element The progress wave `canvas` element.
  109. */
  110. }, {
  111. key: "initProgress",
  112. value: function initProgress(element) {
  113. this.progress = element;
  114. this.progressCtx = this.progress.getContext('2d', this.canvasContextAttributes);
  115. }
  116. /**
  117. * Update the dimensions
  118. *
  119. * @param {number} elementWidth Width of the entry
  120. * @param {number} totalWidth Total width of the multi canvas renderer
  121. * @param {number} width The new width of the element
  122. * @param {number} height The new height of the element
  123. */
  124. }, {
  125. key: "updateDimensions",
  126. value: function updateDimensions(elementWidth, totalWidth, width, height) {
  127. // where the canvas starts and ends in the waveform, represented as a
  128. // decimal between 0 and 1
  129. this.start = this.wave.offsetLeft / totalWidth || 0;
  130. this.end = this.start + elementWidth / totalWidth; // set wave canvas dimensions
  131. this.wave.width = width;
  132. this.wave.height = height;
  133. var elementSize = {
  134. width: elementWidth + 'px'
  135. };
  136. (0, _style.default)(this.wave, elementSize);
  137. if (this.hasProgressCanvas) {
  138. // set progress canvas dimensions
  139. this.progress.width = width;
  140. this.progress.height = height;
  141. (0, _style.default)(this.progress, elementSize);
  142. }
  143. }
  144. /**
  145. * Clear the wave and progress rendering contexts
  146. */
  147. }, {
  148. key: "clearWave",
  149. value: function clearWave() {
  150. // wave
  151. this.waveCtx.clearRect(0, 0, this.waveCtx.canvas.width, this.waveCtx.canvas.height); // progress
  152. if (this.hasProgressCanvas) {
  153. this.progressCtx.clearRect(0, 0, this.progressCtx.canvas.width, this.progressCtx.canvas.height);
  154. }
  155. }
  156. /**
  157. * Set the fill styles for wave and progress
  158. * @param {string|string[]} waveColor Fill color for the wave canvas,
  159. * or an array of colors to apply as a gradient
  160. * @param {?string|string[]} progressColor Fill color for the progress canvas,
  161. * or an array of colors to apply as a gradient
  162. */
  163. }, {
  164. key: "setFillStyles",
  165. value: function setFillStyles(waveColor, progressColor) {
  166. this.waveCtx.fillStyle = this.getFillStyle(this.waveCtx, waveColor);
  167. if (this.hasProgressCanvas) {
  168. this.progressCtx.fillStyle = this.getFillStyle(this.progressCtx, progressColor);
  169. }
  170. }
  171. /**
  172. * Utility function to handle wave color arguments
  173. *
  174. * When the color argument type is a string or CanvasGradient instance,
  175. * it will be returned as is. Otherwise, it will be treated as an array,
  176. * and a new CanvasGradient will be returned
  177. *
  178. * @since 6.0.0
  179. * @param {CanvasRenderingContext2D} ctx Rendering context of target canvas
  180. * @param {string|string[]|CanvasGradient} color Either a single fill color
  181. * for the wave canvas, an existing CanvasGradient instance, or an array
  182. * of colors to apply as a gradient
  183. * @returns {string|CanvasGradient} Returns a string fillstyle value, or a
  184. * canvas gradient
  185. */
  186. }, {
  187. key: "getFillStyle",
  188. value: function getFillStyle(ctx, color) {
  189. if (typeof color == 'string' || color instanceof CanvasGradient) {
  190. return color;
  191. }
  192. var waveGradient = ctx.createLinearGradient(0, 0, 0, ctx.canvas.height);
  193. color.forEach(function (value, index) {
  194. return waveGradient.addColorStop(index / color.length, value);
  195. });
  196. return waveGradient;
  197. }
  198. /**
  199. * Set the canvas transforms for wave and progress
  200. *
  201. * @param {boolean} vertical Whether to render vertically
  202. */
  203. }, {
  204. key: "applyCanvasTransforms",
  205. value: function applyCanvasTransforms(vertical) {
  206. if (vertical) {
  207. // Reflect the waveform across the line y = -x
  208. this.waveCtx.setTransform(0, 1, 1, 0, 0, 0);
  209. if (this.hasProgressCanvas) {
  210. this.progressCtx.setTransform(0, 1, 1, 0, 0, 0);
  211. }
  212. }
  213. }
  214. /**
  215. * Draw a rectangle for wave and progress
  216. *
  217. * @param {number} x X start position
  218. * @param {number} y Y start position
  219. * @param {number} width Width of the rectangle
  220. * @param {number} height Height of the rectangle
  221. * @param {number} radius Radius of the rectangle
  222. */
  223. }, {
  224. key: "fillRects",
  225. value: function fillRects(x, y, width, height, radius) {
  226. this.fillRectToContext(this.waveCtx, x, y, width, height, radius);
  227. if (this.hasProgressCanvas) {
  228. this.fillRectToContext(this.progressCtx, x, y, width, height, radius);
  229. }
  230. }
  231. /**
  232. * Draw the actual rectangle on a `canvas` element
  233. *
  234. * @param {CanvasRenderingContext2D} ctx Rendering context of target canvas
  235. * @param {number} x X start position
  236. * @param {number} y Y start position
  237. * @param {number} width Width of the rectangle
  238. * @param {number} height Height of the rectangle
  239. * @param {number} radius Radius of the rectangle
  240. */
  241. }, {
  242. key: "fillRectToContext",
  243. value: function fillRectToContext(ctx, x, y, width, height, radius) {
  244. if (!ctx) {
  245. return;
  246. }
  247. if (radius) {
  248. this.drawRoundedRect(ctx, x, y, width, height, radius);
  249. } else {
  250. ctx.fillRect(x, y, width, height);
  251. }
  252. }
  253. /**
  254. * Draw a rounded rectangle on Canvas
  255. *
  256. * @param {CanvasRenderingContext2D} ctx Canvas context
  257. * @param {number} x X-position of the rectangle
  258. * @param {number} y Y-position of the rectangle
  259. * @param {number} width Width of the rectangle
  260. * @param {number} height Height of the rectangle
  261. * @param {number} radius Radius of the rectangle
  262. *
  263. * @return {void}
  264. * @example drawRoundedRect(ctx, 50, 50, 5, 10, 3)
  265. */
  266. }, {
  267. key: "drawRoundedRect",
  268. value: function drawRoundedRect(ctx, x, y, width, height, radius) {
  269. if (height === 0) {
  270. return;
  271. } // peaks are float values from -1 to 1. Use absolute height values in
  272. // order to correctly calculate rounded rectangle coordinates
  273. if (height < 0) {
  274. height *= -1;
  275. y -= height;
  276. }
  277. ctx.beginPath();
  278. ctx.moveTo(x + radius, y);
  279. ctx.lineTo(x + width - radius, y);
  280. ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  281. ctx.lineTo(x + width, y + height - radius);
  282. ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  283. ctx.lineTo(x + radius, y + height);
  284. ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  285. ctx.lineTo(x, y + radius);
  286. ctx.quadraticCurveTo(x, y, x + radius, y);
  287. ctx.closePath();
  288. ctx.fill();
  289. }
  290. /**
  291. * Render the actual wave and progress lines
  292. *
  293. * @param {number[]} peaks Array with peaks data
  294. * @param {number} absmax Maximum peak value (absolute)
  295. * @param {number} halfH Half the height of the waveform
  296. * @param {number} offsetY Offset to the top
  297. * @param {number} start The x-offset of the beginning of the area that
  298. * should be rendered
  299. * @param {number} end The x-offset of the end of the area that
  300. * should be rendered
  301. */
  302. }, {
  303. key: "drawLines",
  304. value: function drawLines(peaks, absmax, halfH, offsetY, start, end) {
  305. this.drawLineToContext(this.waveCtx, peaks, absmax, halfH, offsetY, start, end);
  306. if (this.hasProgressCanvas) {
  307. this.drawLineToContext(this.progressCtx, peaks, absmax, halfH, offsetY, start, end);
  308. }
  309. }
  310. /**
  311. * Render the actual waveform line on a `canvas` element
  312. *
  313. * @param {CanvasRenderingContext2D} ctx Rendering context of target canvas
  314. * @param {number[]} peaks Array with peaks data
  315. * @param {number} absmax Maximum peak value (absolute)
  316. * @param {number} halfH Half the height of the waveform
  317. * @param {number} offsetY Offset to the top
  318. * @param {number} start The x-offset of the beginning of the area that
  319. * should be rendered
  320. * @param {number} end The x-offset of the end of the area that
  321. * should be rendered
  322. */
  323. }, {
  324. key: "drawLineToContext",
  325. value: function drawLineToContext(ctx, peaks, absmax, halfH, offsetY, start, end) {
  326. if (!ctx) {
  327. return;
  328. }
  329. var length = peaks.length / 2;
  330. var first = Math.round(length * this.start); // use one more peak value to make sure we join peaks at ends -- unless,
  331. // of course, this is the last canvas
  332. var last = Math.round(length * this.end) + 1;
  333. var canvasStart = first;
  334. var canvasEnd = last;
  335. var scale = this.wave.width / (canvasEnd - canvasStart - 1); // optimization
  336. var halfOffset = halfH + offsetY;
  337. var absmaxHalf = absmax / halfH;
  338. ctx.beginPath();
  339. ctx.moveTo((canvasStart - first) * scale, halfOffset);
  340. ctx.lineTo((canvasStart - first) * scale, halfOffset - Math.round((peaks[2 * canvasStart] || 0) / absmaxHalf));
  341. var i, peak, h;
  342. for (i = canvasStart; i < canvasEnd; i++) {
  343. peak = peaks[2 * i] || 0;
  344. h = Math.round(peak / absmaxHalf);
  345. ctx.lineTo((i - first) * scale + this.halfPixel, halfOffset - h);
  346. } // draw the bottom edge going backwards, to make a single
  347. // closed hull to fill
  348. var j = canvasEnd - 1;
  349. for (j; j >= canvasStart; j--) {
  350. peak = peaks[2 * j + 1] || 0;
  351. h = Math.round(peak / absmaxHalf);
  352. ctx.lineTo((j - first) * scale + this.halfPixel, halfOffset - h);
  353. }
  354. ctx.lineTo((canvasStart - first) * scale, halfOffset - Math.round((peaks[2 * canvasStart + 1] || 0) / absmaxHalf));
  355. ctx.closePath();
  356. ctx.fill();
  357. }
  358. /**
  359. * Destroys this entry
  360. */
  361. }, {
  362. key: "destroy",
  363. value: function destroy() {
  364. this.waveCtx = null;
  365. this.wave = null;
  366. this.progressCtx = null;
  367. this.progress = null;
  368. }
  369. /**
  370. * Return image data of the wave `canvas` element
  371. *
  372. * When using a `type` of `'blob'`, this will return a `Promise` that
  373. * resolves with a `Blob` instance.
  374. *
  375. * @param {string} format='image/png' An optional value of a format type.
  376. * @param {number} quality=0.92 An optional value between 0 and 1.
  377. * @param {string} type='dataURL' Either 'dataURL' or 'blob'.
  378. * @return {string|Promise} When using the default `'dataURL'` `type` this
  379. * returns a data URL. When using the `'blob'` `type` this returns a
  380. * `Promise` that resolves with a `Blob` instance.
  381. */
  382. }, {
  383. key: "getImage",
  384. value: function getImage(format, quality, type) {
  385. var _this = this;
  386. if (type === 'blob') {
  387. return new Promise(function (resolve) {
  388. _this.wave.toBlob(resolve, format, quality);
  389. });
  390. } else if (type === 'dataURL') {
  391. return this.wave.toDataURL(format, quality);
  392. }
  393. }
  394. }]);
  395. return CanvasEntry;
  396. }();
  397. exports["default"] = CanvasEntry;
  398. module.exports = exports.default;
  399. /***/ }),
  400. /***/ "./src/drawer.js":
  401. /*!***********************!*\
  402. !*** ./src/drawer.js ***!
  403. \***********************/
  404. /***/ ((module, exports, __webpack_require__) => {
  405. "use strict";
  406. function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
  407. Object.defineProperty(exports, "__esModule", ({
  408. value: true
  409. }));
  410. exports["default"] = void 0;
  411. var util = _interopRequireWildcard(__webpack_require__(/*! ./util */ "./src/util/index.js"));
  412. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  413. function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  414. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  415. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  416. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  417. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
  418. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  419. function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
  420. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
  421. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  422. function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
  423. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  424. /**
  425. * Parent class for renderers
  426. *
  427. * @extends {Observer}
  428. */
  429. var Drawer = /*#__PURE__*/function (_util$Observer) {
  430. _inherits(Drawer, _util$Observer);
  431. var _super = _createSuper(Drawer);
  432. /**
  433. * @param {HTMLElement} container The container node of the wavesurfer instance
  434. * @param {WavesurferParams} params The wavesurfer initialisation options
  435. */
  436. function Drawer(container, params) {
  437. var _this;
  438. _classCallCheck(this, Drawer);
  439. _this = _super.call(this);
  440. _this.container = util.withOrientation(container, params.vertical);
  441. /**
  442. * @type {WavesurferParams}
  443. */
  444. _this.params = params;
  445. /**
  446. * The width of the renderer
  447. * @type {number}
  448. */
  449. _this.width = 0;
  450. /**
  451. * The height of the renderer
  452. * @type {number}
  453. */
  454. _this.height = params.height * _this.params.pixelRatio;
  455. _this.lastPos = 0;
  456. /**
  457. * The `<wave>` element which is added to the container
  458. * @type {HTMLElement}
  459. */
  460. _this.wrapper = null;
  461. return _this;
  462. }
  463. /**
  464. * Alias of `util.style`
  465. *
  466. * @param {HTMLElement} el The element that the styles will be applied to
  467. * @param {Object} styles The map of propName: attribute, both are used as-is
  468. * @return {HTMLElement} el
  469. */
  470. _createClass(Drawer, [{
  471. key: "style",
  472. value: function style(el, styles) {
  473. return util.style(el, styles);
  474. }
  475. /**
  476. * Create the wrapper `<wave>` element, style it and set up the events for
  477. * interaction
  478. */
  479. }, {
  480. key: "createWrapper",
  481. value: function createWrapper() {
  482. this.wrapper = util.withOrientation(this.container.appendChild(document.createElement('wave')), this.params.vertical);
  483. this.style(this.wrapper, {
  484. display: 'block',
  485. position: 'relative',
  486. userSelect: 'none',
  487. webkitUserSelect: 'none',
  488. height: this.params.height + 'px'
  489. });
  490. if (this.params.fillParent || this.params.scrollParent) {
  491. this.style(this.wrapper, {
  492. width: '100%',
  493. cursor: this.params.hideCursor ? 'none' : 'auto',
  494. overflowX: this.params.hideScrollbar ? 'hidden' : 'auto',
  495. overflowY: 'hidden'
  496. });
  497. }
  498. this.setupWrapperEvents();
  499. }
  500. /**
  501. * Handle click event
  502. *
  503. * @param {Event} e Click event
  504. * @param {?boolean} noPrevent Set to true to not call `e.preventDefault()`
  505. * @return {number} Playback position from 0 to 1
  506. */
  507. }, {
  508. key: "handleEvent",
  509. value: function handleEvent(e, noPrevent) {
  510. !noPrevent && e.preventDefault();
  511. var clientX = util.withOrientation(e.targetTouches ? e.targetTouches[0] : e, this.params.vertical).clientX;
  512. var bbox = this.wrapper.getBoundingClientRect();
  513. var nominalWidth = this.width;
  514. var parentWidth = this.getWidth();
  515. var progressPixels = this.getProgressPixels(bbox, clientX);
  516. var progress;
  517. if (!this.params.fillParent && nominalWidth < parentWidth) {
  518. progress = progressPixels * (this.params.pixelRatio / nominalWidth) || 0;
  519. } else {
  520. progress = (progressPixels + this.wrapper.scrollLeft) / this.wrapper.scrollWidth || 0;
  521. }
  522. return util.clamp(progress, 0, 1);
  523. }
  524. }, {
  525. key: "getProgressPixels",
  526. value: function getProgressPixels(wrapperBbox, clientX) {
  527. if (this.params.rtl) {
  528. return wrapperBbox.right - clientX;
  529. } else {
  530. return clientX - wrapperBbox.left;
  531. }
  532. }
  533. }, {
  534. key: "setupWrapperEvents",
  535. value: function setupWrapperEvents() {
  536. var _this2 = this;
  537. this.wrapper.addEventListener('click', function (e) {
  538. var orientedEvent = util.withOrientation(e, _this2.params.vertical);
  539. var scrollbarHeight = _this2.wrapper.offsetHeight - _this2.wrapper.clientHeight;
  540. if (scrollbarHeight !== 0) {
  541. // scrollbar is visible. Check if click was on it
  542. var bbox = _this2.wrapper.getBoundingClientRect();
  543. if (orientedEvent.clientY >= bbox.bottom - scrollbarHeight) {
  544. // ignore mousedown as it was on the scrollbar
  545. return;
  546. }
  547. }
  548. if (_this2.params.interact) {
  549. _this2.fireEvent('click', e, _this2.handleEvent(e));
  550. }
  551. });
  552. this.wrapper.addEventListener('dblclick', function (e) {
  553. if (_this2.params.interact) {
  554. _this2.fireEvent('dblclick', e, _this2.handleEvent(e));
  555. }
  556. });
  557. this.wrapper.addEventListener('scroll', function (e) {
  558. return _this2.fireEvent('scroll', e);
  559. });
  560. }
  561. /**
  562. * Draw peaks on the canvas
  563. *
  564. * @param {number[]|Number.<Array[]>} peaks Can also be an array of arrays
  565. * for split channel rendering
  566. * @param {number} length The width of the area that should be drawn
  567. * @param {number} start The x-offset of the beginning of the area that
  568. * should be rendered
  569. * @param {number} end The x-offset of the end of the area that should be
  570. * rendered
  571. */
  572. }, {
  573. key: "drawPeaks",
  574. value: function drawPeaks(peaks, length, start, end) {
  575. if (!this.setWidth(length)) {
  576. this.clearWave();
  577. }
  578. this.params.barWidth ? this.drawBars(peaks, 0, start, end) : this.drawWave(peaks, 0, start, end);
  579. }
  580. /**
  581. * Scroll to the beginning
  582. */
  583. }, {
  584. key: "resetScroll",
  585. value: function resetScroll() {
  586. if (this.wrapper !== null) {
  587. this.wrapper.scrollLeft = 0;
  588. }
  589. }
  590. /**
  591. * Recenter the view-port at a certain percent of the waveform
  592. *
  593. * @param {number} percent Value from 0 to 1 on the waveform
  594. */
  595. }, {
  596. key: "recenter",
  597. value: function recenter(percent) {
  598. var position = this.wrapper.scrollWidth * percent;
  599. this.recenterOnPosition(position, true);
  600. }
  601. /**
  602. * Recenter the view-port on a position, either scroll there immediately or
  603. * in steps of 5 pixels
  604. *
  605. * @param {number} position X-offset in pixels
  606. * @param {boolean} immediate Set to true to immediately scroll somewhere
  607. */
  608. }, {
  609. key: "recenterOnPosition",
  610. value: function recenterOnPosition(position, immediate) {
  611. var scrollLeft = this.wrapper.scrollLeft;
  612. var half = ~~(this.wrapper.clientWidth / 2);
  613. var maxScroll = this.wrapper.scrollWidth - this.wrapper.clientWidth;
  614. var target = position - half;
  615. var offset = target - scrollLeft;
  616. if (maxScroll == 0) {
  617. // no need to continue if scrollbar is not there
  618. return;
  619. } // if the cursor is currently visible...
  620. if (!immediate && -half <= offset && offset < half) {
  621. // set rate at which waveform is centered
  622. var rate = this.params.autoCenterRate; // make rate depend on width of view and length of waveform
  623. rate /= half;
  624. rate *= maxScroll;
  625. offset = Math.max(-rate, Math.min(rate, offset));
  626. target = scrollLeft + offset;
  627. } // limit target to valid range (0 to maxScroll)
  628. target = Math.max(0, Math.min(maxScroll, target)); // no use attempting to scroll if we're not moving
  629. if (target != scrollLeft) {
  630. this.wrapper.scrollLeft = target;
  631. }
  632. }
  633. /**
  634. * Get the current scroll position in pixels
  635. *
  636. * @return {number} Horizontal scroll position in pixels
  637. */
  638. }, {
  639. key: "getScrollX",
  640. value: function getScrollX() {
  641. var x = 0;
  642. if (this.wrapper) {
  643. var pixelRatio = this.params.pixelRatio;
  644. x = Math.round(this.wrapper.scrollLeft * pixelRatio); // In cases of elastic scroll (safari with mouse wheel) you can
  645. // scroll beyond the limits of the container
  646. // Calculate and floor the scrollable extent to make sure an out
  647. // of bounds value is not returned
  648. // Ticket #1312
  649. if (this.params.scrollParent) {
  650. var maxScroll = ~~(this.wrapper.scrollWidth * pixelRatio - this.getWidth());
  651. x = Math.min(maxScroll, Math.max(0, x));
  652. }
  653. }
  654. return x;
  655. }
  656. /**
  657. * Get the width of the container
  658. *
  659. * @return {number} The width of the container
  660. */
  661. }, {
  662. key: "getWidth",
  663. value: function getWidth() {
  664. return Math.round(this.container.clientWidth * this.params.pixelRatio);
  665. }
  666. /**
  667. * Set the width of the container
  668. *
  669. * @param {number} width The new width of the container
  670. * @return {boolean} Whether the width of the container was updated or not
  671. */
  672. }, {
  673. key: "setWidth",
  674. value: function setWidth(width) {
  675. if (this.width == width) {
  676. return false;
  677. }
  678. this.width = width;
  679. if (this.params.fillParent || this.params.scrollParent) {
  680. this.style(this.wrapper, {
  681. width: ''
  682. });
  683. } else {
  684. var newWidth = ~~(this.width / this.params.pixelRatio) + 'px';
  685. this.style(this.wrapper, {
  686. width: newWidth
  687. });
  688. }
  689. this.updateSize();
  690. return true;
  691. }
  692. /**
  693. * Set the height of the container
  694. *
  695. * @param {number} height The new height of the container.
  696. * @return {boolean} Whether the height of the container was updated or not
  697. */
  698. }, {
  699. key: "setHeight",
  700. value: function setHeight(height) {
  701. if (height == this.height) {
  702. return false;
  703. }
  704. this.height = height;
  705. this.style(this.wrapper, {
  706. height: ~~(this.height / this.params.pixelRatio) + 'px'
  707. });
  708. this.updateSize();
  709. return true;
  710. }
  711. /**
  712. * Called by wavesurfer when progress should be rendered
  713. *
  714. * @param {number} progress From 0 to 1
  715. */
  716. }, {
  717. key: "progress",
  718. value: function progress(_progress) {
  719. var minPxDelta = 1 / this.params.pixelRatio;
  720. var pos = Math.round(_progress * this.width) * minPxDelta;
  721. if (pos < this.lastPos || pos - this.lastPos >= minPxDelta) {
  722. this.lastPos = pos;
  723. if (this.params.scrollParent && this.params.autoCenter) {
  724. var newPos = ~~(this.wrapper.scrollWidth * _progress);
  725. this.recenterOnPosition(newPos, this.params.autoCenterImmediately);
  726. }
  727. this.updateProgress(pos);
  728. }
  729. }
  730. /**
  731. * This is called when wavesurfer is destroyed
  732. */
  733. }, {
  734. key: "destroy",
  735. value: function destroy() {
  736. this.unAll();
  737. if (this.wrapper) {
  738. if (this.wrapper.parentNode == this.container.domElement) {
  739. this.container.removeChild(this.wrapper.domElement);
  740. }
  741. this.wrapper = null;
  742. }
  743. }
  744. /* Renderer-specific methods */
  745. /**
  746. * Called after cursor related params have changed.
  747. *
  748. * @abstract
  749. */
  750. }, {
  751. key: "updateCursor",
  752. value: function updateCursor() {}
  753. /**
  754. * Called when the size of the container changes so the renderer can adjust
  755. *
  756. * @abstract
  757. */
  758. }, {
  759. key: "updateSize",
  760. value: function updateSize() {}
  761. /**
  762. * Draw a waveform with bars
  763. *
  764. * @abstract
  765. * @param {number[]|Number.<Array[]>} peaks Can also be an array of arrays for split channel
  766. * rendering
  767. * @param {number} channelIndex The index of the current channel. Normally
  768. * should be 0
  769. * @param {number} start The x-offset of the beginning of the area that
  770. * should be rendered
  771. * @param {number} end The x-offset of the end of the area that should be
  772. * rendered
  773. */
  774. }, {
  775. key: "drawBars",
  776. value: function drawBars(peaks, channelIndex, start, end) {}
  777. /**
  778. * Draw a waveform
  779. *
  780. * @abstract
  781. * @param {number[]|Number.<Array[]>} peaks Can also be an array of arrays for split channel
  782. * rendering
  783. * @param {number} channelIndex The index of the current channel. Normally
  784. * should be 0
  785. * @param {number} start The x-offset of the beginning of the area that
  786. * should be rendered
  787. * @param {number} end The x-offset of the end of the area that should be
  788. * rendered
  789. */
  790. }, {
  791. key: "drawWave",
  792. value: function drawWave(peaks, channelIndex, start, end) {}
  793. /**
  794. * Clear the waveform
  795. *
  796. * @abstract
  797. */
  798. }, {
  799. key: "clearWave",
  800. value: function clearWave() {}
  801. /**
  802. * Render the new progress
  803. *
  804. * @abstract
  805. * @param {number} position X-Offset of progress position in pixels
  806. */
  807. }, {
  808. key: "updateProgress",
  809. value: function updateProgress(position) {}
  810. }]);
  811. return Drawer;
  812. }(util.Observer);
  813. exports["default"] = Drawer;
  814. module.exports = exports.default;
  815. /***/ }),
  816. /***/ "./src/drawer.multicanvas.js":
  817. /*!***********************************!*\
  818. !*** ./src/drawer.multicanvas.js ***!
  819. \***********************************/
  820. /***/ ((module, exports, __webpack_require__) => {
  821. "use strict";
  822. function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
  823. Object.defineProperty(exports, "__esModule", ({
  824. value: true
  825. }));
  826. exports["default"] = void 0;
  827. var _drawer = _interopRequireDefault(__webpack_require__(/*! ./drawer */ "./src/drawer.js"));
  828. var util = _interopRequireWildcard(__webpack_require__(/*! ./util */ "./src/util/index.js"));
  829. var _drawer2 = _interopRequireDefault(__webpack_require__(/*! ./drawer.canvasentry */ "./src/drawer.canvasentry.js"));
  830. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  831. function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  832. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  833. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  834. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  835. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  836. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
  837. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  838. function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
  839. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
  840. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  841. function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
  842. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  843. /**
  844. * MultiCanvas renderer for wavesurfer. Is currently the default and sole
  845. * builtin renderer.
  846. *
  847. * A `MultiCanvas` consists of one or more `CanvasEntry` instances, depending
  848. * on the zoom level.
  849. */
  850. var MultiCanvas = /*#__PURE__*/function (_Drawer) {
  851. _inherits(MultiCanvas, _Drawer);
  852. var _super = _createSuper(MultiCanvas);
  853. /**
  854. * @param {HTMLElement} container The container node of the wavesurfer instance
  855. * @param {WavesurferParams} params The wavesurfer initialisation options
  856. */
  857. function MultiCanvas(container, params) {
  858. var _this;
  859. _classCallCheck(this, MultiCanvas);
  860. _this = _super.call(this, container, params);
  861. /**
  862. * @type {number}
  863. */
  864. _this.maxCanvasWidth = params.maxCanvasWidth;
  865. /**
  866. * @type {number}
  867. */
  868. _this.maxCanvasElementWidth = Math.round(params.maxCanvasWidth / params.pixelRatio);
  869. /**
  870. * Whether or not the progress wave is rendered. If the `waveColor`
  871. * and `progressColor` are the same color it is not.
  872. *
  873. * @type {boolean}
  874. */
  875. _this.hasProgressCanvas = params.waveColor != params.progressColor;
  876. /**
  877. * @type {number}
  878. */
  879. _this.halfPixel = 0.5 / params.pixelRatio;
  880. /**
  881. * List of `CanvasEntry` instances.
  882. *
  883. * @type {Array}
  884. */
  885. _this.canvases = [];
  886. /**
  887. * @type {HTMLElement}
  888. */
  889. _this.progressWave = null;
  890. /**
  891. * Class used to generate entries.
  892. *
  893. * @type {function}
  894. */
  895. _this.EntryClass = _drawer2.default;
  896. /**
  897. * Canvas 2d context attributes.
  898. *
  899. * @type {object}
  900. */
  901. _this.canvasContextAttributes = params.drawingContextAttributes;
  902. /**
  903. * Overlap added between entries to prevent vertical white stripes
  904. * between `canvas` elements.
  905. *
  906. * @type {number}
  907. */
  908. _this.overlap = 2 * Math.ceil(params.pixelRatio / 2);
  909. /**
  910. * The radius of the wave bars. Makes bars rounded
  911. *
  912. * @type {number}
  913. */
  914. _this.barRadius = params.barRadius || 0;
  915. /**
  916. * Whether to render the waveform vertically. Defaults to false.
  917. *
  918. * @type {boolean}
  919. */
  920. _this.vertical = params.vertical;
  921. return _this;
  922. }
  923. /**
  924. * Initialize the drawer
  925. */
  926. _createClass(MultiCanvas, [{
  927. key: "init",
  928. value: function init() {
  929. this.createWrapper();
  930. this.createElements();
  931. }
  932. /**
  933. * Create the canvas elements and style them
  934. *
  935. */
  936. }, {
  937. key: "createElements",
  938. value: function createElements() {
  939. this.progressWave = util.withOrientation(this.wrapper.appendChild(document.createElement('wave')), this.params.vertical);
  940. this.style(this.progressWave, {
  941. position: 'absolute',
  942. zIndex: 3,
  943. left: 0,
  944. top: 0,
  945. bottom: 0,
  946. overflow: 'hidden',
  947. width: '0',
  948. display: 'none',
  949. boxSizing: 'border-box',
  950. borderRightStyle: 'solid',
  951. pointerEvents: 'none'
  952. });
  953. this.addCanvas();
  954. this.updateCursor();
  955. }
  956. /**
  957. * Update cursor style
  958. */
  959. }, {
  960. key: "updateCursor",
  961. value: function updateCursor() {
  962. this.style(this.progressWave, {
  963. borderRightWidth: this.params.cursorWidth + 'px',
  964. borderRightColor: this.params.cursorColor
  965. });
  966. }
  967. /**
  968. * Adjust to the updated size by adding or removing canvases
  969. */
  970. }, {
  971. key: "updateSize",
  972. value: function updateSize() {
  973. var _this2 = this;
  974. var totalWidth = Math.round(this.width / this.params.pixelRatio);
  975. var requiredCanvases = Math.ceil(totalWidth / (this.maxCanvasElementWidth + this.overlap)); // add required canvases
  976. while (this.canvases.length < requiredCanvases) {
  977. this.addCanvas();
  978. } // remove older existing canvases, if any
  979. while (this.canvases.length > requiredCanvases) {
  980. this.removeCanvas();
  981. }
  982. var canvasWidth = this.maxCanvasWidth + this.overlap;
  983. var lastCanvas = this.canvases.length - 1;
  984. this.canvases.forEach(function (entry, i) {
  985. if (i == lastCanvas) {
  986. canvasWidth = _this2.width - _this2.maxCanvasWidth * lastCanvas;
  987. }
  988. _this2.updateDimensions(entry, canvasWidth, _this2.height);
  989. entry.clearWave();
  990. });
  991. }
  992. /**
  993. * Add a canvas to the canvas list
  994. *
  995. */
  996. }, {
  997. key: "addCanvas",
  998. value: function addCanvas() {
  999. var entry = new this.EntryClass();
  1000. entry.canvasContextAttributes = this.canvasContextAttributes;
  1001. entry.hasProgressCanvas = this.hasProgressCanvas;
  1002. entry.halfPixel = this.halfPixel;
  1003. var leftOffset = this.maxCanvasElementWidth * this.canvases.length; // wave
  1004. var wave = util.withOrientation(this.wrapper.appendChild(document.createElement('canvas')), this.params.vertical);
  1005. this.style(wave, {
  1006. position: 'absolute',
  1007. zIndex: 2,
  1008. left: leftOffset + 'px',
  1009. top: 0,
  1010. bottom: 0,
  1011. height: '100%',
  1012. pointerEvents: 'none'
  1013. });
  1014. entry.initWave(wave); // progress
  1015. if (this.hasProgressCanvas) {
  1016. var progress = util.withOrientation(this.progressWave.appendChild(document.createElement('canvas')), this.params.vertical);
  1017. this.style(progress, {
  1018. position: 'absolute',
  1019. left: leftOffset + 'px',
  1020. top: 0,
  1021. bottom: 0,
  1022. height: '100%'
  1023. });
  1024. entry.initProgress(progress);
  1025. }
  1026. this.canvases.push(entry);
  1027. }
  1028. /**
  1029. * Pop single canvas from the list
  1030. *
  1031. */
  1032. }, {
  1033. key: "removeCanvas",
  1034. value: function removeCanvas() {
  1035. var lastEntry = this.canvases[this.canvases.length - 1]; // wave
  1036. lastEntry.wave.parentElement.removeChild(lastEntry.wave.domElement); // progress
  1037. if (this.hasProgressCanvas) {
  1038. lastEntry.progress.parentElement.removeChild(lastEntry.progress.domElement);
  1039. } // cleanup
  1040. if (lastEntry) {
  1041. lastEntry.destroy();
  1042. lastEntry = null;
  1043. }
  1044. this.canvases.pop();
  1045. }
  1046. /**
  1047. * Update the dimensions of a canvas element
  1048. *
  1049. * @param {CanvasEntry} entry Target entry
  1050. * @param {number} width The new width of the element
  1051. * @param {number} height The new height of the element
  1052. */
  1053. }, {
  1054. key: "updateDimensions",
  1055. value: function updateDimensions(entry, width, height) {
  1056. var elementWidth = Math.round(width / this.params.pixelRatio);
  1057. var totalWidth = Math.round(this.width / this.params.pixelRatio); // update canvas dimensions
  1058. entry.updateDimensions(elementWidth, totalWidth, width, height); // style element
  1059. this.style(this.progressWave, {
  1060. display: 'block'
  1061. });
  1062. }
  1063. /**
  1064. * Clear the whole multi-canvas
  1065. */
  1066. }, {
  1067. key: "clearWave",
  1068. value: function clearWave() {
  1069. var _this3 = this;
  1070. util.frame(function () {
  1071. _this3.canvases.forEach(function (entry) {
  1072. return entry.clearWave();
  1073. });
  1074. })();
  1075. }
  1076. /**
  1077. * Draw a waveform with bars
  1078. *
  1079. * @param {number[]|Number.<Array[]>} peaks Can also be an array of arrays
  1080. * for split channel rendering
  1081. * @param {number} channelIndex The index of the current channel. Normally
  1082. * should be 0. Must be an integer.
  1083. * @param {number} start The x-offset of the beginning of the area that
  1084. * should be rendered
  1085. * @param {number} end The x-offset of the end of the area that should be
  1086. * rendered
  1087. * @returns {void}
  1088. */
  1089. }, {
  1090. key: "drawBars",
  1091. value: function drawBars(peaks, channelIndex, start, end) {
  1092. var _this4 = this;
  1093. return this.prepareDraw(peaks, channelIndex, start, end, function (_ref) {
  1094. var absmax = _ref.absmax,
  1095. hasMinVals = _ref.hasMinVals,
  1096. height = _ref.height,
  1097. offsetY = _ref.offsetY,
  1098. halfH = _ref.halfH,
  1099. peaks = _ref.peaks,
  1100. ch = _ref.channelIndex;
  1101. // if drawBars was called within ws.empty we don't pass a start and
  1102. // don't want anything to happen
  1103. if (start === undefined) {
  1104. return;
  1105. } // Skip every other value if there are negatives.
  1106. var peakIndexScale = hasMinVals ? 2 : 1;
  1107. var length = peaks.length / peakIndexScale;
  1108. var bar = _this4.params.barWidth * _this4.params.pixelRatio;
  1109. var gap = _this4.params.barGap === null ? Math.max(_this4.params.pixelRatio, ~~(bar / 2)) : Math.max(_this4.params.pixelRatio, _this4.params.barGap * _this4.params.pixelRatio);
  1110. var step = bar + gap;
  1111. var scale = length / _this4.width;
  1112. var first = start;
  1113. var last = end;
  1114. var peakIndex = first;
  1115. for (peakIndex; peakIndex < last; peakIndex += step) {
  1116. // search for the highest peak in the range this bar falls into
  1117. var peak = 0;
  1118. var peakIndexRange = Math.floor(peakIndex * scale) * peakIndexScale; // start index
  1119. var peakIndexEnd = Math.floor((peakIndex + step) * scale) * peakIndexScale;
  1120. do {
  1121. // do..while makes sure at least one peak is always evaluated
  1122. var newPeak = Math.abs(peaks[peakIndexRange]); // for arrays starting with negative values
  1123. if (newPeak > peak) {
  1124. peak = newPeak; // higher
  1125. }
  1126. peakIndexRange += peakIndexScale; // skip every other value for negatives
  1127. } while (peakIndexRange < peakIndexEnd); // calculate the height of this bar according to the highest peak found
  1128. var h = Math.round(peak / absmax * halfH); // in case of silences, allow the user to specify that we
  1129. // always draw *something* (normally a 1px high bar)
  1130. if (h == 0 && _this4.params.barMinHeight) {
  1131. h = _this4.params.barMinHeight;
  1132. }
  1133. _this4.fillRect(peakIndex + _this4.halfPixel, halfH - h + offsetY, bar + _this4.halfPixel, h * 2, _this4.barRadius, ch);
  1134. }
  1135. });
  1136. }
  1137. /**
  1138. * Draw a waveform
  1139. *
  1140. * @param {number[]|Number.<Array[]>} peaks Can also be an array of arrays
  1141. * for split channel rendering
  1142. * @param {number} channelIndex The index of the current channel. Normally
  1143. * should be 0
  1144. * @param {number?} start The x-offset of the beginning of the area that
  1145. * should be rendered (If this isn't set only a flat line is rendered)
  1146. * @param {number?} end The x-offset of the end of the area that should be
  1147. * rendered
  1148. * @returns {void}
  1149. */
  1150. }, {
  1151. key: "drawWave",
  1152. value: function drawWave(peaks, channelIndex, start, end) {
  1153. var _this5 = this;
  1154. return this.prepareDraw(peaks, channelIndex, start, end, function (_ref2) {
  1155. var absmax = _ref2.absmax,
  1156. hasMinVals = _ref2.hasMinVals,
  1157. height = _ref2.height,
  1158. offsetY = _ref2.offsetY,
  1159. halfH = _ref2.halfH,
  1160. peaks = _ref2.peaks,
  1161. channelIndex = _ref2.channelIndex;
  1162. if (!hasMinVals) {
  1163. var reflectedPeaks = [];
  1164. var len = peaks.length;
  1165. var i = 0;
  1166. for (i; i < len; i++) {
  1167. reflectedPeaks[2 * i] = peaks[i];
  1168. reflectedPeaks[2 * i + 1] = -peaks[i];
  1169. }
  1170. peaks = reflectedPeaks;
  1171. } // if drawWave was called within ws.empty we don't pass a start and
  1172. // end and simply want a flat line
  1173. if (start !== undefined) {
  1174. _this5.drawLine(peaks, absmax, halfH, offsetY, start, end, channelIndex);
  1175. } // always draw a median line
  1176. _this5.fillRect(0, halfH + offsetY - _this5.halfPixel, _this5.width, _this5.halfPixel, _this5.barRadius, channelIndex);
  1177. });
  1178. }
  1179. /**
  1180. * Tell the canvas entries to render their portion of the waveform
  1181. *
  1182. * @param {number[]} peaks Peaks data
  1183. * @param {number} absmax Maximum peak value (absolute)
  1184. * @param {number} halfH Half the height of the waveform
  1185. * @param {number} offsetY Offset to the top
  1186. * @param {number} start The x-offset of the beginning of the area that
  1187. * should be rendered
  1188. * @param {number} end The x-offset of the end of the area that
  1189. * should be rendered
  1190. * @param {channelIndex} channelIndex The channel index of the line drawn
  1191. */
  1192. }, {
  1193. key: "drawLine",
  1194. value: function drawLine(peaks, absmax, halfH, offsetY, start, end, channelIndex) {
  1195. var _this6 = this;
  1196. var _ref3 = this.params.splitChannelsOptions.channelColors[channelIndex] || {},
  1197. waveColor = _ref3.waveColor,
  1198. progressColor = _ref3.progressColor;
  1199. this.canvases.forEach(function (entry, i) {
  1200. _this6.setFillStyles(entry, waveColor, progressColor);
  1201. _this6.applyCanvasTransforms(entry, _this6.params.vertical);
  1202. entry.drawLines(peaks, absmax, halfH, offsetY, start, end);
  1203. });
  1204. }
  1205. /**
  1206. * Draw a rectangle on the multi-canvas
  1207. *
  1208. * @param {number} x X-position of the rectangle
  1209. * @param {number} y Y-position of the rectangle
  1210. * @param {number} width Width of the rectangle
  1211. * @param {number} height Height of the rectangle
  1212. * @param {number} radius Radius of the rectangle
  1213. * @param {channelIndex} channelIndex The channel index of the bar drawn
  1214. */
  1215. }, {
  1216. key: "fillRect",
  1217. value: function fillRect(x, y, width, height, radius, channelIndex) {
  1218. var startCanvas = Math.floor(x / this.maxCanvasWidth);
  1219. var endCanvas = Math.min(Math.ceil((x + width) / this.maxCanvasWidth) + 1, this.canvases.length);
  1220. var i = startCanvas;
  1221. for (i; i < endCanvas; i++) {
  1222. var entry = this.canvases[i];
  1223. var leftOffset = i * this.maxCanvasWidth;
  1224. var intersection = {
  1225. x1: Math.max(x, i * this.maxCanvasWidth),
  1226. y1: y,
  1227. x2: Math.min(x + width, i * this.maxCanvasWidth + entry.wave.width),
  1228. y2: y + height
  1229. };
  1230. if (intersection.x1 < intersection.x2) {
  1231. var _ref4 = this.params.splitChannelsOptions.channelColors[channelIndex] || {},
  1232. waveColor = _ref4.waveColor,
  1233. progressColor = _ref4.progressColor;
  1234. this.setFillStyles(entry, waveColor, progressColor);
  1235. this.applyCanvasTransforms(entry, this.params.vertical);
  1236. entry.fillRects(intersection.x1 - leftOffset, intersection.y1, intersection.x2 - intersection.x1, intersection.y2 - intersection.y1, radius);
  1237. }
  1238. }
  1239. }
  1240. /**
  1241. * Returns whether to hide the channel from being drawn based on params.
  1242. *
  1243. * @param {number} channelIndex The index of the current channel.
  1244. * @returns {bool} True to hide the channel, false to draw.
  1245. */
  1246. }, {
  1247. key: "hideChannel",
  1248. value: function hideChannel(channelIndex) {
  1249. return this.params.splitChannels && this.params.splitChannelsOptions.filterChannels.includes(channelIndex);
  1250. }
  1251. /**
  1252. * Performs preparation tasks and calculations which are shared by `drawBars`
  1253. * and `drawWave`
  1254. *
  1255. * @param {number[]|Number.<Array[]>} peaks Can also be an array of arrays for
  1256. * split channel rendering
  1257. * @param {number} channelIndex The index of the current channel. Normally
  1258. * should be 0
  1259. * @param {number?} start The x-offset of the beginning of the area that
  1260. * should be rendered. If this isn't set only a flat line is rendered
  1261. * @param {number?} end The x-offset of the end of the area that should be
  1262. * rendered
  1263. * @param {function} fn The render function to call, e.g. `drawWave`
  1264. * @param {number} drawIndex The index of the current channel after filtering.
  1265. * @param {number?} normalizedMax Maximum modulation value across channels for use with relativeNormalization. Ignored when undefined
  1266. * @returns {void}
  1267. */
  1268. }, {
  1269. key: "prepareDraw",
  1270. value: function prepareDraw(peaks, channelIndex, start, end, fn, drawIndex, normalizedMax) {
  1271. var _this7 = this;
  1272. return util.frame(function () {
  1273. // Split channels and call this function with the channelIndex set
  1274. if (peaks[0] instanceof Array) {
  1275. var channels = peaks;
  1276. if (_this7.params.splitChannels) {
  1277. var filteredChannels = channels.filter(function (c, i) {
  1278. return !_this7.hideChannel(i);
  1279. });
  1280. if (!_this7.params.splitChannelsOptions.overlay) {
  1281. _this7.setHeight(Math.max(filteredChannels.length, 1) * _this7.params.height * _this7.params.pixelRatio);
  1282. }
  1283. var overallAbsMax;
  1284. if (_this7.params.splitChannelsOptions && _this7.params.splitChannelsOptions.relativeNormalization) {
  1285. // calculate maximum peak across channels to use for normalization
  1286. overallAbsMax = util.max(channels.map(function (channelPeaks) {
  1287. return util.absMax(channelPeaks);
  1288. }));
  1289. }
  1290. return channels.forEach(function (channelPeaks, i) {
  1291. return _this7.prepareDraw(channelPeaks, i, start, end, fn, filteredChannels.indexOf(channelPeaks), overallAbsMax);
  1292. });
  1293. }
  1294. peaks = channels[0];
  1295. } // Return and do not draw channel peaks if hidden.
  1296. if (_this7.hideChannel(channelIndex)) {
  1297. return;
  1298. } // calculate maximum modulation value, either from the barHeight
  1299. // parameter or if normalize=true from the largest value in the peak
  1300. // set
  1301. var absmax = 1 / _this7.params.barHeight;
  1302. if (_this7.params.normalize) {
  1303. absmax = normalizedMax === undefined ? util.absMax(peaks) : normalizedMax;
  1304. } // Bar wave draws the bottom only as a reflection of the top,
  1305. // so we don't need negative values
  1306. var hasMinVals = [].some.call(peaks, function (val) {
  1307. return val < 0;
  1308. });
  1309. var height = _this7.params.height * _this7.params.pixelRatio;
  1310. var halfH = height / 2;
  1311. var offsetY = height * drawIndex || 0; // Override offsetY if overlay is true
  1312. if (_this7.params.splitChannelsOptions && _this7.params.splitChannelsOptions.overlay) {
  1313. offsetY = 0;
  1314. }
  1315. return fn({
  1316. absmax: absmax,
  1317. hasMinVals: hasMinVals,
  1318. height: height,
  1319. offsetY: offsetY,
  1320. halfH: halfH,
  1321. peaks: peaks,
  1322. channelIndex: channelIndex
  1323. });
  1324. })();
  1325. }
  1326. /**
  1327. * Set the fill styles for a certain entry (wave and progress)
  1328. *
  1329. * @param {CanvasEntry} entry Target entry
  1330. * @param {string} waveColor Wave color to draw this entry
  1331. * @param {string} progressColor Progress color to draw this entry
  1332. */
  1333. }, {
  1334. key: "setFillStyles",
  1335. value: function setFillStyles(entry) {
  1336. var waveColor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.params.waveColor;
  1337. var progressColor = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.params.progressColor;
  1338. entry.setFillStyles(waveColor, progressColor);
  1339. }
  1340. /**
  1341. * Set the canvas transforms for a certain entry (wave and progress)
  1342. *
  1343. * @param {CanvasEntry} entry Target entry
  1344. * @param {boolean} vertical Whether to render the waveform vertically
  1345. */
  1346. }, {
  1347. key: "applyCanvasTransforms",
  1348. value: function applyCanvasTransforms(entry) {
  1349. var vertical = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
  1350. entry.applyCanvasTransforms(vertical);
  1351. }
  1352. /**
  1353. * Return image data of the multi-canvas
  1354. *
  1355. * When using a `type` of `'blob'`, this will return a `Promise`.
  1356. *
  1357. * @param {string} format='image/png' An optional value of a format type.
  1358. * @param {number} quality=0.92 An optional value between 0 and 1.
  1359. * @param {string} type='dataURL' Either 'dataURL' or 'blob'.
  1360. * @return {string|string[]|Promise} When using the default `'dataURL'`
  1361. * `type` this returns a single data URL or an array of data URLs,
  1362. * one for each canvas. When using the `'blob'` `type` this returns a
  1363. * `Promise` that resolves with an array of `Blob` instances, one for each
  1364. * canvas.
  1365. */
  1366. }, {
  1367. key: "getImage",
  1368. value: function getImage(format, quality, type) {
  1369. if (type === 'blob') {
  1370. return Promise.all(this.canvases.map(function (entry) {
  1371. return entry.getImage(format, quality, type);
  1372. }));
  1373. } else if (type === 'dataURL') {
  1374. var images = this.canvases.map(function (entry) {
  1375. return entry.getImage(format, quality, type);
  1376. });
  1377. return images.length > 1 ? images : images[0];
  1378. }
  1379. }
  1380. /**
  1381. * Render the new progress
  1382. *
  1383. * @param {number} position X-offset of progress position in pixels
  1384. */
  1385. }, {
  1386. key: "updateProgress",
  1387. value: function updateProgress(position) {
  1388. this.style(this.progressWave, {
  1389. width: position + 'px'
  1390. });
  1391. }
  1392. }]);
  1393. return MultiCanvas;
  1394. }(_drawer.default);
  1395. exports["default"] = MultiCanvas;
  1396. module.exports = exports.default;
  1397. /***/ }),
  1398. /***/ "./src/mediaelement-webaudio.js":
  1399. /*!**************************************!*\
  1400. !*** ./src/mediaelement-webaudio.js ***!
  1401. \**************************************/
  1402. /***/ ((module, exports, __webpack_require__) => {
  1403. "use strict";
  1404. function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
  1405. Object.defineProperty(exports, "__esModule", ({
  1406. value: true
  1407. }));
  1408. exports["default"] = void 0;
  1409. var _mediaelement = _interopRequireDefault(__webpack_require__(/*! ./mediaelement */ "./src/mediaelement.js"));
  1410. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1411. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1412. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  1413. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  1414. function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); }
  1415. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  1416. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
  1417. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  1418. function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
  1419. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
  1420. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  1421. function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
  1422. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  1423. /**
  1424. * MediaElementWebAudio backend: load audio via an HTML5 audio tag, but playback with the WebAudio API.
  1425. * The advantage here is that the html5 <audio> tag can perform range requests on the server and not
  1426. * buffer the entire file in one request, and you still get the filtering and scripting functionality
  1427. * of the webaudio API.
  1428. * Note that in order to use range requests and prevent buffering, you must provide peak data.
  1429. *
  1430. * @since 3.2.0
  1431. */
  1432. var MediaElementWebAudio = /*#__PURE__*/function (_MediaElement) {
  1433. _inherits(MediaElementWebAudio, _MediaElement);
  1434. var _super = _createSuper(MediaElementWebAudio);
  1435. /**
  1436. * Construct the backend
  1437. *
  1438. * @param {WavesurferParams} params Wavesurfer parameters
  1439. */
  1440. function MediaElementWebAudio(params) {
  1441. var _this;
  1442. _classCallCheck(this, MediaElementWebAudio);
  1443. _this = _super.call(this, params);
  1444. /** @private */
  1445. _this.params = params;
  1446. /** @private */
  1447. _this.sourceMediaElement = null;
  1448. return _this;
  1449. }
  1450. /**
  1451. * Initialise the backend, called in `wavesurfer.createBackend()`
  1452. */
  1453. _createClass(MediaElementWebAudio, [{
  1454. key: "init",
  1455. value: function init() {
  1456. this.setPlaybackRate(this.params.audioRate);
  1457. this.createTimer();
  1458. this.createVolumeNode();
  1459. this.createScriptNode();
  1460. this.createAnalyserNode();
  1461. }
  1462. /**
  1463. * Private method called by both `load` (from url)
  1464. * and `loadElt` (existing media element) methods.
  1465. *
  1466. * @param {HTMLMediaElement} media HTML5 Audio or Video element
  1467. * @param {number[]|Number.<Array[]>} peaks Array of peak data
  1468. * @param {string} preload HTML 5 preload attribute value
  1469. * @private
  1470. */
  1471. }, {
  1472. key: "_load",
  1473. value: function _load(media, peaks, preload) {
  1474. _get(_getPrototypeOf(MediaElementWebAudio.prototype), "_load", this).call(this, media, peaks, preload);
  1475. this.createMediaElementSource(media);
  1476. }
  1477. /**
  1478. * Create MediaElementSource node
  1479. *
  1480. * @since 3.2.0
  1481. * @param {HTMLMediaElement} mediaElement HTML5 Audio to load
  1482. */
  1483. }, {
  1484. key: "createMediaElementSource",
  1485. value: function createMediaElementSource(mediaElement) {
  1486. this.sourceMediaElement = this.ac.createMediaElementSource(mediaElement);
  1487. this.sourceMediaElement.connect(this.analyser);
  1488. }
  1489. }, {
  1490. key: "play",
  1491. value: function play(start, end) {
  1492. this.resumeAudioContext();
  1493. return _get(_getPrototypeOf(MediaElementWebAudio.prototype), "play", this).call(this, start, end);
  1494. }
  1495. /**
  1496. * This is called when wavesurfer is destroyed
  1497. *
  1498. */
  1499. }, {
  1500. key: "destroy",
  1501. value: function destroy() {
  1502. _get(_getPrototypeOf(MediaElementWebAudio.prototype), "destroy", this).call(this);
  1503. this.destroyWebAudio();
  1504. }
  1505. }]);
  1506. return MediaElementWebAudio;
  1507. }(_mediaelement.default);
  1508. exports["default"] = MediaElementWebAudio;
  1509. module.exports = exports.default;
  1510. /***/ }),
  1511. /***/ "./src/mediaelement.js":
  1512. /*!*****************************!*\
  1513. !*** ./src/mediaelement.js ***!
  1514. \*****************************/
  1515. /***/ ((module, exports, __webpack_require__) => {
  1516. "use strict";
  1517. function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
  1518. Object.defineProperty(exports, "__esModule", ({
  1519. value: true
  1520. }));
  1521. exports["default"] = void 0;
  1522. var _webaudio = _interopRequireDefault(__webpack_require__(/*! ./webaudio */ "./src/webaudio.js"));
  1523. var util = _interopRequireWildcard(__webpack_require__(/*! ./util */ "./src/util/index.js"));
  1524. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  1525. function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  1526. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1527. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1528. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  1529. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  1530. function _get() { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(arguments.length < 3 ? target : receiver); } return desc.value; }; } return _get.apply(this, arguments); }
  1531. function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
  1532. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
  1533. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  1534. function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
  1535. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
  1536. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  1537. function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
  1538. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  1539. /**
  1540. * MediaElement backend
  1541. */
  1542. var MediaElement = /*#__PURE__*/function (_WebAudio) {
  1543. _inherits(MediaElement, _WebAudio);
  1544. var _super = _createSuper(MediaElement);
  1545. /**
  1546. * Construct the backend
  1547. *
  1548. * @param {WavesurferParams} params Wavesurfer parameters
  1549. */
  1550. function MediaElement(params) {
  1551. var _this;
  1552. _classCallCheck(this, MediaElement);
  1553. _this = _super.call(this, params);
  1554. /** @private */
  1555. _this.params = params;
  1556. /**
  1557. * Initially a dummy media element to catch errors. Once `_load` is
  1558. * called, this will contain the actual `HTMLMediaElement`.
  1559. * @private
  1560. */
  1561. _this.media = {
  1562. currentTime: 0,
  1563. duration: 0,
  1564. paused: true,
  1565. playbackRate: 1,
  1566. play: function play() {},
  1567. pause: function pause() {},
  1568. volume: 0
  1569. };
  1570. /** @private */
  1571. _this.mediaType = params.mediaType.toLowerCase();
  1572. /** @private */
  1573. _this.elementPosition = params.elementPosition;
  1574. /** @private */
  1575. _this.peaks = null;
  1576. /** @private */
  1577. _this.playbackRate = 1;
  1578. /** @private */
  1579. _this.volume = 1;
  1580. /** @private */
  1581. _this.isMuted = false;
  1582. /** @private */
  1583. _this.buffer = null;
  1584. /** @private */
  1585. _this.onPlayEnd = null;
  1586. /** @private */
  1587. _this.mediaListeners = {};
  1588. return _this;
  1589. }
  1590. /**
  1591. * Initialise the backend, called in `wavesurfer.createBackend()`
  1592. */
  1593. _createClass(MediaElement, [{
  1594. key: "init",
  1595. value: function init() {
  1596. this.setPlaybackRate(this.params.audioRate);
  1597. this.createTimer();
  1598. }
  1599. /**
  1600. * Attach event listeners to media element.
  1601. */
  1602. }, {
  1603. key: "_setupMediaListeners",
  1604. value: function _setupMediaListeners() {
  1605. var _this2 = this;
  1606. this.mediaListeners.error = function () {
  1607. _this2.fireEvent('error', 'Error loading media element');
  1608. };
  1609. this.mediaListeners.canplay = function () {
  1610. _this2.fireEvent('canplay');
  1611. };
  1612. this.mediaListeners.ended = function () {
  1613. _this2.fireEvent('finish');
  1614. }; // listen to and relay play, pause and seeked events to enable
  1615. // playback control from the external media element
  1616. this.mediaListeners.play = function () {
  1617. _this2.fireEvent('play');
  1618. };
  1619. this.mediaListeners.pause = function () {
  1620. _this2.fireEvent('pause');
  1621. };
  1622. this.mediaListeners.seeked = function (event) {
  1623. _this2.fireEvent('seek');
  1624. };
  1625. this.mediaListeners.volumechange = function (event) {
  1626. _this2.isMuted = _this2.media.muted;
  1627. if (_this2.isMuted) {
  1628. _this2.volume = 0;
  1629. } else {
  1630. _this2.volume = _this2.media.volume;
  1631. }
  1632. _this2.fireEvent('volume');
  1633. }; // reset event listeners
  1634. Object.keys(this.mediaListeners).forEach(function (id) {
  1635. _this2.media.removeEventListener(id, _this2.mediaListeners[id]);
  1636. _this2.media.addEventListener(id, _this2.mediaListeners[id]);
  1637. });
  1638. }
  1639. /**
  1640. * Create a timer to provide a more precise `audioprocess` event.
  1641. */
  1642. }, {
  1643. key: "createTimer",
  1644. value: function createTimer() {
  1645. var _this3 = this;
  1646. var onAudioProcess = function onAudioProcess() {
  1647. if (_this3.isPaused()) {
  1648. return;
  1649. }
  1650. _this3.fireEvent('audioprocess', _this3.getCurrentTime()); // Call again in the next frame
  1651. util.frame(onAudioProcess)();
  1652. };
  1653. this.on('play', onAudioProcess); // Update the progress one more time to prevent it from being stuck in
  1654. // case of lower framerates
  1655. this.on('pause', function () {
  1656. _this3.fireEvent('audioprocess', _this3.getCurrentTime());
  1657. });
  1658. }
  1659. /**
  1660. * Create media element with url as its source,
  1661. * and append to container element.
  1662. *
  1663. * @param {string} url Path to media file
  1664. * @param {HTMLElement} container HTML element
  1665. * @param {number[]|Number.<Array[]>} peaks Array of peak data
  1666. * @param {string} preload HTML 5 preload attribute value
  1667. * @throws Will throw an error if the `url` argument is not a valid media
  1668. * element.
  1669. */
  1670. }, {
  1671. key: "load",
  1672. value: function load(url, container, peaks, preload) {
  1673. var media = document.createElement(this.mediaType);
  1674. media.controls = this.params.mediaControls;
  1675. media.autoplay = this.params.autoplay || false;
  1676. media.preload = preload == null ? 'auto' : preload;
  1677. media.src = url;
  1678. media.style.width = '100%';
  1679. var prevMedia = container.querySelector(this.mediaType);
  1680. if (prevMedia) {
  1681. container.removeChild(prevMedia);
  1682. }
  1683. container.appendChild(media);
  1684. this._load(media, peaks, preload);
  1685. }
  1686. /**
  1687. * Load existing media element.
  1688. *
  1689. * @param {HTMLMediaElement} elt HTML5 Audio or Video element
  1690. * @param {number[]|Number.<Array[]>} peaks Array of peak data
  1691. */
  1692. }, {
  1693. key: "loadElt",
  1694. value: function loadElt(elt, peaks) {
  1695. elt.controls = this.params.mediaControls;
  1696. elt.autoplay = this.params.autoplay || false;
  1697. this._load(elt, peaks, elt.preload);
  1698. }
  1699. /**
  1700. * Method called by both `load` (from url)
  1701. * and `loadElt` (existing media element) methods.
  1702. *
  1703. * @param {HTMLMediaElement} media HTML5 Audio or Video element
  1704. * @param {number[]|Number.<Array[]>} peaks Array of peak data
  1705. * @param {string} preload HTML 5 preload attribute value
  1706. * @throws Will throw an error if the `media` argument is not a valid media
  1707. * element.
  1708. * @private
  1709. */
  1710. }, {
  1711. key: "_load",
  1712. value: function _load(media, peaks, preload) {
  1713. // verify media element is valid
  1714. if (!(media instanceof HTMLMediaElement) || typeof media.addEventListener === 'undefined') {
  1715. throw new Error('media parameter is not a valid media element');
  1716. } // load must be called manually on iOS, otherwise peaks won't draw
  1717. // until a user interaction triggers load --> 'ready' event
  1718. //
  1719. // note that we avoid calling media.load here when given peaks and preload == 'none'
  1720. // as this almost always triggers some browser fetch of the media.
  1721. if (typeof media.load == 'function' && !(peaks && preload == 'none')) {
  1722. // Resets the media element and restarts the media resource. Any
  1723. // pending events are discarded. How much media data is fetched is
  1724. // still affected by the preload attribute.
  1725. media.load();
  1726. }
  1727. this.media = media;
  1728. this._setupMediaListeners();
  1729. this.peaks = peaks;
  1730. this.onPlayEnd = null;
  1731. this.buffer = null;
  1732. this.isMuted = media.muted;
  1733. this.setPlaybackRate(this.playbackRate);
  1734. this.setVolume(this.volume);
  1735. }
  1736. /**
  1737. * Used by `wavesurfer.isPlaying()` and `wavesurfer.playPause()`
  1738. *
  1739. * @return {boolean} Media paused or not
  1740. */
  1741. }, {
  1742. key: "isPaused",
  1743. value: function isPaused() {
  1744. return !this.media || this.media.paused;
  1745. }
  1746. /**
  1747. * Used by `wavesurfer.getDuration()`
  1748. *
  1749. * @return {number} Duration
  1750. */
  1751. }, {
  1752. key: "getDuration",
  1753. value: function getDuration() {
  1754. if (this.explicitDuration) {
  1755. return this.explicitDuration;
  1756. }
  1757. var duration = (this.buffer || this.media).duration;
  1758. if (duration >= Infinity) {
  1759. // streaming audio
  1760. duration = this.media.seekable.end(0);
  1761. }
  1762. return duration;
  1763. }
  1764. /**
  1765. * Returns the current time in seconds relative to the audio-clip's
  1766. * duration.
  1767. *
  1768. * @return {number} Current time
  1769. */
  1770. }, {
  1771. key: "getCurrentTime",
  1772. value: function getCurrentTime() {
  1773. return this.media && this.media.currentTime;
  1774. }
  1775. /**
  1776. * Get the position from 0 to 1
  1777. *
  1778. * @return {number} Current position
  1779. */
  1780. }, {
  1781. key: "getPlayedPercents",
  1782. value: function getPlayedPercents() {
  1783. return this.getCurrentTime() / this.getDuration() || 0;
  1784. }
  1785. /**
  1786. * Get the audio source playback rate.
  1787. *
  1788. * @return {number} Playback rate
  1789. */
  1790. }, {
  1791. key: "getPlaybackRate",
  1792. value: function getPlaybackRate() {
  1793. return this.playbackRate || this.media.playbackRate;
  1794. }
  1795. /**
  1796. * Set the audio source playback rate.
  1797. *
  1798. * @param {number} value Playback rate
  1799. */
  1800. }, {
  1801. key: "setPlaybackRate",
  1802. value: function setPlaybackRate(value) {
  1803. this.playbackRate = value || 1;
  1804. this.media.playbackRate = this.playbackRate;
  1805. }
  1806. /**
  1807. * Used by `wavesurfer.seekTo()`
  1808. *
  1809. * @param {number} start Position to start at in seconds
  1810. */
  1811. }, {
  1812. key: "seekTo",
  1813. value: function seekTo(start) {
  1814. if (start != null && !isNaN(start)) {
  1815. this.media.currentTime = start;
  1816. }
  1817. this.clearPlayEnd();
  1818. }
  1819. /**
  1820. * Plays the loaded audio region.
  1821. *
  1822. * @param {number} start Start offset in seconds, relative to the beginning
  1823. * of a clip.
  1824. * @param {number} end When to stop, relative to the beginning of a clip.
  1825. * @emits MediaElement#play
  1826. * @return {Promise} Result
  1827. */
  1828. }, {
  1829. key: "play",
  1830. value: function play(start, end) {
  1831. this.seekTo(start);
  1832. var promise = this.media.play();
  1833. end && this.setPlayEnd(end);
  1834. return promise;
  1835. }
  1836. /**
  1837. * Pauses the loaded audio.
  1838. *
  1839. * @emits MediaElement#pause
  1840. * @return {Promise} Result
  1841. */
  1842. }, {
  1843. key: "pause",
  1844. value: function pause() {
  1845. var promise;
  1846. if (this.media) {
  1847. promise = this.media.pause();
  1848. }
  1849. this.clearPlayEnd();
  1850. return promise;
  1851. }
  1852. /**
  1853. * Set the play end
  1854. *
  1855. * @param {number} end Where to end
  1856. */
  1857. }, {
  1858. key: "setPlayEnd",
  1859. value: function setPlayEnd(end) {
  1860. var _this4 = this;
  1861. this.clearPlayEnd();
  1862. this._onPlayEnd = function (time) {
  1863. if (time >= end) {
  1864. _this4.pause();
  1865. _this4.seekTo(end);
  1866. }
  1867. };
  1868. this.on('audioprocess', this._onPlayEnd);
  1869. }
  1870. /** @private */
  1871. }, {
  1872. key: "clearPlayEnd",
  1873. value: function clearPlayEnd() {
  1874. if (this._onPlayEnd) {
  1875. this.un('audioprocess', this._onPlayEnd);
  1876. this._onPlayEnd = null;
  1877. }
  1878. }
  1879. /**
  1880. * Compute the max and min value of the waveform when broken into
  1881. * <length> subranges.
  1882. *
  1883. * @param {number} length How many subranges to break the waveform into.
  1884. * @param {number} first First sample in the required range.
  1885. * @param {number} last Last sample in the required range.
  1886. * @return {number[]|Number.<Array[]>} Array of 2*<length> peaks or array of
  1887. * arrays of peaks consisting of (max, min) values for each subrange.
  1888. */
  1889. }, {
  1890. key: "getPeaks",
  1891. value: function getPeaks(length, first, last) {
  1892. if (this.buffer) {
  1893. return _get(_getPrototypeOf(MediaElement.prototype), "getPeaks", this).call(this, length, first, last);
  1894. }
  1895. return this.peaks || [];
  1896. }
  1897. /**
  1898. * Set the sink id for the media player
  1899. *
  1900. * @param {string} deviceId String value representing audio device id.
  1901. * @returns {Promise} A Promise that resolves to `undefined` when there
  1902. * are no errors.
  1903. */
  1904. }, {
  1905. key: "setSinkId",
  1906. value: function setSinkId(deviceId) {
  1907. if (deviceId) {
  1908. if (!this.media.setSinkId) {
  1909. return Promise.reject(new Error('setSinkId is not supported in your browser'));
  1910. }
  1911. return this.media.setSinkId(deviceId);
  1912. }
  1913. return Promise.reject(new Error('Invalid deviceId: ' + deviceId));
  1914. }
  1915. /**
  1916. * Get the current volume
  1917. *
  1918. * @return {number} value A floating point value between 0 and 1.
  1919. */
  1920. }, {
  1921. key: "getVolume",
  1922. value: function getVolume() {
  1923. return this.volume;
  1924. }
  1925. /**
  1926. * Set the audio volume
  1927. *
  1928. * @param {number} value A floating point value between 0 and 1.
  1929. */
  1930. }, {
  1931. key: "setVolume",
  1932. value: function setVolume(value) {
  1933. this.volume = value; // no need to change when it's already at that volume
  1934. if (this.media.volume !== this.volume) {
  1935. this.media.volume = this.volume;
  1936. }
  1937. }
  1938. /**
  1939. * Enable or disable muted audio
  1940. *
  1941. * @since 4.0.0
  1942. * @param {boolean} muted Specify `true` to mute audio.
  1943. */
  1944. }, {
  1945. key: "setMute",
  1946. value: function setMute(muted) {
  1947. // This causes a volume change to be emitted too through the
  1948. // volumechange event listener.
  1949. this.isMuted = this.media.muted = muted;
  1950. }
  1951. /**
  1952. * This is called when wavesurfer is destroyed
  1953. *
  1954. */
  1955. }, {
  1956. key: "destroy",
  1957. value: function destroy() {
  1958. var _this5 = this;
  1959. this.pause();
  1960. this.unAll();
  1961. this.destroyed = true; // cleanup media event listeners
  1962. Object.keys(this.mediaListeners).forEach(function (id) {
  1963. if (_this5.media) {
  1964. _this5.media.removeEventListener(id, _this5.mediaListeners[id]);
  1965. }
  1966. });
  1967. if (this.params.removeMediaElementOnDestroy && this.media && this.media.parentNode) {
  1968. this.media.parentNode.removeChild(this.media);
  1969. }
  1970. this.media = null;
  1971. }
  1972. }]);
  1973. return MediaElement;
  1974. }(_webaudio.default);
  1975. exports["default"] = MediaElement;
  1976. module.exports = exports.default;
  1977. /***/ }),
  1978. /***/ "./src/peakcache.js":
  1979. /*!**************************!*\
  1980. !*** ./src/peakcache.js ***!
  1981. \**************************/
  1982. /***/ ((module, exports) => {
  1983. "use strict";
  1984. Object.defineProperty(exports, "__esModule", ({
  1985. value: true
  1986. }));
  1987. exports["default"] = void 0;
  1988. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1989. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  1990. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  1991. /**
  1992. * Caches the decoded peaks data to improve rendering speed for large audio
  1993. *
  1994. * Is used if the option parameter `partialRender` is set to `true`
  1995. */
  1996. var PeakCache = /*#__PURE__*/function () {
  1997. /**
  1998. * Instantiate cache
  1999. */
  2000. function PeakCache() {
  2001. _classCallCheck(this, PeakCache);
  2002. this.clearPeakCache();
  2003. }
  2004. /**
  2005. * Empty the cache
  2006. */
  2007. _createClass(PeakCache, [{
  2008. key: "clearPeakCache",
  2009. value: function clearPeakCache() {
  2010. /**
  2011. * Flat array with entries that are always in pairs to mark the
  2012. * beginning and end of each subrange. This is a convenience so we can
  2013. * iterate over the pairs for easy set difference operations.
  2014. * @private
  2015. */
  2016. this.peakCacheRanges = [];
  2017. /**
  2018. * Length of the entire cachable region, used for resetting the cache
  2019. * when this changes (zoom events, for instance).
  2020. * @private
  2021. */
  2022. this.peakCacheLength = -1;
  2023. }
  2024. /**
  2025. * Add a range of peaks to the cache
  2026. *
  2027. * @param {number} length The length of the range
  2028. * @param {number} start The x offset of the start of the range
  2029. * @param {number} end The x offset of the end of the range
  2030. * @return {Number.<Array[]>} Array with arrays of numbers
  2031. */
  2032. }, {
  2033. key: "addRangeToPeakCache",
  2034. value: function addRangeToPeakCache(length, start, end) {
  2035. if (length != this.peakCacheLength) {
  2036. this.clearPeakCache();
  2037. this.peakCacheLength = length;
  2038. } // Return ranges that weren't in the cache before the call.
  2039. var uncachedRanges = [];
  2040. var i = 0; // Skip ranges before the current start.
  2041. while (i < this.peakCacheRanges.length && this.peakCacheRanges[i] < start) {
  2042. i++;
  2043. } // If |i| is even, |start| falls after an existing range. Otherwise,
  2044. // |start| falls between an existing range, and the uncached region
  2045. // starts when we encounter the next node in |peakCacheRanges| or
  2046. // |end|, whichever comes first.
  2047. if (i % 2 == 0) {
  2048. uncachedRanges.push(start);
  2049. }
  2050. while (i < this.peakCacheRanges.length && this.peakCacheRanges[i] <= end) {
  2051. uncachedRanges.push(this.peakCacheRanges[i]);
  2052. i++;
  2053. } // If |i| is even, |end| is after all existing ranges.
  2054. if (i % 2 == 0) {
  2055. uncachedRanges.push(end);
  2056. } // Filter out the 0-length ranges.
  2057. uncachedRanges = uncachedRanges.filter(function (item, pos, arr) {
  2058. if (pos == 0) {
  2059. return item != arr[pos + 1];
  2060. } else if (pos == arr.length - 1) {
  2061. return item != arr[pos - 1];
  2062. }
  2063. return item != arr[pos - 1] && item != arr[pos + 1];
  2064. }); // Merge the two ranges together, uncachedRanges will either contain
  2065. // wholly new points, or duplicates of points in peakCacheRanges. If
  2066. // duplicates are detected, remove both and extend the range.
  2067. this.peakCacheRanges = this.peakCacheRanges.concat(uncachedRanges);
  2068. this.peakCacheRanges = this.peakCacheRanges.sort(function (a, b) {
  2069. return a - b;
  2070. }).filter(function (item, pos, arr) {
  2071. if (pos == 0) {
  2072. return item != arr[pos + 1];
  2073. } else if (pos == arr.length - 1) {
  2074. return item != arr[pos - 1];
  2075. }
  2076. return item != arr[pos - 1] && item != arr[pos + 1];
  2077. }); // Push the uncached ranges into an array of arrays for ease of
  2078. // iteration in the functions that call this.
  2079. var uncachedRangePairs = [];
  2080. for (i = 0; i < uncachedRanges.length; i += 2) {
  2081. uncachedRangePairs.push([uncachedRanges[i], uncachedRanges[i + 1]]);
  2082. }
  2083. return uncachedRangePairs;
  2084. }
  2085. /**
  2086. * For testing
  2087. *
  2088. * @return {Number.<Array[]>} Array with arrays of numbers
  2089. */
  2090. }, {
  2091. key: "getCacheRanges",
  2092. value: function getCacheRanges() {
  2093. var peakCacheRangePairs = [];
  2094. var i;
  2095. for (i = 0; i < this.peakCacheRanges.length; i += 2) {
  2096. peakCacheRangePairs.push([this.peakCacheRanges[i], this.peakCacheRanges[i + 1]]);
  2097. }
  2098. return peakCacheRangePairs;
  2099. }
  2100. }]);
  2101. return PeakCache;
  2102. }();
  2103. exports["default"] = PeakCache;
  2104. module.exports = exports.default;
  2105. /***/ }),
  2106. /***/ "./src/util/absMax.js":
  2107. /*!****************************!*\
  2108. !*** ./src/util/absMax.js ***!
  2109. \****************************/
  2110. /***/ ((module, exports, __webpack_require__) => {
  2111. "use strict";
  2112. Object.defineProperty(exports, "__esModule", ({
  2113. value: true
  2114. }));
  2115. exports["default"] = absMax;
  2116. var _max = _interopRequireDefault(__webpack_require__(/*! ./max */ "./src/util/max.js"));
  2117. var _min = _interopRequireDefault(__webpack_require__(/*! ./min */ "./src/util/min.js"));
  2118. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2119. /**
  2120. * Get the largest absolute value in an array
  2121. *
  2122. * @param {Array} values Array of numbers
  2123. * @returns {Number} Largest number found
  2124. * @example console.log(max([-3, 2, 1]), max([-3, 2, 4])); // logs 3 4
  2125. * @since 4.3.0
  2126. */
  2127. function absMax(values) {
  2128. var max = (0, _max.default)(values);
  2129. var min = (0, _min.default)(values);
  2130. return -min > max ? -min : max;
  2131. }
  2132. module.exports = exports.default;
  2133. /***/ }),
  2134. /***/ "./src/util/clamp.js":
  2135. /*!***************************!*\
  2136. !*** ./src/util/clamp.js ***!
  2137. \***************************/
  2138. /***/ ((module, exports) => {
  2139. "use strict";
  2140. Object.defineProperty(exports, "__esModule", ({
  2141. value: true
  2142. }));
  2143. exports["default"] = clamp;
  2144. /**
  2145. * Returns a number limited to the given range.
  2146. *
  2147. * @param {number} val The number to be limited to a range
  2148. * @param {number} min The lower boundary of the limit range
  2149. * @param {number} max The upper boundary of the limit range
  2150. * @returns {number} A number in the range [min, max]
  2151. */
  2152. function clamp(val, min, max) {
  2153. return Math.min(Math.max(min, val), max);
  2154. }
  2155. module.exports = exports.default;
  2156. /***/ }),
  2157. /***/ "./src/util/fetch.js":
  2158. /*!***************************!*\
  2159. !*** ./src/util/fetch.js ***!
  2160. \***************************/
  2161. /***/ ((module, exports, __webpack_require__) => {
  2162. "use strict";
  2163. Object.defineProperty(exports, "__esModule", ({
  2164. value: true
  2165. }));
  2166. exports["default"] = fetchFile;
  2167. var _observer = _interopRequireDefault(__webpack_require__(/*! ./observer */ "./src/util/observer.js"));
  2168. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2169. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2170. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  2171. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  2172. var ProgressHandler = /*#__PURE__*/function () {
  2173. /**
  2174. * Instantiate ProgressHandler
  2175. *
  2176. * @param {Observer} instance The `fetchFile` observer instance.
  2177. * @param {Number} contentLength Content length.
  2178. * @param {Response} response Response object.
  2179. */
  2180. function ProgressHandler(instance, contentLength, response) {
  2181. _classCallCheck(this, ProgressHandler);
  2182. this.instance = instance;
  2183. this.instance._reader = response.body.getReader();
  2184. this.total = parseInt(contentLength, 10);
  2185. this.loaded = 0;
  2186. }
  2187. /**
  2188. * A method that is called once, immediately after the `ReadableStream``
  2189. * is constructed.
  2190. *
  2191. * @param {ReadableStreamDefaultController} controller Controller instance
  2192. * used to control the stream.
  2193. */
  2194. _createClass(ProgressHandler, [{
  2195. key: "start",
  2196. value: function start(controller) {
  2197. var _this = this;
  2198. var read = function read() {
  2199. // instance._reader.read() returns a promise that resolves
  2200. // when a value has been received
  2201. _this.instance._reader.read().then(function (_ref) {
  2202. var done = _ref.done,
  2203. value = _ref.value;
  2204. // result objects contain two properties:
  2205. // done - true if the stream has already given you all its data.
  2206. // value - some data. Always undefined when done is true.
  2207. if (done) {
  2208. // ensure onProgress called when content-length=0
  2209. if (_this.total === 0) {
  2210. _this.instance.onProgress.call(_this.instance, {
  2211. loaded: _this.loaded,
  2212. total: _this.total,
  2213. lengthComputable: false
  2214. });
  2215. } // no more data needs to be consumed, close the stream
  2216. controller.close();
  2217. return;
  2218. }
  2219. _this.loaded += value.byteLength;
  2220. _this.instance.onProgress.call(_this.instance, {
  2221. loaded: _this.loaded,
  2222. total: _this.total,
  2223. lengthComputable: !(_this.total === 0)
  2224. }); // enqueue the next data chunk into our target stream
  2225. controller.enqueue(value);
  2226. read();
  2227. }).catch(function (error) {
  2228. controller.error(error);
  2229. });
  2230. };
  2231. read();
  2232. }
  2233. }]);
  2234. return ProgressHandler;
  2235. }();
  2236. /**
  2237. * Load a file using `fetch`.
  2238. *
  2239. * @param {object} options Request options to use. See example below.
  2240. * @returns {Observer} Observer instance
  2241. * @example
  2242. * // default options
  2243. * let options = {
  2244. * url: undefined,
  2245. * method: 'GET',
  2246. * mode: 'cors',
  2247. * credentials: 'same-origin',
  2248. * cache: 'default',
  2249. * responseType: 'json',
  2250. * requestHeaders: [],
  2251. * redirect: 'follow',
  2252. * referrer: 'client'
  2253. * };
  2254. *
  2255. * // override some options
  2256. * options.url = '../media/demo.wav';
  2257. * // available types: 'arraybuffer', 'blob', 'json' or 'text'
  2258. * options.responseType = 'arraybuffer';
  2259. *
  2260. * // make fetch call
  2261. * let request = util.fetchFile(options);
  2262. *
  2263. * // listen for events
  2264. * request.on('progress', e => {
  2265. * console.log('progress', e);
  2266. * });
  2267. *
  2268. * request.on('success', data => {
  2269. * console.log('success!', data);
  2270. * });
  2271. *
  2272. * request.on('error', e => {
  2273. * console.warn('fetchFile error: ', e);
  2274. * });
  2275. */
  2276. function fetchFile(options) {
  2277. if (!options) {
  2278. throw new Error('fetch options missing');
  2279. } else if (!options.url) {
  2280. throw new Error('fetch url missing');
  2281. }
  2282. var instance = new _observer.default();
  2283. var fetchHeaders = new Headers();
  2284. var fetchRequest = new Request(options.url); // add ability to abort
  2285. instance.controller = new AbortController(); // check if headers have to be added
  2286. if (options && options.requestHeaders) {
  2287. // add custom request headers
  2288. options.requestHeaders.forEach(function (header) {
  2289. fetchHeaders.append(header.key, header.value);
  2290. });
  2291. } // parse fetch options
  2292. var responseType = options.responseType || 'json';
  2293. var fetchOptions = {
  2294. method: options.method || 'GET',
  2295. headers: fetchHeaders,
  2296. mode: options.mode || 'cors',
  2297. credentials: options.credentials || 'same-origin',
  2298. cache: options.cache || 'default',
  2299. redirect: options.redirect || 'follow',
  2300. referrer: options.referrer || 'client',
  2301. signal: instance.controller.signal
  2302. };
  2303. fetch(fetchRequest, fetchOptions).then(function (response) {
  2304. // store response reference
  2305. instance.response = response;
  2306. var progressAvailable = true;
  2307. if (!response.body) {
  2308. // ReadableStream is not yet supported in this browser
  2309. // see https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream
  2310. progressAvailable = false;
  2311. } // Server must send CORS header "Access-Control-Expose-Headers: content-length"
  2312. var contentLength = response.headers.get('content-length');
  2313. if (contentLength === null) {
  2314. // Content-Length server response header missing.
  2315. // Don't evaluate download progress if we can't compare against a total size
  2316. // see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Access-Control-Expose-Headers
  2317. progressAvailable = false;
  2318. }
  2319. if (!progressAvailable) {
  2320. // not able to check download progress so skip it
  2321. return response;
  2322. } // fire progress event when during load
  2323. instance.onProgress = function (e) {
  2324. instance.fireEvent('progress', e);
  2325. };
  2326. return new Response(new ReadableStream(new ProgressHandler(instance, contentLength, response)), fetchOptions);
  2327. }).then(function (response) {
  2328. var errMsg;
  2329. if (response.ok) {
  2330. switch (responseType) {
  2331. case 'arraybuffer':
  2332. return response.arrayBuffer();
  2333. case 'json':
  2334. return response.json();
  2335. case 'blob':
  2336. return response.blob();
  2337. case 'text':
  2338. return response.text();
  2339. default:
  2340. errMsg = 'Unknown responseType: ' + responseType;
  2341. break;
  2342. }
  2343. }
  2344. if (!errMsg) {
  2345. errMsg = 'HTTP error status: ' + response.status;
  2346. }
  2347. throw new Error(errMsg);
  2348. }).then(function (response) {
  2349. instance.fireEvent('success', response);
  2350. }).catch(function (error) {
  2351. instance.fireEvent('error', error);
  2352. }); // return the fetch request
  2353. instance.fetchRequest = fetchRequest;
  2354. return instance;
  2355. }
  2356. module.exports = exports.default;
  2357. /***/ }),
  2358. /***/ "./src/util/frame.js":
  2359. /*!***************************!*\
  2360. !*** ./src/util/frame.js ***!
  2361. \***************************/
  2362. /***/ ((module, exports, __webpack_require__) => {
  2363. "use strict";
  2364. Object.defineProperty(exports, "__esModule", ({
  2365. value: true
  2366. }));
  2367. exports["default"] = frame;
  2368. var _requestAnimationFrame = _interopRequireDefault(__webpack_require__(/*! ./request-animation-frame */ "./src/util/request-animation-frame.js"));
  2369. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2370. /**
  2371. * Create a function which will be called at the next requestAnimationFrame
  2372. * cycle
  2373. *
  2374. * @param {function} func The function to call
  2375. *
  2376. * @return {func} The function wrapped within a requestAnimationFrame
  2377. */
  2378. function frame(func) {
  2379. return function () {
  2380. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  2381. args[_key] = arguments[_key];
  2382. }
  2383. return (0, _requestAnimationFrame.default)(function () {
  2384. return func.apply(void 0, args);
  2385. });
  2386. };
  2387. }
  2388. module.exports = exports.default;
  2389. /***/ }),
  2390. /***/ "./src/util/get-id.js":
  2391. /*!****************************!*\
  2392. !*** ./src/util/get-id.js ***!
  2393. \****************************/
  2394. /***/ ((module, exports) => {
  2395. "use strict";
  2396. Object.defineProperty(exports, "__esModule", ({
  2397. value: true
  2398. }));
  2399. exports["default"] = getId;
  2400. /**
  2401. * Get a random prefixed ID
  2402. *
  2403. * @param {String} prefix Prefix to use. Default is `'wavesurfer_'`.
  2404. * @returns {String} Random prefixed ID
  2405. * @example
  2406. * console.log(getId()); // logs 'wavesurfer_b5pors4ru6g'
  2407. *
  2408. * let prefix = 'foo-';
  2409. * console.log(getId(prefix)); // logs 'foo-b5pors4ru6g'
  2410. */
  2411. function getId(prefix) {
  2412. if (prefix === undefined) {
  2413. prefix = 'wavesurfer_';
  2414. }
  2415. return prefix + Math.random().toString(32).substring(2);
  2416. }
  2417. module.exports = exports.default;
  2418. /***/ }),
  2419. /***/ "./src/util/index.js":
  2420. /*!***************************!*\
  2421. !*** ./src/util/index.js ***!
  2422. \***************************/
  2423. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  2424. "use strict";
  2425. Object.defineProperty(exports, "__esModule", ({
  2426. value: true
  2427. }));
  2428. Object.defineProperty(exports, "Observer", ({
  2429. enumerable: true,
  2430. get: function get() {
  2431. return _observer.default;
  2432. }
  2433. }));
  2434. Object.defineProperty(exports, "absMax", ({
  2435. enumerable: true,
  2436. get: function get() {
  2437. return _absMax.default;
  2438. }
  2439. }));
  2440. Object.defineProperty(exports, "clamp", ({
  2441. enumerable: true,
  2442. get: function get() {
  2443. return _clamp.default;
  2444. }
  2445. }));
  2446. Object.defineProperty(exports, "debounce", ({
  2447. enumerable: true,
  2448. get: function get() {
  2449. return _debounce.default;
  2450. }
  2451. }));
  2452. Object.defineProperty(exports, "fetchFile", ({
  2453. enumerable: true,
  2454. get: function get() {
  2455. return _fetch.default;
  2456. }
  2457. }));
  2458. Object.defineProperty(exports, "frame", ({
  2459. enumerable: true,
  2460. get: function get() {
  2461. return _frame.default;
  2462. }
  2463. }));
  2464. Object.defineProperty(exports, "getId", ({
  2465. enumerable: true,
  2466. get: function get() {
  2467. return _getId.default;
  2468. }
  2469. }));
  2470. Object.defineProperty(exports, "ignoreSilenceMode", ({
  2471. enumerable: true,
  2472. get: function get() {
  2473. return _silenceMode.default;
  2474. }
  2475. }));
  2476. Object.defineProperty(exports, "max", ({
  2477. enumerable: true,
  2478. get: function get() {
  2479. return _max.default;
  2480. }
  2481. }));
  2482. Object.defineProperty(exports, "min", ({
  2483. enumerable: true,
  2484. get: function get() {
  2485. return _min.default;
  2486. }
  2487. }));
  2488. Object.defineProperty(exports, "preventClick", ({
  2489. enumerable: true,
  2490. get: function get() {
  2491. return _preventClick.default;
  2492. }
  2493. }));
  2494. Object.defineProperty(exports, "requestAnimationFrame", ({
  2495. enumerable: true,
  2496. get: function get() {
  2497. return _requestAnimationFrame.default;
  2498. }
  2499. }));
  2500. Object.defineProperty(exports, "style", ({
  2501. enumerable: true,
  2502. get: function get() {
  2503. return _style.default;
  2504. }
  2505. }));
  2506. Object.defineProperty(exports, "withOrientation", ({
  2507. enumerable: true,
  2508. get: function get() {
  2509. return _orientation.default;
  2510. }
  2511. }));
  2512. var _getId = _interopRequireDefault(__webpack_require__(/*! ./get-id */ "./src/util/get-id.js"));
  2513. var _max = _interopRequireDefault(__webpack_require__(/*! ./max */ "./src/util/max.js"));
  2514. var _min = _interopRequireDefault(__webpack_require__(/*! ./min */ "./src/util/min.js"));
  2515. var _absMax = _interopRequireDefault(__webpack_require__(/*! ./absMax */ "./src/util/absMax.js"));
  2516. var _observer = _interopRequireDefault(__webpack_require__(/*! ./observer */ "./src/util/observer.js"));
  2517. var _style = _interopRequireDefault(__webpack_require__(/*! ./style */ "./src/util/style.js"));
  2518. var _requestAnimationFrame = _interopRequireDefault(__webpack_require__(/*! ./request-animation-frame */ "./src/util/request-animation-frame.js"));
  2519. var _frame = _interopRequireDefault(__webpack_require__(/*! ./frame */ "./src/util/frame.js"));
  2520. var _debounce = _interopRequireDefault(__webpack_require__(/*! debounce */ "./node_modules/debounce/index.js"));
  2521. var _preventClick = _interopRequireDefault(__webpack_require__(/*! ./prevent-click */ "./src/util/prevent-click.js"));
  2522. var _fetch = _interopRequireDefault(__webpack_require__(/*! ./fetch */ "./src/util/fetch.js"));
  2523. var _clamp = _interopRequireDefault(__webpack_require__(/*! ./clamp */ "./src/util/clamp.js"));
  2524. var _orientation = _interopRequireDefault(__webpack_require__(/*! ./orientation */ "./src/util/orientation.js"));
  2525. var _silenceMode = _interopRequireDefault(__webpack_require__(/*! ./silence-mode */ "./src/util/silence-mode.js"));
  2526. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2527. /***/ }),
  2528. /***/ "./src/util/max.js":
  2529. /*!*************************!*\
  2530. !*** ./src/util/max.js ***!
  2531. \*************************/
  2532. /***/ ((module, exports) => {
  2533. "use strict";
  2534. Object.defineProperty(exports, "__esModule", ({
  2535. value: true
  2536. }));
  2537. exports["default"] = max;
  2538. /**
  2539. * Get the largest value
  2540. *
  2541. * @param {Array} values Array of numbers
  2542. * @returns {Number} Largest number found
  2543. * @example console.log(max([1, 2, 3])); // logs 3
  2544. */
  2545. function max(values) {
  2546. var largest = -Infinity;
  2547. Object.keys(values).forEach(function (i) {
  2548. if (values[i] > largest) {
  2549. largest = values[i];
  2550. }
  2551. });
  2552. return largest;
  2553. }
  2554. module.exports = exports.default;
  2555. /***/ }),
  2556. /***/ "./src/util/min.js":
  2557. /*!*************************!*\
  2558. !*** ./src/util/min.js ***!
  2559. \*************************/
  2560. /***/ ((module, exports) => {
  2561. "use strict";
  2562. Object.defineProperty(exports, "__esModule", ({
  2563. value: true
  2564. }));
  2565. exports["default"] = min;
  2566. /**
  2567. * Get the smallest value
  2568. *
  2569. * @param {Array} values Array of numbers
  2570. * @returns {Number} Smallest number found
  2571. * @example console.log(min([1, 2, 3])); // logs 1
  2572. */
  2573. function min(values) {
  2574. var smallest = Number(Infinity);
  2575. Object.keys(values).forEach(function (i) {
  2576. if (values[i] < smallest) {
  2577. smallest = values[i];
  2578. }
  2579. });
  2580. return smallest;
  2581. }
  2582. module.exports = exports.default;
  2583. /***/ }),
  2584. /***/ "./src/util/observer.js":
  2585. /*!******************************!*\
  2586. !*** ./src/util/observer.js ***!
  2587. \******************************/
  2588. /***/ ((module, exports) => {
  2589. "use strict";
  2590. Object.defineProperty(exports, "__esModule", ({
  2591. value: true
  2592. }));
  2593. exports["default"] = void 0;
  2594. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  2595. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  2596. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  2597. /**
  2598. * @typedef {Object} ListenerDescriptor
  2599. * @property {string} name The name of the event
  2600. * @property {function} callback The callback
  2601. * @property {function} un The function to call to remove the listener
  2602. */
  2603. /**
  2604. * Observer class
  2605. */
  2606. var Observer = /*#__PURE__*/function () {
  2607. /**
  2608. * Instantiate Observer
  2609. */
  2610. function Observer() {
  2611. _classCallCheck(this, Observer);
  2612. /**
  2613. * @private
  2614. * @todo Initialise the handlers here already and remove the conditional
  2615. * assignment in `on()`
  2616. */
  2617. this._disabledEventEmissions = [];
  2618. this.handlers = null;
  2619. }
  2620. /**
  2621. * Attach a handler function for an event.
  2622. *
  2623. * @param {string} event Name of the event to listen to
  2624. * @param {function} fn The callback to trigger when the event is fired
  2625. * @return {ListenerDescriptor} The event descriptor
  2626. */
  2627. _createClass(Observer, [{
  2628. key: "on",
  2629. value: function on(event, fn) {
  2630. var _this = this;
  2631. if (!this.handlers) {
  2632. this.handlers = {};
  2633. }
  2634. var handlers = this.handlers[event];
  2635. if (!handlers) {
  2636. handlers = this.handlers[event] = [];
  2637. }
  2638. handlers.push(fn); // Return an event descriptor
  2639. return {
  2640. name: event,
  2641. callback: fn,
  2642. un: function un(e, fn) {
  2643. return _this.un(e, fn);
  2644. }
  2645. };
  2646. }
  2647. /**
  2648. * Remove an event handler.
  2649. *
  2650. * @param {string} event Name of the event the listener that should be
  2651. * removed listens to
  2652. * @param {function} fn The callback that should be removed
  2653. */
  2654. }, {
  2655. key: "un",
  2656. value: function un(event, fn) {
  2657. if (!this.handlers) {
  2658. return;
  2659. }
  2660. var handlers = this.handlers[event];
  2661. var i;
  2662. if (handlers) {
  2663. if (fn) {
  2664. for (i = handlers.length - 1; i >= 0; i--) {
  2665. if (handlers[i] == fn) {
  2666. handlers.splice(i, 1);
  2667. }
  2668. }
  2669. } else {
  2670. handlers.length = 0;
  2671. }
  2672. }
  2673. }
  2674. /**
  2675. * Remove all event handlers.
  2676. */
  2677. }, {
  2678. key: "unAll",
  2679. value: function unAll() {
  2680. this.handlers = null;
  2681. }
  2682. /**
  2683. * Attach a handler to an event. The handler is executed at most once per
  2684. * event type.
  2685. *
  2686. * @param {string} event The event to listen to
  2687. * @param {function} handler The callback that is only to be called once
  2688. * @return {ListenerDescriptor} The event descriptor
  2689. */
  2690. }, {
  2691. key: "once",
  2692. value: function once(event, handler) {
  2693. var _this2 = this;
  2694. var fn = function fn() {
  2695. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  2696. args[_key] = arguments[_key];
  2697. }
  2698. /* eslint-disable no-invalid-this */
  2699. handler.apply(_this2, args);
  2700. /* eslint-enable no-invalid-this */
  2701. setTimeout(function () {
  2702. _this2.un(event, fn);
  2703. }, 0);
  2704. };
  2705. return this.on(event, fn);
  2706. }
  2707. /**
  2708. * Disable firing a list of events by name. When specified, event handlers for any event type
  2709. * passed in here will not be called.
  2710. *
  2711. * @since 4.0.0
  2712. * @param {string[]} eventNames an array of event names to disable emissions for
  2713. * @example
  2714. * // disable seek and interaction events
  2715. * wavesurfer.setDisabledEventEmissions(['seek', 'interaction']);
  2716. */
  2717. }, {
  2718. key: "setDisabledEventEmissions",
  2719. value: function setDisabledEventEmissions(eventNames) {
  2720. this._disabledEventEmissions = eventNames;
  2721. }
  2722. /**
  2723. * plugins borrow part of this class without calling the constructor,
  2724. * so we have to be careful about _disabledEventEmissions
  2725. */
  2726. }, {
  2727. key: "_isDisabledEventEmission",
  2728. value: function _isDisabledEventEmission(event) {
  2729. return this._disabledEventEmissions && this._disabledEventEmissions.includes(event);
  2730. }
  2731. /**
  2732. * Manually fire an event
  2733. *
  2734. * @param {string} event The event to fire manually
  2735. * @param {...any} args The arguments with which to call the listeners
  2736. */
  2737. }, {
  2738. key: "fireEvent",
  2739. value: function fireEvent(event) {
  2740. for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  2741. args[_key2 - 1] = arguments[_key2];
  2742. }
  2743. if (!this.handlers || this._isDisabledEventEmission(event)) {
  2744. return;
  2745. }
  2746. var handlers = this.handlers[event];
  2747. handlers && handlers.forEach(function (fn) {
  2748. fn.apply(void 0, args);
  2749. });
  2750. }
  2751. }]);
  2752. return Observer;
  2753. }();
  2754. exports["default"] = Observer;
  2755. module.exports = exports.default;
  2756. /***/ }),
  2757. /***/ "./src/util/orientation.js":
  2758. /*!*********************************!*\
  2759. !*** ./src/util/orientation.js ***!
  2760. \*********************************/
  2761. /***/ ((module, exports) => {
  2762. "use strict";
  2763. Object.defineProperty(exports, "__esModule", ({
  2764. value: true
  2765. }));
  2766. exports["default"] = withOrientation;
  2767. var verticalPropMap = {
  2768. width: 'height',
  2769. height: 'width',
  2770. overflowX: 'overflowY',
  2771. overflowY: 'overflowX',
  2772. clientWidth: 'clientHeight',
  2773. clientHeight: 'clientWidth',
  2774. clientX: 'clientY',
  2775. clientY: 'clientX',
  2776. scrollWidth: 'scrollHeight',
  2777. scrollLeft: 'scrollTop',
  2778. offsetLeft: 'offsetTop',
  2779. offsetTop: 'offsetLeft',
  2780. offsetHeight: 'offsetWidth',
  2781. offsetWidth: 'offsetHeight',
  2782. left: 'top',
  2783. right: 'bottom',
  2784. top: 'left',
  2785. bottom: 'right',
  2786. borderRightStyle: 'borderBottomStyle',
  2787. borderRightWidth: 'borderBottomWidth',
  2788. borderRightColor: 'borderBottomColor'
  2789. };
  2790. /**
  2791. * Convert a horizontally-oriented property name to a vertical one.
  2792. *
  2793. * @param {string} prop A property name
  2794. * @param {bool} vertical Whether the element is oriented vertically
  2795. * @returns {string} prop, converted appropriately
  2796. */
  2797. function mapProp(prop, vertical) {
  2798. if (Object.prototype.hasOwnProperty.call(verticalPropMap, prop)) {
  2799. return vertical ? verticalPropMap[prop] : prop;
  2800. } else {
  2801. return prop;
  2802. }
  2803. }
  2804. var isProxy = Symbol("isProxy");
  2805. /**
  2806. * Returns an appropriately oriented object based on vertical.
  2807. * If vertical is true, attribute getting and setting will be mapped through
  2808. * verticalPropMap, so that e.g. getting the object's .width will give its
  2809. * .height instead.
  2810. * Certain methods of an oriented object will return oriented objects as well.
  2811. * Oriented objects can't be added to the DOM directly since they are Proxy objects
  2812. * and thus fail typechecks. Use domElement to get the actual element for this.
  2813. *
  2814. * @param {object} target The object to be wrapped and oriented
  2815. * @param {bool} vertical Whether the element is oriented vertically
  2816. * @returns {Proxy} An oriented object with attr translation via verticalAttrMap
  2817. * @since 5.0.0
  2818. */
  2819. function withOrientation(target, vertical) {
  2820. if (target[isProxy]) {
  2821. return target;
  2822. } else {
  2823. return new Proxy(target, {
  2824. get: function get(obj, prop, receiver) {
  2825. if (prop === isProxy) {
  2826. return true;
  2827. } else if (prop === 'domElement') {
  2828. return obj;
  2829. } else if (prop === 'style') {
  2830. return withOrientation(obj.style, vertical);
  2831. } else if (prop === 'canvas') {
  2832. return withOrientation(obj.canvas, vertical);
  2833. } else if (prop === 'getBoundingClientRect') {
  2834. return function () {
  2835. return withOrientation(obj.getBoundingClientRect.apply(obj, arguments), vertical);
  2836. };
  2837. } else if (prop === 'getContext') {
  2838. return function () {
  2839. return withOrientation(obj.getContext.apply(obj, arguments), vertical);
  2840. };
  2841. } else {
  2842. var value = obj[mapProp(prop, vertical)];
  2843. return typeof value == 'function' ? value.bind(obj) : value;
  2844. }
  2845. },
  2846. set: function set(obj, prop, value) {
  2847. obj[mapProp(prop, vertical)] = value;
  2848. return true;
  2849. }
  2850. });
  2851. }
  2852. }
  2853. module.exports = exports.default;
  2854. /***/ }),
  2855. /***/ "./src/util/prevent-click.js":
  2856. /*!***********************************!*\
  2857. !*** ./src/util/prevent-click.js ***!
  2858. \***********************************/
  2859. /***/ ((module, exports) => {
  2860. "use strict";
  2861. Object.defineProperty(exports, "__esModule", ({
  2862. value: true
  2863. }));
  2864. exports["default"] = preventClick;
  2865. /**
  2866. * Stops propagation of click event and removes event listener
  2867. *
  2868. * @private
  2869. * @param {object} event The click event
  2870. */
  2871. function preventClickHandler(event) {
  2872. event.stopPropagation();
  2873. document.body.removeEventListener('click', preventClickHandler, true);
  2874. }
  2875. /**
  2876. * Starts listening for click event and prevent propagation
  2877. *
  2878. * @param {object} values Values
  2879. */
  2880. function preventClick(values) {
  2881. document.body.addEventListener('click', preventClickHandler, true);
  2882. }
  2883. module.exports = exports.default;
  2884. /***/ }),
  2885. /***/ "./src/util/request-animation-frame.js":
  2886. /*!*********************************************!*\
  2887. !*** ./src/util/request-animation-frame.js ***!
  2888. \*********************************************/
  2889. /***/ ((module, exports) => {
  2890. "use strict";
  2891. Object.defineProperty(exports, "__esModule", ({
  2892. value: true
  2893. }));
  2894. exports["default"] = void 0;
  2895. /* eslint-disable valid-jsdoc */
  2896. /**
  2897. * Returns the `requestAnimationFrame` function for the browser, or a shim with
  2898. * `setTimeout` if the function is not found
  2899. *
  2900. * @return {function} Available `requestAnimationFrame` function for the browser
  2901. */
  2902. var _default = (window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback, element) {
  2903. return setTimeout(callback, 1000 / 60);
  2904. }).bind(window);
  2905. exports["default"] = _default;
  2906. module.exports = exports.default;
  2907. /***/ }),
  2908. /***/ "./src/util/silence-mode.js":
  2909. /*!**********************************!*\
  2910. !*** ./src/util/silence-mode.js ***!
  2911. \**********************************/
  2912. /***/ ((module, exports) => {
  2913. "use strict";
  2914. Object.defineProperty(exports, "__esModule", ({
  2915. value: true
  2916. }));
  2917. exports["default"] = ignoreSilenceMode;
  2918. /**
  2919. * Ignores device silence mode when using the `WebAudio` backend.
  2920. *
  2921. * Many mobile devices contain a hardware button to mute the ringtone for incoming
  2922. * calls and messages. Unfortunately, on some platforms like iOS, this also mutes
  2923. * wavesurfer's audio when using the `WebAudio` backend. This function creates a
  2924. * temporary `<audio>` element that makes sure the WebAudio backend keeps playing
  2925. * when muting the device ringer.
  2926. *
  2927. * @since 5.2.0
  2928. */
  2929. function ignoreSilenceMode() {
  2930. // Set the src to a short bit of url encoded as a silent mp3
  2931. // NOTE The silence MP3 must be high quality, when web audio sounds are played
  2932. // in parallel the web audio sound is mixed to match the bitrate of the html sound
  2933. // 0.01 seconds of silence VBR220-260 Joint Stereo 859B
  2934. var audioData = "data:audio/mpeg;base64,//uQxAAAAAAAAAAAAAAAAAAAAAAAWGluZwAAAA8AAAACAAACcQCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA//////////////////////////////////////////////////////////////////8AAABhTEFNRTMuMTAwA8MAAAAAAAAAABQgJAUHQQAB9AAAAnGMHkkIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//sQxAADgnABGiAAQBCqgCRMAAgEAH///////////////7+n/9FTuQsQH//////2NG0jWUGlio5gLQTOtIoeR2WX////X4s9Atb/JRVCbBUpeRUq//////////////////9RUi0f2jn/+xDECgPCjAEQAABN4AAANIAAAAQVTEFNRTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVQ=="; // disable iOS Airplay (setting the attribute in js doesn't work)
  2935. var tmp = document.createElement("div");
  2936. tmp.innerHTML = '<audio x-webkit-airplay="deny"></audio>';
  2937. var audioSilentMode = tmp.children.item(0);
  2938. audioSilentMode.src = audioData;
  2939. audioSilentMode.preload = "auto";
  2940. audioSilentMode.type = "audio/mpeg";
  2941. audioSilentMode.disableRemotePlayback = true; // play
  2942. audioSilentMode.play(); // cleanup
  2943. audioSilentMode.remove();
  2944. tmp.remove();
  2945. }
  2946. module.exports = exports.default;
  2947. /***/ }),
  2948. /***/ "./src/util/style.js":
  2949. /*!***************************!*\
  2950. !*** ./src/util/style.js ***!
  2951. \***************************/
  2952. /***/ ((module, exports) => {
  2953. "use strict";
  2954. Object.defineProperty(exports, "__esModule", ({
  2955. value: true
  2956. }));
  2957. exports["default"] = style;
  2958. /**
  2959. * Apply a map of styles to an element
  2960. *
  2961. * @param {HTMLElement} el The element that the styles will be applied to
  2962. * @param {Object} styles The map of propName: attribute, both are used as-is
  2963. *
  2964. * @return {HTMLElement} el
  2965. */
  2966. function style(el, styles) {
  2967. Object.keys(styles).forEach(function (prop) {
  2968. if (el.style[prop] !== styles[prop]) {
  2969. el.style[prop] = styles[prop];
  2970. }
  2971. });
  2972. return el;
  2973. }
  2974. module.exports = exports.default;
  2975. /***/ }),
  2976. /***/ "./src/wavesurfer.js":
  2977. /*!***************************!*\
  2978. !*** ./src/wavesurfer.js ***!
  2979. \***************************/
  2980. /***/ ((module, exports, __webpack_require__) => {
  2981. "use strict";
  2982. function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
  2983. Object.defineProperty(exports, "__esModule", ({
  2984. value: true
  2985. }));
  2986. exports["default"] = void 0;
  2987. var util = _interopRequireWildcard(__webpack_require__(/*! ./util */ "./src/util/index.js"));
  2988. var _drawer = _interopRequireDefault(__webpack_require__(/*! ./drawer.multicanvas */ "./src/drawer.multicanvas.js"));
  2989. var _webaudio = _interopRequireDefault(__webpack_require__(/*! ./webaudio */ "./src/webaudio.js"));
  2990. var _mediaelement = _interopRequireDefault(__webpack_require__(/*! ./mediaelement */ "./src/mediaelement.js"));
  2991. var _peakcache = _interopRequireDefault(__webpack_require__(/*! ./peakcache */ "./src/peakcache.js"));
  2992. var _mediaelementWebaudio = _interopRequireDefault(__webpack_require__(/*! ./mediaelement-webaudio */ "./src/mediaelement-webaudio.js"));
  2993. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  2994. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  2995. function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  2996. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
  2997. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  2998. function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
  2999. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
  3000. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  3001. function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
  3002. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  3003. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  3004. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  3005. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  3006. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  3007. /*
  3008. * This work is licensed under a BSD-3-Clause License.
  3009. */
  3010. /** @external {HTMLElement} https://developer.mozilla.org/en/docs/Web/API/HTMLElement */
  3011. /** @external {OfflineAudioContext} https://developer.mozilla.org/en-US/docs/Web/API/OfflineAudioContext */
  3012. /** @external {File} https://developer.mozilla.org/en-US/docs/Web/API/File */
  3013. /** @external {Blob} https://developer.mozilla.org/en-US/docs/Web/API/Blob */
  3014. /** @external {CanvasRenderingContext2D} https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D */
  3015. /** @external {MediaStreamConstraints} https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints */
  3016. /** @external {AudioNode} https://developer.mozilla.org/de/docs/Web/API/AudioNode */
  3017. /**
  3018. * @typedef {Object} WavesurferParams
  3019. * @property {AudioContext} audioContext=null Use your own previously
  3020. * initialized AudioContext or leave blank.
  3021. * @property {number} audioRate=1 Speed at which to play audio. Lower number is
  3022. * slower.
  3023. * @property {ScriptProcessorNode} audioScriptProcessor=null Use your own previously
  3024. * initialized ScriptProcessorNode or leave blank.
  3025. * @property {boolean} autoCenter=true If a scrollbar is present, center the
  3026. * waveform on current progress
  3027. * @property {number} autoCenterRate=5 If autoCenter is active, rate at which the
  3028. * waveform is centered
  3029. * @property {boolean} autoCenterImmediately=false If autoCenter is active, immediately
  3030. * center waveform on current progress
  3031. * @property {string} backend='WebAudio' `'WebAudio'|'MediaElement'|'MediaElementWebAudio'` In most cases
  3032. * you don't have to set this manually. MediaElement is a fallback for unsupported browsers.
  3033. * MediaElementWebAudio allows to use WebAudio API also with big audio files, loading audio like with
  3034. * MediaElement backend (HTML5 audio tag). You have to use the same methods of MediaElement backend for loading and
  3035. * playback, giving also peaks, so the audio data are not decoded. In this way you can use WebAudio features, like filters,
  3036. * also with audio with big duration. For example:
  3037. * ` wavesurfer.load(url | HTMLMediaElement, peaks, preload, duration);
  3038. * wavesurfer.play();
  3039. * wavesurfer.setFilter(customFilter);
  3040. * `
  3041. * @property {string} backgroundColor=null Change background color of the
  3042. * waveform container.
  3043. * @property {number} barHeight=1 The height of the wave bars.
  3044. * @property {number} barRadius=0 The radius of the wave bars. Makes bars rounded
  3045. * @property {number} barGap=null The optional spacing between bars of the wave,
  3046. * if not provided will be calculated in legacy format.
  3047. * @property {number} barWidth=null Draw the waveform using bars.
  3048. * @property {number} barMinHeight=null If specified, draw at least a bar of this height,
  3049. * eliminating waveform gaps
  3050. * @property {boolean} closeAudioContext=false Close and nullify all audio
  3051. * contexts when the destroy method is called.
  3052. * @property {!string|HTMLElement} container CSS selector or HTML element where
  3053. * the waveform should be drawn. This is the only required parameter.
  3054. * @property {string} cursorColor='#333' The fill color of the cursor indicating
  3055. * the playhead position.
  3056. * @property {number} cursorWidth=1 Measured in pixels.
  3057. * @property {object} drawingContextAttributes={desynchronized: false} Drawing context
  3058. * attributes.
  3059. * @property {number} duration=null Optional audio length so pre-rendered peaks
  3060. * can be display immediately for example.
  3061. * @property {boolean} fillParent=true Whether to fill the entire container or
  3062. * draw only according to `minPxPerSec`.
  3063. * @property {boolean} forceDecode=false Force decoding of audio using web audio
  3064. * when zooming to get a more detailed waveform.
  3065. * @property {number} height=128 The height of the waveform. Measured in
  3066. * pixels.
  3067. * @property {boolean} hideScrollbar=false Whether to hide the horizontal
  3068. * scrollbar when one would normally be shown.
  3069. * @property {boolean} hideCursor=false Whether to hide the mouse cursor
  3070. * when one would normally be shown by default.
  3071. * @property {boolean} ignoreSilenceMode=false If true, ignores device silence mode
  3072. * when using the `WebAudio` backend.
  3073. * @property {boolean} interact=true Whether the mouse interaction will be
  3074. * enabled at initialization. You can switch this parameter at any time later
  3075. * on.
  3076. * @property {boolean} loopSelection=true (Use with regions plugin) Enable
  3077. * looping of selected regions
  3078. * @property {number} maxCanvasWidth=4000 Maximum width of a single canvas in
  3079. * pixels, excluding a small overlap (2 * `pixelRatio`, rounded up to the next
  3080. * even integer). If the waveform is longer than this value, additional canvases
  3081. * will be used to render the waveform, which is useful for very large waveforms
  3082. * that may be too wide for browsers to draw on a single canvas.
  3083. * @property {boolean} mediaControls=false (Use with backend `MediaElement` or `MediaElementWebAudio`)
  3084. * this enables the native controls for the media element
  3085. * @property {string} mediaType='audio' (Use with backend `MediaElement` or `MediaElementWebAudio`)
  3086. * `'audio'|'video'` ('video' only for `MediaElement`)
  3087. * @property {number} minPxPerSec=20 Minimum number of pixels per second of
  3088. * audio.
  3089. * @property {boolean} normalize=false If true, normalize by the maximum peak
  3090. * instead of 1.0.
  3091. * @property {boolean} partialRender=false Use the PeakCache to improve
  3092. * rendering speed of large waveforms
  3093. * @property {number} pixelRatio=window.devicePixelRatio The pixel ratio used to
  3094. * calculate display
  3095. * @property {PluginDefinition[]} plugins=[] An array of plugin definitions to
  3096. * register during instantiation, they will be directly initialised unless they
  3097. * are added with the `deferInit` property set to true.
  3098. * @property {string} progressColor='#555' The fill color of the part of the
  3099. * waveform behind the cursor. When `progressColor` and `waveColor` are the same
  3100. * the progress wave is not rendered at all.
  3101. * @property {boolean} removeMediaElementOnDestroy=true Set to false to keep the
  3102. * media element in the DOM when the player is destroyed. This is useful when
  3103. * reusing an existing media element via the `loadMediaElement` method.
  3104. * @property {Object} renderer=MultiCanvas Can be used to inject a custom
  3105. * renderer.
  3106. * @property {boolean|number} responsive=false If set to `true` resize the
  3107. * waveform, when the window is resized. This is debounced with a `100ms`
  3108. * timeout by default. If this parameter is a number it represents that timeout.
  3109. * @property {boolean} rtl=false If set to `true`, renders waveform from
  3110. * right-to-left.
  3111. * @property {boolean} scrollParent=false Whether to scroll the container with a
  3112. * lengthy waveform. Otherwise the waveform is shrunk to the container width
  3113. * (see fillParent).
  3114. * @property {number} skipLength=2 Number of seconds to skip with the
  3115. * skipForward() and skipBackward() methods.
  3116. * @property {boolean} splitChannels=false Render with separate waveforms for
  3117. * the channels of the audio
  3118. * @property {SplitChannelOptions} splitChannelsOptions={} Options for splitChannel rendering
  3119. * @property {boolean} vertical=false Render the waveform vertically instead of horizontally.
  3120. * @property {string} waveColor='#999' The fill color of the waveform after the
  3121. * cursor.
  3122. * @property {object} xhr={} XHR options. For example:
  3123. * `let xhr = {
  3124. * cache: 'default',
  3125. * mode: 'cors',
  3126. * method: 'GET',
  3127. * credentials: 'same-origin',
  3128. * redirect: 'follow',
  3129. * referrer: 'client',
  3130. * requestHeaders: [
  3131. * {
  3132. * key: 'Authorization',
  3133. * value: 'my-token'
  3134. * }
  3135. * ]
  3136. * };`
  3137. */
  3138. /**
  3139. * @typedef {Object} PluginDefinition
  3140. * @desc The Object used to describe a plugin
  3141. * @example wavesurfer.addPlugin(pluginDefinition);
  3142. * @property {string} name The name of the plugin, the plugin instance will be
  3143. * added as a property to the wavesurfer instance under this name
  3144. * @property {?Object} staticProps The properties that should be added to the
  3145. * wavesurfer instance as static properties
  3146. * @property {?boolean} deferInit Don't initialise plugin
  3147. * automatically
  3148. * @property {Object} params={} The plugin parameters, they are the first parameter
  3149. * passed to the plugin class constructor function
  3150. * @property {PluginClass} instance The plugin instance factory, is called with
  3151. * the dependency specified in extends. Returns the plugin class.
  3152. */
  3153. /**
  3154. * @typedef {Object} SplitChannelOptions
  3155. * @desc parameters applied when splitChannels option is true
  3156. * @property {boolean} overlay=false determines whether channels are rendered on top of each other or on separate tracks
  3157. * @property {object} channelColors={} object describing color for each channel. Example:
  3158. * {
  3159. * 0: {
  3160. * progressColor: 'green',
  3161. * waveColor: 'pink'
  3162. * },
  3163. * 1: {
  3164. * progressColor: 'orange',
  3165. * waveColor: 'purple'
  3166. * }
  3167. * }
  3168. * @property {number[]} filterChannels=[] indexes of channels to be hidden from rendering
  3169. * @property {boolean} relativeNormalization=false determines whether
  3170. * normalization is done per channel or maintains proportionality between
  3171. * channels. Only applied when normalize and splitChannels are both true.
  3172. * @since 4.3.0
  3173. */
  3174. /**
  3175. * @interface PluginClass
  3176. *
  3177. * @desc This is the interface which is implemented by all plugin classes. Note
  3178. * that this only turns into an observer after being passed through
  3179. * `wavesurfer.addPlugin`.
  3180. *
  3181. * @extends {Observer}
  3182. */
  3183. var PluginClass = /*#__PURE__*/function () {
  3184. /**
  3185. * Construct the plugin
  3186. *
  3187. * @param {Object} params={} The plugin params (specific to the plugin)
  3188. * @param {Object} ws The wavesurfer instance
  3189. */
  3190. function PluginClass(params, ws) {
  3191. _classCallCheck(this, PluginClass);
  3192. }
  3193. /**
  3194. * Initialise the plugin
  3195. *
  3196. * Start doing something. This is called by
  3197. * `wavesurfer.initPlugin(pluginName)`
  3198. */
  3199. _createClass(PluginClass, [{
  3200. key: "create",
  3201. value:
  3202. /**
  3203. * Plugin definition factory
  3204. *
  3205. * This function must be used to create a plugin definition which can be
  3206. * used by wavesurfer to correctly instantiate the plugin.
  3207. *
  3208. * It returns a `PluginDefinition` object representing the plugin.
  3209. *
  3210. * @param {Object} params={} The plugin params (specific to the plugin)
  3211. */
  3212. function create(params) {}
  3213. }, {
  3214. key: "init",
  3215. value: function init() {}
  3216. /**
  3217. * Destroy the plugin instance
  3218. *
  3219. * Stop doing something. This is called by
  3220. * `wavesurfer.destroyPlugin(pluginName)`
  3221. */
  3222. }, {
  3223. key: "destroy",
  3224. value: function destroy() {}
  3225. }]);
  3226. return PluginClass;
  3227. }();
  3228. /**
  3229. * WaveSurfer core library class
  3230. *
  3231. * @extends {Observer}
  3232. * @example
  3233. * const params = {
  3234. * container: '#waveform',
  3235. * waveColor: 'violet',
  3236. * progressColor: 'purple'
  3237. * };
  3238. *
  3239. * // initialise like this
  3240. * const wavesurfer = WaveSurfer.create(params);
  3241. *
  3242. * // or like this ...
  3243. * const wavesurfer = new WaveSurfer(params);
  3244. * wavesurfer.init();
  3245. *
  3246. * // load audio file
  3247. * wavesurfer.load('example/media/demo.wav');
  3248. */
  3249. var WaveSurfer = /*#__PURE__*/function (_util$Observer) {
  3250. _inherits(WaveSurfer, _util$Observer);
  3251. var _super = _createSuper(WaveSurfer);
  3252. /**
  3253. * Initialise wavesurfer instance
  3254. *
  3255. * @param {WavesurferParams} params Instantiation options for wavesurfer
  3256. * @example
  3257. * const wavesurfer = new WaveSurfer(params);
  3258. * @returns {this} Wavesurfer instance
  3259. */
  3260. function WaveSurfer(params) {
  3261. var _this;
  3262. _classCallCheck(this, WaveSurfer);
  3263. _this = _super.call(this);
  3264. /**
  3265. * Extract relevant parameters (or defaults)
  3266. * @private
  3267. */
  3268. _defineProperty(_assertThisInitialized(_this), "defaultParams", {
  3269. audioContext: null,
  3270. audioScriptProcessor: null,
  3271. audioRate: 1,
  3272. autoCenter: true,
  3273. autoCenterRate: 5,
  3274. autoCenterImmediately: false,
  3275. backend: 'WebAudio',
  3276. backgroundColor: null,
  3277. barHeight: 1,
  3278. barRadius: 0,
  3279. barGap: null,
  3280. barMinHeight: null,
  3281. container: null,
  3282. cursorColor: '#333',
  3283. cursorWidth: 1,
  3284. dragSelection: true,
  3285. drawingContextAttributes: {
  3286. // Boolean that hints the user agent to reduce the latency
  3287. // by desynchronizing the canvas paint cycle from the event
  3288. // loop
  3289. desynchronized: false
  3290. },
  3291. duration: null,
  3292. fillParent: true,
  3293. forceDecode: false,
  3294. height: 128,
  3295. hideScrollbar: false,
  3296. hideCursor: false,
  3297. ignoreSilenceMode: false,
  3298. interact: true,
  3299. loopSelection: true,
  3300. maxCanvasWidth: 4000,
  3301. mediaContainer: null,
  3302. mediaControls: false,
  3303. mediaType: 'audio',
  3304. minPxPerSec: 20,
  3305. normalize: false,
  3306. partialRender: false,
  3307. pixelRatio: window.devicePixelRatio || screen.deviceXDPI / screen.logicalXDPI,
  3308. plugins: [],
  3309. progressColor: '#555',
  3310. removeMediaElementOnDestroy: true,
  3311. renderer: _drawer.default,
  3312. responsive: false,
  3313. rtl: false,
  3314. scrollParent: false,
  3315. skipLength: 2,
  3316. splitChannels: false,
  3317. splitChannelsOptions: {
  3318. overlay: false,
  3319. channelColors: {},
  3320. filterChannels: [],
  3321. relativeNormalization: false
  3322. },
  3323. vertical: false,
  3324. waveColor: '#999',
  3325. xhr: {}
  3326. });
  3327. _defineProperty(_assertThisInitialized(_this), "backends", {
  3328. MediaElement: _mediaelement.default,
  3329. WebAudio: _webaudio.default,
  3330. MediaElementWebAudio: _mediaelementWebaudio.default
  3331. });
  3332. _defineProperty(_assertThisInitialized(_this), "util", util);
  3333. _this.params = Object.assign({}, _this.defaultParams, params);
  3334. _this.params.splitChannelsOptions = Object.assign({}, _this.defaultParams.splitChannelsOptions, params.splitChannelsOptions);
  3335. /** @private */
  3336. _this.container = 'string' == typeof params.container ? document.querySelector(_this.params.container) : _this.params.container;
  3337. if (!_this.container) {
  3338. throw new Error('Container element not found');
  3339. }
  3340. if (_this.params.mediaContainer == null) {
  3341. /** @private */
  3342. _this.mediaContainer = _this.container;
  3343. } else if (typeof _this.params.mediaContainer == 'string') {
  3344. /** @private */
  3345. _this.mediaContainer = document.querySelector(_this.params.mediaContainer);
  3346. } else {
  3347. /** @private */
  3348. _this.mediaContainer = _this.params.mediaContainer;
  3349. }
  3350. if (!_this.mediaContainer) {
  3351. throw new Error('Media Container element not found');
  3352. }
  3353. if (_this.params.maxCanvasWidth <= 1) {
  3354. throw new Error('maxCanvasWidth must be greater than 1');
  3355. } else if (_this.params.maxCanvasWidth % 2 == 1) {
  3356. throw new Error('maxCanvasWidth must be an even number');
  3357. }
  3358. if (_this.params.rtl === true) {
  3359. if (_this.params.vertical === true) {
  3360. util.style(_this.container, {
  3361. transform: 'rotateX(180deg)'
  3362. });
  3363. } else {
  3364. util.style(_this.container, {
  3365. transform: 'rotateY(180deg)'
  3366. });
  3367. }
  3368. }
  3369. if (_this.params.backgroundColor) {
  3370. _this.setBackgroundColor(_this.params.backgroundColor);
  3371. }
  3372. /**
  3373. * @private Used to save the current volume when muting so we can
  3374. * restore once unmuted
  3375. * @type {number}
  3376. */
  3377. _this.savedVolume = 0;
  3378. /**
  3379. * @private The current muted state
  3380. * @type {boolean}
  3381. */
  3382. _this.isMuted = false;
  3383. /**
  3384. * @private Will hold a list of event descriptors that need to be
  3385. * canceled on subsequent loads of audio
  3386. * @type {Object[]}
  3387. */
  3388. _this.tmpEvents = [];
  3389. /**
  3390. * @private Holds any running audio downloads
  3391. * @type {Observer}
  3392. */
  3393. _this.currentRequest = null;
  3394. /** @private */
  3395. _this.arraybuffer = null;
  3396. /** @private */
  3397. _this.drawer = null;
  3398. /** @private */
  3399. _this.backend = null;
  3400. /** @private */
  3401. _this.peakCache = null; // cache constructor objects
  3402. if (typeof _this.params.renderer !== 'function') {
  3403. throw new Error('Renderer parameter is invalid');
  3404. }
  3405. /**
  3406. * @private The uninitialised Drawer class
  3407. */
  3408. _this.Drawer = _this.params.renderer;
  3409. /**
  3410. * @private The uninitialised Backend class
  3411. */
  3412. // Back compat
  3413. if (_this.params.backend == 'AudioElement') {
  3414. _this.params.backend = 'MediaElement';
  3415. }
  3416. if ((_this.params.backend == 'WebAudio' || _this.params.backend === 'MediaElementWebAudio') && !_webaudio.default.prototype.supportsWebAudio.call(null)) {
  3417. _this.params.backend = 'MediaElement';
  3418. }
  3419. _this.Backend = _this.backends[_this.params.backend];
  3420. /**
  3421. * @private map of plugin names that are currently initialised
  3422. */
  3423. _this.initialisedPluginList = {};
  3424. /** @private */
  3425. _this.isDestroyed = false;
  3426. /**
  3427. * Get the current ready status.
  3428. *
  3429. * @example const isReady = wavesurfer.isReady;
  3430. * @return {boolean}
  3431. */
  3432. _this.isReady = false; // responsive debounced event listener. If this.params.responsive is not
  3433. // set, this is never called. Use 100ms or this.params.responsive as
  3434. // timeout for the debounce function.
  3435. var prevWidth = 0;
  3436. _this._onResize = util.debounce(function () {
  3437. if (prevWidth != _this.drawer.wrapper.clientWidth && !_this.params.scrollParent) {
  3438. prevWidth = _this.drawer.wrapper.clientWidth;
  3439. if (prevWidth) {
  3440. // redraw only if waveform container is rendered and has a width
  3441. _this.drawer.fireEvent('redraw');
  3442. }
  3443. }
  3444. }, typeof _this.params.responsive === 'number' ? _this.params.responsive : 100);
  3445. return _possibleConstructorReturn(_this, _assertThisInitialized(_this));
  3446. }
  3447. /**
  3448. * Initialise the wave
  3449. *
  3450. * @example
  3451. * var wavesurfer = new WaveSurfer(params);
  3452. * wavesurfer.init();
  3453. * @return {this} The wavesurfer instance
  3454. */
  3455. _createClass(WaveSurfer, [{
  3456. key: "init",
  3457. value: function init() {
  3458. this.registerPlugins(this.params.plugins);
  3459. this.createDrawer();
  3460. this.createBackend();
  3461. this.createPeakCache();
  3462. return this;
  3463. }
  3464. /**
  3465. * Add and initialise array of plugins (if `plugin.deferInit` is falsey),
  3466. * this function is called in the init function of wavesurfer
  3467. *
  3468. * @param {PluginDefinition[]} plugins An array of plugin definitions
  3469. * @emits {WaveSurfer#plugins-registered} Called with the array of plugin definitions
  3470. * @return {this} The wavesurfer instance
  3471. */
  3472. }, {
  3473. key: "registerPlugins",
  3474. value: function registerPlugins(plugins) {
  3475. var _this2 = this;
  3476. // first instantiate all the plugins
  3477. plugins.forEach(function (plugin) {
  3478. return _this2.addPlugin(plugin);
  3479. }); // now run the init functions
  3480. plugins.forEach(function (plugin) {
  3481. // call init function of the plugin if deferInit is falsey
  3482. // in that case you would manually use initPlugins()
  3483. if (!plugin.deferInit) {
  3484. _this2.initPlugin(plugin.name);
  3485. }
  3486. });
  3487. this.fireEvent('plugins-registered', plugins);
  3488. return this;
  3489. }
  3490. /**
  3491. * Get a map of plugin names that are currently initialised
  3492. *
  3493. * @example wavesurfer.getPlugins();
  3494. * @return {Object} Object with plugin names
  3495. */
  3496. }, {
  3497. key: "getActivePlugins",
  3498. value: function getActivePlugins() {
  3499. return this.initialisedPluginList;
  3500. }
  3501. /**
  3502. * Add a plugin object to wavesurfer
  3503. *
  3504. * @param {PluginDefinition} plugin A plugin definition
  3505. * @emits {WaveSurfer#plugin-added} Called with the name of the plugin that was added
  3506. * @example wavesurfer.addPlugin(WaveSurfer.minimap());
  3507. * @return {this} The wavesurfer instance
  3508. */
  3509. }, {
  3510. key: "addPlugin",
  3511. value: function addPlugin(plugin) {
  3512. var _this3 = this;
  3513. if (!plugin.name) {
  3514. throw new Error('Plugin does not have a name!');
  3515. }
  3516. if (!plugin.instance) {
  3517. throw new Error("Plugin ".concat(plugin.name, " does not have an instance property!"));
  3518. } // staticProps properties are applied to wavesurfer instance
  3519. if (plugin.staticProps) {
  3520. Object.keys(plugin.staticProps).forEach(function (pluginStaticProp) {
  3521. /**
  3522. * Properties defined in a plugin definition's `staticProps` property are added as
  3523. * staticProps properties of the WaveSurfer instance
  3524. */
  3525. _this3[pluginStaticProp] = plugin.staticProps[pluginStaticProp];
  3526. });
  3527. }
  3528. var Instance = plugin.instance; // turn the plugin instance into an observer
  3529. var observerPrototypeKeys = Object.getOwnPropertyNames(util.Observer.prototype);
  3530. observerPrototypeKeys.forEach(function (key) {
  3531. Instance.prototype[key] = util.Observer.prototype[key];
  3532. });
  3533. /**
  3534. * Instantiated plugin classes are added as a property of the wavesurfer
  3535. * instance
  3536. * @type {Object}
  3537. */
  3538. this[plugin.name] = new Instance(plugin.params || {}, this);
  3539. this.fireEvent('plugin-added', plugin.name);
  3540. return this;
  3541. }
  3542. /**
  3543. * Initialise a plugin
  3544. *
  3545. * @param {string} name A plugin name
  3546. * @emits WaveSurfer#plugin-initialised
  3547. * @example wavesurfer.initPlugin('minimap');
  3548. * @return {this} The wavesurfer instance
  3549. */
  3550. }, {
  3551. key: "initPlugin",
  3552. value: function initPlugin(name) {
  3553. if (!this[name]) {
  3554. throw new Error("Plugin ".concat(name, " has not been added yet!"));
  3555. }
  3556. if (this.initialisedPluginList[name]) {
  3557. // destroy any already initialised plugins
  3558. this.destroyPlugin(name);
  3559. }
  3560. this[name].init();
  3561. this.initialisedPluginList[name] = true;
  3562. this.fireEvent('plugin-initialised', name);
  3563. return this;
  3564. }
  3565. /**
  3566. * Destroy a plugin
  3567. *
  3568. * @param {string} name A plugin name
  3569. * @emits WaveSurfer#plugin-destroyed
  3570. * @example wavesurfer.destroyPlugin('minimap');
  3571. * @returns {this} The wavesurfer instance
  3572. */
  3573. }, {
  3574. key: "destroyPlugin",
  3575. value: function destroyPlugin(name) {
  3576. if (!this[name]) {
  3577. throw new Error("Plugin ".concat(name, " has not been added yet and cannot be destroyed!"));
  3578. }
  3579. if (!this.initialisedPluginList[name]) {
  3580. throw new Error("Plugin ".concat(name, " is not active and cannot be destroyed!"));
  3581. }
  3582. if (typeof this[name].destroy !== 'function') {
  3583. throw new Error("Plugin ".concat(name, " does not have a destroy function!"));
  3584. }
  3585. this[name].destroy();
  3586. delete this.initialisedPluginList[name];
  3587. this.fireEvent('plugin-destroyed', name);
  3588. return this;
  3589. }
  3590. /**
  3591. * Destroy all initialised plugins. Convenience function to use when
  3592. * wavesurfer is removed
  3593. *
  3594. * @private
  3595. */
  3596. }, {
  3597. key: "destroyAllPlugins",
  3598. value: function destroyAllPlugins() {
  3599. var _this4 = this;
  3600. Object.keys(this.initialisedPluginList).forEach(function (name) {
  3601. return _this4.destroyPlugin(name);
  3602. });
  3603. }
  3604. /**
  3605. * Create the drawer and draw the waveform
  3606. *
  3607. * @private
  3608. * @emits WaveSurfer#drawer-created
  3609. */
  3610. }, {
  3611. key: "createDrawer",
  3612. value: function createDrawer() {
  3613. var _this5 = this;
  3614. this.drawer = new this.Drawer(this.container, this.params);
  3615. this.drawer.init();
  3616. this.fireEvent('drawer-created', this.drawer);
  3617. if (this.params.responsive !== false) {
  3618. window.addEventListener('resize', this._onResize, true);
  3619. window.addEventListener('orientationchange', this._onResize, true);
  3620. }
  3621. this.drawer.on('redraw', function () {
  3622. _this5.drawBuffer();
  3623. _this5.drawer.progress(_this5.backend.getPlayedPercents());
  3624. }); // Click-to-seek
  3625. this.drawer.on('click', function (e, progress) {
  3626. setTimeout(function () {
  3627. return _this5.seekTo(progress);
  3628. }, 0);
  3629. }); // Relay the scroll event from the drawer
  3630. this.drawer.on('scroll', function (e) {
  3631. if (_this5.params.partialRender) {
  3632. _this5.drawBuffer();
  3633. }
  3634. _this5.fireEvent('scroll', e);
  3635. });
  3636. }
  3637. /**
  3638. * Create the backend
  3639. *
  3640. * @private
  3641. * @emits WaveSurfer#backend-created
  3642. */
  3643. }, {
  3644. key: "createBackend",
  3645. value: function createBackend() {
  3646. var _this6 = this;
  3647. if (this.backend) {
  3648. this.backend.destroy();
  3649. }
  3650. this.backend = new this.Backend(this.params);
  3651. this.backend.init();
  3652. this.fireEvent('backend-created', this.backend);
  3653. this.backend.on('finish', function () {
  3654. _this6.drawer.progress(_this6.backend.getPlayedPercents());
  3655. _this6.fireEvent('finish');
  3656. });
  3657. this.backend.on('play', function () {
  3658. return _this6.fireEvent('play');
  3659. });
  3660. this.backend.on('pause', function () {
  3661. return _this6.fireEvent('pause');
  3662. });
  3663. this.backend.on('audioprocess', function (time) {
  3664. _this6.drawer.progress(_this6.backend.getPlayedPercents());
  3665. _this6.fireEvent('audioprocess', time);
  3666. }); // only needed for MediaElement and MediaElementWebAudio backend
  3667. if (this.params.backend === 'MediaElement' || this.params.backend === 'MediaElementWebAudio') {
  3668. this.backend.on('seek', function () {
  3669. _this6.drawer.progress(_this6.backend.getPlayedPercents());
  3670. });
  3671. this.backend.on('volume', function () {
  3672. var newVolume = _this6.getVolume();
  3673. _this6.fireEvent('volume', newVolume);
  3674. if (_this6.backend.isMuted !== _this6.isMuted) {
  3675. _this6.isMuted = _this6.backend.isMuted;
  3676. _this6.fireEvent('mute', _this6.isMuted);
  3677. }
  3678. });
  3679. }
  3680. }
  3681. /**
  3682. * Create the peak cache
  3683. *
  3684. * @private
  3685. */
  3686. }, {
  3687. key: "createPeakCache",
  3688. value: function createPeakCache() {
  3689. if (this.params.partialRender) {
  3690. this.peakCache = new _peakcache.default();
  3691. }
  3692. }
  3693. /**
  3694. * Get the duration of the audio clip
  3695. *
  3696. * @example const duration = wavesurfer.getDuration();
  3697. * @return {number} Duration in seconds
  3698. */
  3699. }, {
  3700. key: "getDuration",
  3701. value: function getDuration() {
  3702. return this.backend.getDuration();
  3703. }
  3704. /**
  3705. * Get the current playback position
  3706. *
  3707. * @example const currentTime = wavesurfer.getCurrentTime();
  3708. * @return {number} Playback position in seconds
  3709. */
  3710. }, {
  3711. key: "getCurrentTime",
  3712. value: function getCurrentTime() {
  3713. return this.backend.getCurrentTime();
  3714. }
  3715. /**
  3716. * Set the current play time in seconds.
  3717. *
  3718. * @param {number} seconds A positive number in seconds. E.g. 10 means 10
  3719. * seconds, 60 means 1 minute
  3720. */
  3721. }, {
  3722. key: "setCurrentTime",
  3723. value: function setCurrentTime(seconds) {
  3724. if (seconds >= this.getDuration()) {
  3725. this.seekTo(1);
  3726. } else {
  3727. this.seekTo(seconds / this.getDuration());
  3728. }
  3729. }
  3730. /**
  3731. * Starts playback from the current position. Optional start and end
  3732. * measured in seconds can be used to set the range of audio to play.
  3733. *
  3734. * @param {?number} start Position to start at
  3735. * @param {?number} end Position to end at
  3736. * @emits WaveSurfer#interaction
  3737. * @return {Promise} Result of the backend play method
  3738. * @example
  3739. * // play from second 1 to 5
  3740. * wavesurfer.play(1, 5);
  3741. */
  3742. }, {
  3743. key: "play",
  3744. value: function play(start, end) {
  3745. var _this7 = this;
  3746. if (this.params.ignoreSilenceMode) {
  3747. // ignores device hardware silence mode
  3748. util.ignoreSilenceMode();
  3749. }
  3750. this.fireEvent('interaction', function () {
  3751. return _this7.play(start, end);
  3752. });
  3753. return this.backend.play(start, end);
  3754. }
  3755. /**
  3756. * Set a point in seconds for playback to stop at.
  3757. *
  3758. * @param {number} position Position (in seconds) to stop at
  3759. * @version 3.3.0
  3760. */
  3761. }, {
  3762. key: "setPlayEnd",
  3763. value: function setPlayEnd(position) {
  3764. this.backend.setPlayEnd(position);
  3765. }
  3766. /**
  3767. * Stops and pauses playback
  3768. *
  3769. * @example wavesurfer.pause();
  3770. * @return {Promise} Result of the backend pause method
  3771. */
  3772. }, {
  3773. key: "pause",
  3774. value: function pause() {
  3775. if (!this.backend.isPaused()) {
  3776. return this.backend.pause();
  3777. }
  3778. }
  3779. /**
  3780. * Toggle playback
  3781. *
  3782. * @example wavesurfer.playPause();
  3783. * @return {Promise} Result of the backend play or pause method
  3784. */
  3785. }, {
  3786. key: "playPause",
  3787. value: function playPause() {
  3788. return this.backend.isPaused() ? this.play() : this.pause();
  3789. }
  3790. /**
  3791. * Get the current playback state
  3792. *
  3793. * @example const isPlaying = wavesurfer.isPlaying();
  3794. * @return {boolean} False if paused, true if playing
  3795. */
  3796. }, {
  3797. key: "isPlaying",
  3798. value: function isPlaying() {
  3799. return !this.backend.isPaused();
  3800. }
  3801. /**
  3802. * Skip backward
  3803. *
  3804. * @param {?number} seconds Amount to skip back, if not specified `skipLength`
  3805. * is used
  3806. * @example wavesurfer.skipBackward();
  3807. */
  3808. }, {
  3809. key: "skipBackward",
  3810. value: function skipBackward(seconds) {
  3811. this.skip(-seconds || -this.params.skipLength);
  3812. }
  3813. /**
  3814. * Skip forward
  3815. *
  3816. * @param {?number} seconds Amount to skip back, if not specified `skipLength`
  3817. * is used
  3818. * @example wavesurfer.skipForward();
  3819. */
  3820. }, {
  3821. key: "skipForward",
  3822. value: function skipForward(seconds) {
  3823. this.skip(seconds || this.params.skipLength);
  3824. }
  3825. /**
  3826. * Skip a number of seconds from the current position (use a negative value
  3827. * to go backwards).
  3828. *
  3829. * @param {number} offset Amount to skip back or forwards
  3830. * @example
  3831. * // go back 2 seconds
  3832. * wavesurfer.skip(-2);
  3833. */
  3834. }, {
  3835. key: "skip",
  3836. value: function skip(offset) {
  3837. var duration = this.getDuration() || 1;
  3838. var position = this.getCurrentTime() || 0;
  3839. position = Math.max(0, Math.min(duration, position + (offset || 0)));
  3840. this.seekAndCenter(position / duration);
  3841. }
  3842. /**
  3843. * Seeks to a position and centers the view
  3844. *
  3845. * @param {number} progress Between 0 (=beginning) and 1 (=end)
  3846. * @example
  3847. * // seek and go to the middle of the audio
  3848. * wavesurfer.seekTo(0.5);
  3849. */
  3850. }, {
  3851. key: "seekAndCenter",
  3852. value: function seekAndCenter(progress) {
  3853. this.seekTo(progress);
  3854. this.drawer.recenter(progress);
  3855. }
  3856. /**
  3857. * Seeks to a position
  3858. *
  3859. * @param {number} progress Between 0 (=beginning) and 1 (=end)
  3860. * @emits WaveSurfer#interaction
  3861. * @emits WaveSurfer#seek
  3862. * @example
  3863. * // seek to the middle of the audio
  3864. * wavesurfer.seekTo(0.5);
  3865. */
  3866. }, {
  3867. key: "seekTo",
  3868. value: function seekTo(progress) {
  3869. var _this8 = this;
  3870. // return an error if progress is not a number between 0 and 1
  3871. if (typeof progress !== 'number' || !isFinite(progress) || progress < 0 || progress > 1) {
  3872. throw new Error('Error calling wavesurfer.seekTo, parameter must be a number between 0 and 1!');
  3873. }
  3874. this.fireEvent('interaction', function () {
  3875. return _this8.seekTo(progress);
  3876. });
  3877. var isWebAudioBackend = this.params.backend === 'WebAudio';
  3878. var paused = this.backend.isPaused();
  3879. if (isWebAudioBackend && !paused) {
  3880. this.backend.pause();
  3881. } // avoid small scrolls while paused seeking
  3882. var oldScrollParent = this.params.scrollParent;
  3883. this.params.scrollParent = false;
  3884. this.backend.seekTo(progress * this.getDuration());
  3885. this.drawer.progress(progress);
  3886. if (isWebAudioBackend && !paused) {
  3887. this.backend.play();
  3888. }
  3889. this.params.scrollParent = oldScrollParent;
  3890. this.fireEvent('seek', progress);
  3891. }
  3892. /**
  3893. * Stops and goes to the beginning.
  3894. *
  3895. * @example wavesurfer.stop();
  3896. */
  3897. }, {
  3898. key: "stop",
  3899. value: function stop() {
  3900. this.pause();
  3901. this.seekTo(0);
  3902. this.drawer.progress(0);
  3903. }
  3904. /**
  3905. * Sets the ID of the audio device to use for output and returns a Promise.
  3906. *
  3907. * @param {string} deviceId String value representing underlying output
  3908. * device
  3909. * @returns {Promise} `Promise` that resolves to `undefined` when there are
  3910. * no errors detected.
  3911. */
  3912. }, {
  3913. key: "setSinkId",
  3914. value: function setSinkId(deviceId) {
  3915. return this.backend.setSinkId(deviceId);
  3916. }
  3917. /**
  3918. * Set the playback volume.
  3919. *
  3920. * @param {number} newVolume A value between 0 and 1, 0 being no
  3921. * volume and 1 being full volume.
  3922. * @emits WaveSurfer#volume
  3923. */
  3924. }, {
  3925. key: "setVolume",
  3926. value: function setVolume(newVolume) {
  3927. this.backend.setVolume(newVolume);
  3928. this.fireEvent('volume', newVolume);
  3929. }
  3930. /**
  3931. * Get the playback volume.
  3932. *
  3933. * @return {number} A value between 0 and 1, 0 being no
  3934. * volume and 1 being full volume.
  3935. */
  3936. }, {
  3937. key: "getVolume",
  3938. value: function getVolume() {
  3939. return this.backend.getVolume();
  3940. }
  3941. /**
  3942. * Set the playback rate.
  3943. *
  3944. * @param {number} rate A positive number. E.g. 0.5 means half the normal
  3945. * speed, 2 means double speed and so on.
  3946. * @example wavesurfer.setPlaybackRate(2);
  3947. */
  3948. }, {
  3949. key: "setPlaybackRate",
  3950. value: function setPlaybackRate(rate) {
  3951. this.backend.setPlaybackRate(rate);
  3952. }
  3953. /**
  3954. * Get the playback rate.
  3955. *
  3956. * @return {number} The current playback rate.
  3957. */
  3958. }, {
  3959. key: "getPlaybackRate",
  3960. value: function getPlaybackRate() {
  3961. return this.backend.getPlaybackRate();
  3962. }
  3963. /**
  3964. * Toggle the volume on and off. If not currently muted it will save the
  3965. * current volume value and turn the volume off. If currently muted then it
  3966. * will restore the volume to the saved value, and then rest the saved
  3967. * value.
  3968. *
  3969. * @example wavesurfer.toggleMute();
  3970. */
  3971. }, {
  3972. key: "toggleMute",
  3973. value: function toggleMute() {
  3974. this.setMute(!this.isMuted);
  3975. }
  3976. /**
  3977. * Enable or disable muted audio
  3978. *
  3979. * @param {boolean} mute Specify `true` to mute audio.
  3980. * @emits WaveSurfer#volume
  3981. * @emits WaveSurfer#mute
  3982. * @example
  3983. * // unmute
  3984. * wavesurfer.setMute(false);
  3985. * console.log(wavesurfer.getMute()) // logs false
  3986. */
  3987. }, {
  3988. key: "setMute",
  3989. value: function setMute(mute) {
  3990. // ignore all muting requests if the audio is already in that state
  3991. if (mute === this.isMuted) {
  3992. this.fireEvent('mute', this.isMuted);
  3993. return;
  3994. }
  3995. if (this.backend.setMute) {
  3996. // Backends such as the MediaElement backend have their own handling
  3997. // of mute, let them handle it.
  3998. this.backend.setMute(mute);
  3999. this.isMuted = mute;
  4000. } else {
  4001. if (mute) {
  4002. // If currently not muted then save current volume,
  4003. // turn off the volume and update the mute properties
  4004. this.savedVolume = this.backend.getVolume();
  4005. this.backend.setVolume(0);
  4006. this.isMuted = true;
  4007. this.fireEvent('volume', 0);
  4008. } else {
  4009. // If currently muted then restore to the saved volume
  4010. // and update the mute properties
  4011. this.backend.setVolume(this.savedVolume);
  4012. this.isMuted = false;
  4013. this.fireEvent('volume', this.savedVolume);
  4014. }
  4015. }
  4016. this.fireEvent('mute', this.isMuted);
  4017. }
  4018. /**
  4019. * Get the current mute status.
  4020. *
  4021. * @example const isMuted = wavesurfer.getMute();
  4022. * @return {boolean} Current mute status
  4023. */
  4024. }, {
  4025. key: "getMute",
  4026. value: function getMute() {
  4027. return this.isMuted;
  4028. }
  4029. /**
  4030. * Get the list of current set filters as an array.
  4031. *
  4032. * Filters must be set with setFilters method first
  4033. *
  4034. * @return {array} List of enabled filters
  4035. */
  4036. }, {
  4037. key: "getFilters",
  4038. value: function getFilters() {
  4039. return this.backend.filters || [];
  4040. }
  4041. /**
  4042. * Toggles `scrollParent` and redraws
  4043. *
  4044. * @example wavesurfer.toggleScroll();
  4045. */
  4046. }, {
  4047. key: "toggleScroll",
  4048. value: function toggleScroll() {
  4049. this.params.scrollParent = !this.params.scrollParent;
  4050. this.drawBuffer();
  4051. }
  4052. /**
  4053. * Toggle mouse interaction
  4054. *
  4055. * @example wavesurfer.toggleInteraction();
  4056. */
  4057. }, {
  4058. key: "toggleInteraction",
  4059. value: function toggleInteraction() {
  4060. this.params.interact = !this.params.interact;
  4061. }
  4062. /**
  4063. * Get the fill color of the waveform after the cursor.
  4064. *
  4065. * @param {?number} channelIdx Optional index of the channel to get its wave color if splitChannels is true
  4066. * @return {string|object} A CSS color string, or an array of CSS color strings.
  4067. */
  4068. }, {
  4069. key: "getWaveColor",
  4070. value: function getWaveColor() {
  4071. var channelIdx = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
  4072. if (this.params.splitChannelsOptions.channelColors[channelIdx]) {
  4073. return this.params.splitChannelsOptions.channelColors[channelIdx].waveColor;
  4074. }
  4075. return this.params.waveColor;
  4076. }
  4077. /**
  4078. * Set the fill color of the waveform after the cursor.
  4079. *
  4080. * @param {string|object} color A CSS color string, or an array of CSS color strings.
  4081. * @param {?number} channelIdx Optional index of the channel to set its wave color if splitChannels is true
  4082. * @example wavesurfer.setWaveColor('#ddd');
  4083. */
  4084. }, {
  4085. key: "setWaveColor",
  4086. value: function setWaveColor(color) {
  4087. var channelIdx = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
  4088. if (this.params.splitChannelsOptions.channelColors[channelIdx]) {
  4089. this.params.splitChannelsOptions.channelColors[channelIdx].waveColor = color;
  4090. } else {
  4091. this.params.waveColor = color;
  4092. }
  4093. this.drawBuffer();
  4094. }
  4095. /**
  4096. * Get the fill color of the waveform behind the cursor.
  4097. *
  4098. * @param {?number} channelIdx Optional index of the channel to get its progress color if splitChannels is true
  4099. * @return {string|object} A CSS color string, or an array of CSS color strings.
  4100. */
  4101. }, {
  4102. key: "getProgressColor",
  4103. value: function getProgressColor() {
  4104. var channelIdx = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
  4105. if (this.params.splitChannelsOptions.channelColors[channelIdx]) {
  4106. return this.params.splitChannelsOptions.channelColors[channelIdx].progressColor;
  4107. }
  4108. return this.params.progressColor;
  4109. }
  4110. /**
  4111. * Set the fill color of the waveform behind the cursor.
  4112. *
  4113. * @param {string|object} color A CSS color string, or an array of CSS color strings.
  4114. * @param {?number} channelIdx Optional index of the channel to set its progress color if splitChannels is true
  4115. * @example wavesurfer.setProgressColor('#400');
  4116. */
  4117. }, {
  4118. key: "setProgressColor",
  4119. value: function setProgressColor(color, channelIdx) {
  4120. if (this.params.splitChannelsOptions.channelColors[channelIdx]) {
  4121. this.params.splitChannelsOptions.channelColors[channelIdx].progressColor = color;
  4122. } else {
  4123. this.params.progressColor = color;
  4124. }
  4125. this.drawBuffer();
  4126. }
  4127. /**
  4128. * Get the background color of the waveform container.
  4129. *
  4130. * @return {string} A CSS color string.
  4131. */
  4132. }, {
  4133. key: "getBackgroundColor",
  4134. value: function getBackgroundColor() {
  4135. return this.params.backgroundColor;
  4136. }
  4137. /**
  4138. * Set the background color of the waveform container.
  4139. *
  4140. * @param {string} color A CSS color string.
  4141. * @example wavesurfer.setBackgroundColor('#FF00FF');
  4142. */
  4143. }, {
  4144. key: "setBackgroundColor",
  4145. value: function setBackgroundColor(color) {
  4146. this.params.backgroundColor = color;
  4147. util.style(this.container, {
  4148. background: this.params.backgroundColor
  4149. });
  4150. }
  4151. /**
  4152. * Get the fill color of the cursor indicating the playhead
  4153. * position.
  4154. *
  4155. * @return {string} A CSS color string.
  4156. */
  4157. }, {
  4158. key: "getCursorColor",
  4159. value: function getCursorColor() {
  4160. return this.params.cursorColor;
  4161. }
  4162. /**
  4163. * Set the fill color of the cursor indicating the playhead
  4164. * position.
  4165. *
  4166. * @param {string} color A CSS color string.
  4167. * @example wavesurfer.setCursorColor('#222');
  4168. */
  4169. }, {
  4170. key: "setCursorColor",
  4171. value: function setCursorColor(color) {
  4172. this.params.cursorColor = color;
  4173. this.drawer.updateCursor();
  4174. }
  4175. /**
  4176. * Get the height of the waveform.
  4177. *
  4178. * @return {number} Height measured in pixels.
  4179. */
  4180. }, {
  4181. key: "getHeight",
  4182. value: function getHeight() {
  4183. return this.params.height;
  4184. }
  4185. /**
  4186. * Set the height of the waveform.
  4187. *
  4188. * @param {number} height Height measured in pixels.
  4189. * @example wavesurfer.setHeight(200);
  4190. */
  4191. }, {
  4192. key: "setHeight",
  4193. value: function setHeight(height) {
  4194. this.params.height = height;
  4195. this.drawer.setHeight(height * this.params.pixelRatio);
  4196. this.drawBuffer();
  4197. }
  4198. /**
  4199. * Hide channels from being drawn on the waveform if splitting channels.
  4200. *
  4201. * For example, if we want to draw only the peaks for the right stereo channel:
  4202. *
  4203. * const wavesurfer = new WaveSurfer.create({...splitChannels: true});
  4204. * wavesurfer.load('stereo_audio.mp3');
  4205. *
  4206. * wavesurfer.setFilteredChannel([0]); <-- hide left channel peaks.
  4207. *
  4208. * @param {array} channelIndices Channels to be filtered out from drawing.
  4209. * @version 4.0.0
  4210. */
  4211. }, {
  4212. key: "setFilteredChannels",
  4213. value: function setFilteredChannels(channelIndices) {
  4214. this.params.splitChannelsOptions.filterChannels = channelIndices;
  4215. this.drawBuffer();
  4216. }
  4217. /**
  4218. * Get the correct peaks for current wave view-port and render wave
  4219. *
  4220. * @private
  4221. * @emits WaveSurfer#redraw
  4222. */
  4223. }, {
  4224. key: "drawBuffer",
  4225. value: function drawBuffer() {
  4226. var nominalWidth = Math.round(this.getDuration() * this.params.minPxPerSec * this.params.pixelRatio);
  4227. var parentWidth = this.drawer.getWidth();
  4228. var width = nominalWidth; // always start at 0 after zooming for scrolling : issue redraw left part
  4229. var start = 0;
  4230. var end = Math.max(start + parentWidth, width); // Fill container
  4231. if (this.params.fillParent && (!this.params.scrollParent || nominalWidth < parentWidth)) {
  4232. width = parentWidth;
  4233. start = 0;
  4234. end = width;
  4235. }
  4236. var peaks;
  4237. if (this.params.partialRender) {
  4238. var newRanges = this.peakCache.addRangeToPeakCache(width, start, end);
  4239. var i;
  4240. for (i = 0; i < newRanges.length; i++) {
  4241. peaks = this.backend.getPeaks(width, newRanges[i][0], newRanges[i][1]);
  4242. this.drawer.drawPeaks(peaks, width, newRanges[i][0], newRanges[i][1]);
  4243. }
  4244. } else {
  4245. peaks = this.backend.getPeaks(width, start, end);
  4246. this.drawer.drawPeaks(peaks, width, start, end);
  4247. }
  4248. this.fireEvent('redraw', peaks, width);
  4249. }
  4250. /**
  4251. * Horizontally zooms the waveform in and out. It also changes the parameter
  4252. * `minPxPerSec` and enables the `scrollParent` option. Calling the function
  4253. * with a falsey parameter will reset the zoom state.
  4254. *
  4255. * @param {?number} pxPerSec Number of horizontal pixels per second of
  4256. * audio, if none is set the waveform returns to unzoomed state
  4257. * @emits WaveSurfer#zoom
  4258. * @example wavesurfer.zoom(20);
  4259. */
  4260. }, {
  4261. key: "zoom",
  4262. value: function zoom(pxPerSec) {
  4263. if (!pxPerSec) {
  4264. this.params.minPxPerSec = this.defaultParams.minPxPerSec;
  4265. this.params.scrollParent = false;
  4266. } else {
  4267. this.params.minPxPerSec = pxPerSec;
  4268. this.params.scrollParent = true;
  4269. }
  4270. this.drawBuffer();
  4271. this.drawer.progress(this.backend.getPlayedPercents());
  4272. this.drawer.recenter(this.getCurrentTime() / this.getDuration());
  4273. this.fireEvent('zoom', pxPerSec);
  4274. }
  4275. /**
  4276. * Decode buffer and load
  4277. *
  4278. * @private
  4279. * @param {ArrayBuffer} arraybuffer Buffer to process
  4280. */
  4281. }, {
  4282. key: "loadArrayBuffer",
  4283. value: function loadArrayBuffer(arraybuffer) {
  4284. var _this9 = this;
  4285. this.decodeArrayBuffer(arraybuffer, function (data) {
  4286. if (!_this9.isDestroyed) {
  4287. _this9.loadDecodedBuffer(data);
  4288. }
  4289. });
  4290. }
  4291. /**
  4292. * Directly load an externally decoded AudioBuffer
  4293. *
  4294. * @private
  4295. * @param {AudioBuffer} buffer Buffer to process
  4296. * @emits WaveSurfer#ready
  4297. */
  4298. }, {
  4299. key: "loadDecodedBuffer",
  4300. value: function loadDecodedBuffer(buffer) {
  4301. this.backend.load(buffer);
  4302. this.drawBuffer();
  4303. this.isReady = true;
  4304. this.fireEvent('ready');
  4305. }
  4306. /**
  4307. * Loads audio data from a Blob or File object
  4308. *
  4309. * @param {Blob|File} blob Audio data
  4310. * @example
  4311. */
  4312. }, {
  4313. key: "loadBlob",
  4314. value: function loadBlob(blob) {
  4315. var _this10 = this;
  4316. // Create file reader
  4317. var reader = new FileReader();
  4318. reader.addEventListener('progress', function (e) {
  4319. return _this10.onProgress(e);
  4320. });
  4321. reader.addEventListener('load', function (e) {
  4322. return _this10.loadArrayBuffer(e.target.result);
  4323. });
  4324. reader.addEventListener('error', function () {
  4325. return _this10.fireEvent('error', 'Error reading file');
  4326. });
  4327. reader.readAsArrayBuffer(blob);
  4328. this.empty();
  4329. }
  4330. /**
  4331. * Loads audio and re-renders the waveform.
  4332. *
  4333. * @param {string|HTMLMediaElement} url The url of the audio file or the
  4334. * audio element with the audio
  4335. * @param {number[]|Number.<Array[]>} peaks Wavesurfer does not have to decode
  4336. * the audio to render the waveform if this is specified
  4337. * @param {?string} preload (Use with backend `MediaElement` and `MediaElementWebAudio`)
  4338. * `'none'|'metadata'|'auto'` Preload attribute for the media element
  4339. * @param {?number} duration The duration of the audio. This is used to
  4340. * render the peaks data in the correct size for the audio duration (as
  4341. * befits the current `minPxPerSec` and zoom value) without having to decode
  4342. * the audio.
  4343. * @returns {void}
  4344. * @throws Will throw an error if the `url` argument is empty.
  4345. * @example
  4346. * // uses fetch or media element to load file (depending on backend)
  4347. * wavesurfer.load('http://example.com/demo.wav');
  4348. *
  4349. * // setting preload attribute with media element backend and supplying
  4350. * // peaks
  4351. * wavesurfer.load(
  4352. * 'http://example.com/demo.wav',
  4353. * [0.0218, 0.0183, 0.0165, 0.0198, 0.2137, 0.2888],
  4354. * true
  4355. * );
  4356. */
  4357. }, {
  4358. key: "load",
  4359. value: function load(url, peaks, preload, duration) {
  4360. if (!url) {
  4361. throw new Error('url parameter cannot be empty');
  4362. }
  4363. this.empty();
  4364. if (preload) {
  4365. // check whether the preload attribute will be usable and if not log
  4366. // a warning listing the reasons why not and nullify the variable
  4367. var preloadIgnoreReasons = {
  4368. "Preload is not 'auto', 'none' or 'metadata'": ['auto', 'metadata', 'none'].indexOf(preload) === -1,
  4369. 'Peaks are not provided': !peaks,
  4370. "Backend is not of type 'MediaElement' or 'MediaElementWebAudio'": ['MediaElement', 'MediaElementWebAudio'].indexOf(this.params.backend) === -1,
  4371. 'Url is not of type string': typeof url !== 'string'
  4372. };
  4373. var activeReasons = Object.keys(preloadIgnoreReasons).filter(function (reason) {
  4374. return preloadIgnoreReasons[reason];
  4375. });
  4376. if (activeReasons.length) {
  4377. // eslint-disable-next-line no-console
  4378. console.warn('Preload parameter of wavesurfer.load will be ignored because:\n\t- ' + activeReasons.join('\n\t- ')); // stop invalid values from being used
  4379. preload = null;
  4380. }
  4381. } // loadBuffer(url, peaks, duration) requires that url is a string
  4382. // but users can pass in a HTMLMediaElement to WaveSurfer
  4383. if (this.params.backend === 'WebAudio' && url instanceof HTMLMediaElement) {
  4384. url = url.src;
  4385. }
  4386. switch (this.params.backend) {
  4387. case 'WebAudio':
  4388. return this.loadBuffer(url, peaks, duration);
  4389. case 'MediaElement':
  4390. case 'MediaElementWebAudio':
  4391. return this.loadMediaElement(url, peaks, preload, duration);
  4392. }
  4393. }
  4394. /**
  4395. * Loads audio using Web Audio buffer backend.
  4396. *
  4397. * @private
  4398. * @emits WaveSurfer#waveform-ready
  4399. * @param {string} url URL of audio file
  4400. * @param {number[]|Number.<Array[]>} peaks Peaks data
  4401. * @param {?number} duration Optional duration of audio file
  4402. * @returns {void}
  4403. */
  4404. }, {
  4405. key: "loadBuffer",
  4406. value: function loadBuffer(url, peaks, duration) {
  4407. var _this11 = this;
  4408. var load = function load(action) {
  4409. if (action) {
  4410. _this11.tmpEvents.push(_this11.once('ready', action));
  4411. }
  4412. return _this11.getArrayBuffer(url, function (data) {
  4413. return _this11.loadArrayBuffer(data);
  4414. });
  4415. };
  4416. if (peaks) {
  4417. this.backend.setPeaks(peaks, duration);
  4418. this.drawBuffer();
  4419. this.fireEvent('waveform-ready');
  4420. this.tmpEvents.push(this.once('interaction', load));
  4421. } else {
  4422. return load();
  4423. }
  4424. }
  4425. /**
  4426. * Either create a media element, or load an existing media element.
  4427. *
  4428. * @private
  4429. * @emits WaveSurfer#waveform-ready
  4430. * @param {string|HTMLMediaElement} urlOrElt Either a path to a media file, or an
  4431. * existing HTML5 Audio/Video Element
  4432. * @param {number[]|Number.<Array[]>} peaks Array of peaks. Required to bypass web audio
  4433. * dependency
  4434. * @param {?boolean} preload Set to true if the preload attribute of the
  4435. * audio element should be enabled
  4436. * @param {?number} duration Optional duration of audio file
  4437. */
  4438. }, {
  4439. key: "loadMediaElement",
  4440. value: function loadMediaElement(urlOrElt, peaks, preload, duration) {
  4441. var _this12 = this;
  4442. var url = urlOrElt;
  4443. if (typeof urlOrElt === 'string') {
  4444. this.backend.load(url, this.mediaContainer, peaks, preload);
  4445. } else {
  4446. var elt = urlOrElt;
  4447. this.backend.loadElt(elt, peaks); // If peaks are not provided,
  4448. // url = element.src so we can get peaks with web audio
  4449. url = elt.src;
  4450. }
  4451. this.tmpEvents.push(this.backend.once('canplay', function () {
  4452. // ignore when backend was already destroyed
  4453. if (!_this12.backend.destroyed) {
  4454. _this12.drawBuffer();
  4455. _this12.isReady = true;
  4456. _this12.fireEvent('ready');
  4457. }
  4458. }), this.backend.once('error', function (err) {
  4459. return _this12.fireEvent('error', err);
  4460. })); // If peaks are provided, render them and fire the `waveform-ready` event.
  4461. if (peaks) {
  4462. this.backend.setPeaks(peaks, duration);
  4463. this.drawBuffer();
  4464. this.fireEvent('waveform-ready');
  4465. } // If no pre-decoded peaks are provided, or are provided with
  4466. // forceDecode flag, attempt to download the audio file and decode it
  4467. // with Web Audio.
  4468. if ((!peaks || this.params.forceDecode) && this.backend.supportsWebAudio()) {
  4469. this.getArrayBuffer(url, function (arraybuffer) {
  4470. _this12.decodeArrayBuffer(arraybuffer, function (buffer) {
  4471. _this12.backend.buffer = buffer;
  4472. _this12.backend.setPeaks(null);
  4473. _this12.drawBuffer();
  4474. _this12.fireEvent('waveform-ready');
  4475. });
  4476. });
  4477. }
  4478. }
  4479. /**
  4480. * Decode an array buffer and pass data to a callback
  4481. *
  4482. * @private
  4483. * @param {Object} arraybuffer The array buffer to decode
  4484. * @param {function} callback The function to call on complete
  4485. */
  4486. }, {
  4487. key: "decodeArrayBuffer",
  4488. value: function decodeArrayBuffer(arraybuffer, callback) {
  4489. var _this13 = this;
  4490. if (!this.isDestroyed) {
  4491. this.arraybuffer = arraybuffer;
  4492. this.backend.decodeArrayBuffer(arraybuffer, function (data) {
  4493. // Only use the decoded data if we haven't been destroyed or
  4494. // another decode started in the meantime
  4495. if (!_this13.isDestroyed && _this13.arraybuffer == arraybuffer) {
  4496. callback(data);
  4497. _this13.arraybuffer = null;
  4498. }
  4499. }, function () {
  4500. return _this13.fireEvent('error', 'Error decoding audiobuffer');
  4501. });
  4502. }
  4503. }
  4504. /**
  4505. * Load an array buffer using fetch and pass the result to a callback
  4506. *
  4507. * @param {string} url The URL of the file object
  4508. * @param {function} callback The function to call on complete
  4509. * @returns {util.fetchFile} fetch call
  4510. * @private
  4511. */
  4512. }, {
  4513. key: "getArrayBuffer",
  4514. value: function getArrayBuffer(url, callback) {
  4515. var _this14 = this;
  4516. var options = Object.assign({
  4517. url: url,
  4518. responseType: 'arraybuffer'
  4519. }, this.params.xhr);
  4520. var request = util.fetchFile(options);
  4521. this.currentRequest = request;
  4522. this.tmpEvents.push(request.on('progress', function (e) {
  4523. _this14.onProgress(e);
  4524. }), request.on('success', function (data) {
  4525. callback(data);
  4526. _this14.currentRequest = null;
  4527. }), request.on('error', function (e) {
  4528. _this14.fireEvent('error', e);
  4529. _this14.currentRequest = null;
  4530. }));
  4531. return request;
  4532. }
  4533. /**
  4534. * Called while the audio file is loading
  4535. *
  4536. * @private
  4537. * @param {Event} e Progress event
  4538. * @emits WaveSurfer#loading
  4539. */
  4540. }, {
  4541. key: "onProgress",
  4542. value: function onProgress(e) {
  4543. var percentComplete;
  4544. if (e.lengthComputable) {
  4545. percentComplete = e.loaded / e.total;
  4546. } else {
  4547. // Approximate progress with an asymptotic
  4548. // function, and assume downloads in the 1-3 MB range.
  4549. percentComplete = e.loaded / (e.loaded + 1000000);
  4550. }
  4551. this.fireEvent('loading', Math.round(percentComplete * 100), e.target);
  4552. }
  4553. /**
  4554. * Exports PCM data into a JSON array and optionally opens in a new window
  4555. * as valid JSON Blob instance.
  4556. *
  4557. * @param {number} length=1024 The scale in which to export the peaks
  4558. * @param {number} accuracy=10000
  4559. * @param {?boolean} noWindow Set to true to disable opening a new
  4560. * window with the JSON
  4561. * @param {number} start Start index
  4562. * @param {number} end End index
  4563. * @return {Promise} Promise that resolves with array of peaks
  4564. */
  4565. }, {
  4566. key: "exportPCM",
  4567. value: function exportPCM(length, accuracy, noWindow, start, end) {
  4568. length = length || 1024;
  4569. start = start || 0;
  4570. accuracy = accuracy || 10000;
  4571. noWindow = noWindow || false;
  4572. var peaks = this.backend.getPeaks(length, start, end);
  4573. var arr = [].map.call(peaks, function (val) {
  4574. return Math.round(val * accuracy) / accuracy;
  4575. });
  4576. return new Promise(function (resolve, reject) {
  4577. if (!noWindow) {
  4578. var blobJSON = new Blob([JSON.stringify(arr)], {
  4579. type: 'application/json;charset=utf-8'
  4580. });
  4581. var objURL = URL.createObjectURL(blobJSON);
  4582. window.open(objURL);
  4583. URL.revokeObjectURL(objURL);
  4584. }
  4585. resolve(arr);
  4586. });
  4587. }
  4588. /**
  4589. * Save waveform image as data URI.
  4590. *
  4591. * The default format is `'image/png'`. Other supported types are
  4592. * `'image/jpeg'` and `'image/webp'`.
  4593. *
  4594. * @param {string} format='image/png' A string indicating the image format.
  4595. * The default format type is `'image/png'`.
  4596. * @param {number} quality=1 A number between 0 and 1 indicating the image
  4597. * quality to use for image formats that use lossy compression such as
  4598. * `'image/jpeg'`` and `'image/webp'`.
  4599. * @param {string} type Image data type to return. Either 'dataURL' (default)
  4600. * or 'blob'.
  4601. * @return {string|string[]|Promise} When using `'dataURL'` type this returns
  4602. * a single data URL or an array of data URLs, one for each canvas. When using
  4603. * `'blob'` type this returns a `Promise` resolving with an array of `Blob`
  4604. * instances, one for each canvas.
  4605. */
  4606. }, {
  4607. key: "exportImage",
  4608. value: function exportImage(format, quality, type) {
  4609. if (!format) {
  4610. format = 'image/png';
  4611. }
  4612. if (!quality) {
  4613. quality = 1;
  4614. }
  4615. if (!type) {
  4616. type = 'dataURL';
  4617. }
  4618. return this.drawer.getImage(format, quality, type);
  4619. }
  4620. /**
  4621. * Cancel any fetch request currently in progress
  4622. */
  4623. }, {
  4624. key: "cancelAjax",
  4625. value: function cancelAjax() {
  4626. if (this.currentRequest && this.currentRequest.controller) {
  4627. // If the current request has a ProgressHandler, then its ReadableStream might need to be cancelled too
  4628. // See: Wavesurfer issue #2042
  4629. // See Firefox bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1583815
  4630. if (this.currentRequest._reader) {
  4631. // Ignoring exceptions thrown by call to cancel()
  4632. this.currentRequest._reader.cancel().catch(function (err) {});
  4633. }
  4634. this.currentRequest.controller.abort();
  4635. this.currentRequest = null;
  4636. }
  4637. }
  4638. /**
  4639. * @private
  4640. */
  4641. }, {
  4642. key: "clearTmpEvents",
  4643. value: function clearTmpEvents() {
  4644. this.tmpEvents.forEach(function (e) {
  4645. return e.un();
  4646. });
  4647. }
  4648. /**
  4649. * Display empty waveform.
  4650. */
  4651. }, {
  4652. key: "empty",
  4653. value: function empty() {
  4654. if (!this.backend.isPaused()) {
  4655. this.stop();
  4656. this.backend.disconnectSource();
  4657. }
  4658. this.isReady = false;
  4659. this.cancelAjax();
  4660. this.clearTmpEvents(); // empty drawer
  4661. this.drawer.progress(0);
  4662. this.drawer.setWidth(0);
  4663. this.drawer.drawPeaks({
  4664. length: this.drawer.getWidth()
  4665. }, 0);
  4666. }
  4667. /**
  4668. * Remove events, elements and disconnect WebAudio nodes.
  4669. *
  4670. * @emits WaveSurfer#destroy
  4671. */
  4672. }, {
  4673. key: "destroy",
  4674. value: function destroy() {
  4675. this.destroyAllPlugins();
  4676. this.fireEvent('destroy');
  4677. this.cancelAjax();
  4678. this.clearTmpEvents();
  4679. this.unAll();
  4680. if (this.params.responsive !== false) {
  4681. window.removeEventListener('resize', this._onResize, true);
  4682. window.removeEventListener('orientationchange', this._onResize, true);
  4683. }
  4684. if (this.backend) {
  4685. this.backend.destroy(); // clears memory usage
  4686. this.backend = null;
  4687. }
  4688. if (this.drawer) {
  4689. this.drawer.destroy();
  4690. }
  4691. this.isDestroyed = true;
  4692. this.isReady = false;
  4693. this.arraybuffer = null;
  4694. }
  4695. }], [{
  4696. key: "create",
  4697. value:
  4698. /** @private */
  4699. /** @private */
  4700. /**
  4701. * Instantiate this class, call its `init` function and returns it
  4702. *
  4703. * @param {WavesurferParams} params The wavesurfer parameters
  4704. * @return {Object} WaveSurfer instance
  4705. * @example const wavesurfer = WaveSurfer.create(params);
  4706. */
  4707. function create(params) {
  4708. var wavesurfer = new WaveSurfer(params);
  4709. return wavesurfer.init();
  4710. }
  4711. /**
  4712. * The library version number is available as a static property of the
  4713. * WaveSurfer class
  4714. *
  4715. * @type {String}
  4716. * @example
  4717. * console.log('Using wavesurfer.js ' + WaveSurfer.VERSION);
  4718. */
  4719. }]);
  4720. return WaveSurfer;
  4721. }(util.Observer);
  4722. exports["default"] = WaveSurfer;
  4723. _defineProperty(WaveSurfer, "VERSION", "6.1.0");
  4724. _defineProperty(WaveSurfer, "util", util);
  4725. module.exports = exports.default;
  4726. /***/ }),
  4727. /***/ "./src/webaudio.js":
  4728. /*!*************************!*\
  4729. !*** ./src/webaudio.js ***!
  4730. \*************************/
  4731. /***/ ((module, exports, __webpack_require__) => {
  4732. "use strict";
  4733. function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
  4734. Object.defineProperty(exports, "__esModule", ({
  4735. value: true
  4736. }));
  4737. exports["default"] = void 0;
  4738. var util = _interopRequireWildcard(__webpack_require__(/*! ./util */ "./src/util/index.js"));
  4739. function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
  4740. function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
  4741. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4742. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  4743. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  4744. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
  4745. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  4746. function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
  4747. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
  4748. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  4749. function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
  4750. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  4751. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  4752. // using constants to prevent someone writing the string wrong
  4753. var PLAYING = 'playing';
  4754. var PAUSED = 'paused';
  4755. var FINISHED = 'finished';
  4756. /**
  4757. * WebAudio backend
  4758. *
  4759. * @extends {Observer}
  4760. */
  4761. var WebAudio = /*#__PURE__*/function (_util$Observer) {
  4762. _inherits(WebAudio, _util$Observer);
  4763. var _super = _createSuper(WebAudio);
  4764. /**
  4765. * Construct the backend
  4766. *
  4767. * @param {WavesurferParams} params Wavesurfer parameters
  4768. */
  4769. function WebAudio(params) {
  4770. var _defineProperty2, _this$states;
  4771. var _this;
  4772. _classCallCheck(this, WebAudio);
  4773. _this = _super.call(this);
  4774. /** @private */
  4775. _defineProperty(_assertThisInitialized(_this), "audioContext", null);
  4776. _defineProperty(_assertThisInitialized(_this), "offlineAudioContext", null);
  4777. _defineProperty(_assertThisInitialized(_this), "stateBehaviors", (_defineProperty2 = {}, _defineProperty(_defineProperty2, PLAYING, {
  4778. init: function init() {
  4779. this.addOnAudioProcess();
  4780. },
  4781. getPlayedPercents: function getPlayedPercents() {
  4782. var duration = this.getDuration();
  4783. return this.getCurrentTime() / duration || 0;
  4784. },
  4785. getCurrentTime: function getCurrentTime() {
  4786. return this.startPosition + this.getPlayedTime();
  4787. }
  4788. }), _defineProperty(_defineProperty2, PAUSED, {
  4789. init: function init() {
  4790. this.removeOnAudioProcess();
  4791. },
  4792. getPlayedPercents: function getPlayedPercents() {
  4793. var duration = this.getDuration();
  4794. return this.getCurrentTime() / duration || 0;
  4795. },
  4796. getCurrentTime: function getCurrentTime() {
  4797. return this.startPosition;
  4798. }
  4799. }), _defineProperty(_defineProperty2, FINISHED, {
  4800. init: function init() {
  4801. this.removeOnAudioProcess();
  4802. this.fireEvent('finish');
  4803. },
  4804. getPlayedPercents: function getPlayedPercents() {
  4805. return 1;
  4806. },
  4807. getCurrentTime: function getCurrentTime() {
  4808. return this.getDuration();
  4809. }
  4810. }), _defineProperty2));
  4811. _this.params = params;
  4812. /** ac: Audio Context instance */
  4813. _this.ac = params.audioContext || (_this.supportsWebAudio() ? _this.getAudioContext() : {});
  4814. /**@private */
  4815. _this.lastPlay = _this.ac.currentTime;
  4816. /** @private */
  4817. _this.startPosition = 0;
  4818. /** @private */
  4819. _this.scheduledPause = null;
  4820. /** @private */
  4821. _this.states = (_this$states = {}, _defineProperty(_this$states, PLAYING, Object.create(_this.stateBehaviors[PLAYING])), _defineProperty(_this$states, PAUSED, Object.create(_this.stateBehaviors[PAUSED])), _defineProperty(_this$states, FINISHED, Object.create(_this.stateBehaviors[FINISHED])), _this$states);
  4822. /** @private */
  4823. _this.buffer = null;
  4824. /** @private */
  4825. _this.filters = [];
  4826. /** gainNode: allows to control audio volume */
  4827. _this.gainNode = null;
  4828. /** @private */
  4829. _this.mergedPeaks = null;
  4830. /** @private */
  4831. _this.offlineAc = null;
  4832. /** @private */
  4833. _this.peaks = null;
  4834. /** @private */
  4835. _this.playbackRate = 1;
  4836. /** analyser: provides audio analysis information */
  4837. _this.analyser = null;
  4838. /** scriptNode: allows processing audio */
  4839. _this.scriptNode = null;
  4840. /** @private */
  4841. _this.source = null;
  4842. /** @private */
  4843. _this.splitPeaks = [];
  4844. /** @private */
  4845. _this.state = null;
  4846. /** @private */
  4847. _this.explicitDuration = params.duration;
  4848. /** @private */
  4849. _this.sinkStreamDestination = null;
  4850. /** @private */
  4851. _this.sinkAudioElement = null;
  4852. /**
  4853. * Boolean indicating if the backend was destroyed.
  4854. */
  4855. _this.destroyed = false;
  4856. return _this;
  4857. }
  4858. /**
  4859. * Initialise the backend, called in `wavesurfer.createBackend()`
  4860. */
  4861. _createClass(WebAudio, [{
  4862. key: "supportsWebAudio",
  4863. value:
  4864. /** scriptBufferSize: size of the processing buffer */
  4865. /** audioContext: allows to process audio with WebAudio API */
  4866. /** @private */
  4867. /** @private */
  4868. /**
  4869. * Does the browser support this backend
  4870. *
  4871. * @return {boolean} Whether or not this browser supports this backend
  4872. */
  4873. function supportsWebAudio() {
  4874. return !!(window.AudioContext || window.webkitAudioContext);
  4875. }
  4876. /**
  4877. * Get the audio context used by this backend or create one
  4878. *
  4879. * @return {AudioContext} Existing audio context, or creates a new one
  4880. */
  4881. }, {
  4882. key: "getAudioContext",
  4883. value: function getAudioContext() {
  4884. if (!window.WaveSurferAudioContext) {
  4885. window.WaveSurferAudioContext = new (window.AudioContext || window.webkitAudioContext)();
  4886. }
  4887. return window.WaveSurferAudioContext;
  4888. }
  4889. /**
  4890. * Get the offline audio context used by this backend or create one
  4891. *
  4892. * @param {number} sampleRate The sample rate to use
  4893. * @return {OfflineAudioContext} Existing offline audio context, or creates
  4894. * a new one
  4895. */
  4896. }, {
  4897. key: "getOfflineAudioContext",
  4898. value: function getOfflineAudioContext(sampleRate) {
  4899. if (!window.WaveSurferOfflineAudioContext) {
  4900. window.WaveSurferOfflineAudioContext = new (window.OfflineAudioContext || window.webkitOfflineAudioContext)(1, 2, sampleRate);
  4901. }
  4902. return window.WaveSurferOfflineAudioContext;
  4903. }
  4904. }, {
  4905. key: "init",
  4906. value: function init() {
  4907. this.createVolumeNode();
  4908. this.createScriptNode();
  4909. this.createAnalyserNode();
  4910. this.setState(PAUSED);
  4911. this.setPlaybackRate(this.params.audioRate);
  4912. this.setLength(0);
  4913. }
  4914. /** @private */
  4915. }, {
  4916. key: "disconnectFilters",
  4917. value: function disconnectFilters() {
  4918. if (this.filters) {
  4919. this.filters.forEach(function (filter) {
  4920. filter && filter.disconnect();
  4921. });
  4922. this.filters = null; // Reconnect direct path
  4923. this.analyser.connect(this.gainNode);
  4924. }
  4925. }
  4926. /**
  4927. * @private
  4928. *
  4929. * @param {string} state The new state
  4930. */
  4931. }, {
  4932. key: "setState",
  4933. value: function setState(state) {
  4934. if (this.state !== this.states[state]) {
  4935. this.state = this.states[state];
  4936. this.state.init.call(this);
  4937. }
  4938. }
  4939. /**
  4940. * Unpacked `setFilters()`
  4941. *
  4942. * @param {...AudioNode} filters One or more filters to set
  4943. */
  4944. }, {
  4945. key: "setFilter",
  4946. value: function setFilter() {
  4947. for (var _len = arguments.length, filters = new Array(_len), _key = 0; _key < _len; _key++) {
  4948. filters[_key] = arguments[_key];
  4949. }
  4950. this.setFilters(filters);
  4951. }
  4952. /**
  4953. * Insert custom Web Audio nodes into the graph
  4954. *
  4955. * @param {AudioNode[]} filters Packed filters array
  4956. * @example
  4957. * const lowpass = wavesurfer.backend.ac.createBiquadFilter();
  4958. * wavesurfer.backend.setFilter(lowpass);
  4959. */
  4960. }, {
  4961. key: "setFilters",
  4962. value: function setFilters(filters) {
  4963. // Remove existing filters
  4964. this.disconnectFilters(); // Insert filters if filter array not empty
  4965. if (filters && filters.length) {
  4966. this.filters = filters; // Disconnect direct path before inserting filters
  4967. this.analyser.disconnect(); // Connect each filter in turn
  4968. filters.reduce(function (prev, curr) {
  4969. prev.connect(curr);
  4970. return curr;
  4971. }, this.analyser).connect(this.gainNode);
  4972. }
  4973. }
  4974. /** Create ScriptProcessorNode to process audio */
  4975. }, {
  4976. key: "createScriptNode",
  4977. value: function createScriptNode() {
  4978. if (this.params.audioScriptProcessor) {
  4979. this.scriptNode = this.params.audioScriptProcessor;
  4980. } else {
  4981. if (this.ac.createScriptProcessor) {
  4982. this.scriptNode = this.ac.createScriptProcessor(WebAudio.scriptBufferSize);
  4983. } else {
  4984. this.scriptNode = this.ac.createJavaScriptNode(WebAudio.scriptBufferSize);
  4985. }
  4986. }
  4987. this.scriptNode.connect(this.ac.destination);
  4988. }
  4989. /** @private */
  4990. }, {
  4991. key: "addOnAudioProcess",
  4992. value: function addOnAudioProcess() {
  4993. var _this2 = this;
  4994. this.scriptNode.onaudioprocess = function () {
  4995. var time = _this2.getCurrentTime();
  4996. if (time >= _this2.getDuration()) {
  4997. _this2.setState(FINISHED);
  4998. _this2.fireEvent('pause');
  4999. } else if (time >= _this2.scheduledPause) {
  5000. _this2.pause();
  5001. } else if (_this2.state === _this2.states[PLAYING]) {
  5002. _this2.fireEvent('audioprocess', time);
  5003. }
  5004. };
  5005. }
  5006. /** @private */
  5007. }, {
  5008. key: "removeOnAudioProcess",
  5009. value: function removeOnAudioProcess() {
  5010. this.scriptNode.onaudioprocess = null;
  5011. }
  5012. /** Create analyser node to perform audio analysis */
  5013. }, {
  5014. key: "createAnalyserNode",
  5015. value: function createAnalyserNode() {
  5016. this.analyser = this.ac.createAnalyser();
  5017. this.analyser.connect(this.gainNode);
  5018. }
  5019. /**
  5020. * Create the gain node needed to control the playback volume.
  5021. *
  5022. */
  5023. }, {
  5024. key: "createVolumeNode",
  5025. value: function createVolumeNode() {
  5026. // Create gain node using the AudioContext
  5027. if (this.ac.createGain) {
  5028. this.gainNode = this.ac.createGain();
  5029. } else {
  5030. this.gainNode = this.ac.createGainNode();
  5031. } // Add the gain node to the graph
  5032. this.gainNode.connect(this.ac.destination);
  5033. }
  5034. /**
  5035. * Set the sink id for the media player
  5036. *
  5037. * @param {string} deviceId String value representing audio device id.
  5038. * @returns {Promise} A Promise that resolves to `undefined` when there
  5039. * are no errors.
  5040. */
  5041. }, {
  5042. key: "setSinkId",
  5043. value: function setSinkId(deviceId) {
  5044. if (deviceId) {
  5045. /**
  5046. * The webaudio API doesn't currently support setting the device
  5047. * output. Here we create an HTMLAudioElement, connect the
  5048. * webaudio stream to that element and setSinkId there.
  5049. */
  5050. if (!this.sinkAudioElement) {
  5051. this.sinkAudioElement = new window.Audio(); // autoplay is necessary since we're not invoking .play()
  5052. this.sinkAudioElement.autoplay = true;
  5053. }
  5054. if (!this.sinkAudioElement.setSinkId) {
  5055. return Promise.reject(new Error('setSinkId is not supported in your browser'));
  5056. }
  5057. if (!this.sinkStreamDestination) {
  5058. this.sinkStreamDestination = this.ac.createMediaStreamDestination();
  5059. }
  5060. this.gainNode.disconnect();
  5061. this.gainNode.connect(this.sinkStreamDestination);
  5062. this.sinkAudioElement.srcObject = this.sinkStreamDestination.stream;
  5063. return this.sinkAudioElement.setSinkId(deviceId);
  5064. } else {
  5065. return Promise.reject(new Error('Invalid deviceId: ' + deviceId));
  5066. }
  5067. }
  5068. /**
  5069. * Set the audio volume
  5070. *
  5071. * @param {number} value A floating point value between 0 and 1.
  5072. */
  5073. }, {
  5074. key: "setVolume",
  5075. value: function setVolume(value) {
  5076. this.gainNode.gain.setValueAtTime(value, this.ac.currentTime);
  5077. }
  5078. /**
  5079. * Get the current volume
  5080. *
  5081. * @return {number} value A floating point value between 0 and 1.
  5082. */
  5083. }, {
  5084. key: "getVolume",
  5085. value: function getVolume() {
  5086. return this.gainNode.gain.value;
  5087. }
  5088. /**
  5089. * Decode an array buffer and pass data to a callback
  5090. *
  5091. * @private
  5092. * @param {ArrayBuffer} arraybuffer The array buffer to decode
  5093. * @param {function} callback The function to call on complete.
  5094. * @param {function} errback The function to call on error.
  5095. */
  5096. }, {
  5097. key: "decodeArrayBuffer",
  5098. value: function decodeArrayBuffer(arraybuffer, callback, errback) {
  5099. if (!this.offlineAc) {
  5100. this.offlineAc = this.getOfflineAudioContext(this.ac && this.ac.sampleRate ? this.ac.sampleRate : 44100);
  5101. }
  5102. if ('webkitAudioContext' in window) {
  5103. // Safari: no support for Promise-based decodeAudioData enabled
  5104. // Enable it in Safari using the Experimental Features > Modern WebAudio API option
  5105. this.offlineAc.decodeAudioData(arraybuffer, function (data) {
  5106. return callback(data);
  5107. }, errback);
  5108. } else {
  5109. this.offlineAc.decodeAudioData(arraybuffer).then(function (data) {
  5110. return callback(data);
  5111. }).catch(function (err) {
  5112. return errback(err);
  5113. });
  5114. }
  5115. }
  5116. /**
  5117. * Set pre-decoded peaks
  5118. *
  5119. * @param {number[]|Number.<Array[]>} peaks Peaks data
  5120. * @param {?number} duration Explicit duration
  5121. */
  5122. }, {
  5123. key: "setPeaks",
  5124. value: function setPeaks(peaks, duration) {
  5125. if (duration != null) {
  5126. this.explicitDuration = duration;
  5127. }
  5128. this.peaks = peaks;
  5129. }
  5130. /**
  5131. * Set the rendered length (different from the length of the audio)
  5132. *
  5133. * @param {number} length The rendered length
  5134. */
  5135. }, {
  5136. key: "setLength",
  5137. value: function setLength(length) {
  5138. // No resize, we can preserve the cached peaks.
  5139. if (this.mergedPeaks && length == 2 * this.mergedPeaks.length - 1 + 2) {
  5140. return;
  5141. }
  5142. this.splitPeaks = [];
  5143. this.mergedPeaks = []; // Set the last element of the sparse array so the peak arrays are
  5144. // appropriately sized for other calculations.
  5145. var channels = this.buffer ? this.buffer.numberOfChannels : 1;
  5146. var c;
  5147. for (c = 0; c < channels; c++) {
  5148. this.splitPeaks[c] = [];
  5149. this.splitPeaks[c][2 * (length - 1)] = 0;
  5150. this.splitPeaks[c][2 * (length - 1) + 1] = 0;
  5151. }
  5152. this.mergedPeaks[2 * (length - 1)] = 0;
  5153. this.mergedPeaks[2 * (length - 1) + 1] = 0;
  5154. }
  5155. /**
  5156. * Compute the max and min value of the waveform when broken into <length> subranges.
  5157. *
  5158. * @param {number} length How many subranges to break the waveform into.
  5159. * @param {number} first First sample in the required range.
  5160. * @param {number} last Last sample in the required range.
  5161. * @return {number[]|Number.<Array[]>} Array of 2*<length> peaks or array of arrays of
  5162. * peaks consisting of (max, min) values for each subrange.
  5163. */
  5164. }, {
  5165. key: "getPeaks",
  5166. value: function getPeaks(length, first, last) {
  5167. if (this.peaks) {
  5168. return this.peaks;
  5169. }
  5170. if (!this.buffer) {
  5171. return [];
  5172. }
  5173. first = first || 0;
  5174. last = last || length - 1;
  5175. this.setLength(length);
  5176. if (!this.buffer) {
  5177. return this.params.splitChannels ? this.splitPeaks : this.mergedPeaks;
  5178. }
  5179. /**
  5180. * The following snippet fixes a buffering data issue on the Safari
  5181. * browser which returned undefined It creates the missing buffer based
  5182. * on 1 channel, 4096 samples and the sampleRate from the current
  5183. * webaudio context 4096 samples seemed to be the best fit for rendering
  5184. * will review this code once a stable version of Safari TP is out
  5185. */
  5186. if (!this.buffer.length) {
  5187. var newBuffer = this.createBuffer(1, 4096, this.sampleRate);
  5188. this.buffer = newBuffer.buffer;
  5189. }
  5190. var sampleSize = this.buffer.length / length;
  5191. var sampleStep = ~~(sampleSize / 10) || 1;
  5192. var channels = this.buffer.numberOfChannels;
  5193. var c;
  5194. for (c = 0; c < channels; c++) {
  5195. var peaks = this.splitPeaks[c];
  5196. var chan = this.buffer.getChannelData(c);
  5197. var i = void 0;
  5198. for (i = first; i <= last; i++) {
  5199. var start = ~~(i * sampleSize);
  5200. var end = ~~(start + sampleSize);
  5201. /**
  5202. * Initialize the max and min to the first sample of this
  5203. * subrange, so that even if the samples are entirely
  5204. * on one side of zero, we still return the true max and
  5205. * min values in the subrange.
  5206. */
  5207. var min = chan[start];
  5208. var max = min;
  5209. var j = void 0;
  5210. for (j = start; j < end; j += sampleStep) {
  5211. var value = chan[j];
  5212. if (value > max) {
  5213. max = value;
  5214. }
  5215. if (value < min) {
  5216. min = value;
  5217. }
  5218. }
  5219. peaks[2 * i] = max;
  5220. peaks[2 * i + 1] = min;
  5221. if (c == 0 || max > this.mergedPeaks[2 * i]) {
  5222. this.mergedPeaks[2 * i] = max;
  5223. }
  5224. if (c == 0 || min < this.mergedPeaks[2 * i + 1]) {
  5225. this.mergedPeaks[2 * i + 1] = min;
  5226. }
  5227. }
  5228. }
  5229. return this.params.splitChannels ? this.splitPeaks : this.mergedPeaks;
  5230. }
  5231. /**
  5232. * Get the position from 0 to 1
  5233. *
  5234. * @return {number} Position
  5235. */
  5236. }, {
  5237. key: "getPlayedPercents",
  5238. value: function getPlayedPercents() {
  5239. return this.state.getPlayedPercents.call(this);
  5240. }
  5241. /** @private */
  5242. }, {
  5243. key: "disconnectSource",
  5244. value: function disconnectSource() {
  5245. if (this.source) {
  5246. this.source.disconnect();
  5247. }
  5248. }
  5249. /**
  5250. * Destroy all references with WebAudio, disconnecting audio nodes and closing Audio Context
  5251. */
  5252. }, {
  5253. key: "destroyWebAudio",
  5254. value: function destroyWebAudio() {
  5255. this.disconnectFilters();
  5256. this.disconnectSource();
  5257. this.gainNode.disconnect();
  5258. this.scriptNode.disconnect();
  5259. this.analyser.disconnect(); // close the audioContext if closeAudioContext option is set to true
  5260. if (this.params.closeAudioContext) {
  5261. // check if browser supports AudioContext.close()
  5262. if (typeof this.ac.close === 'function' && this.ac.state != 'closed') {
  5263. this.ac.close();
  5264. } // clear the reference to the audiocontext
  5265. this.ac = null; // clear the actual audiocontext, either passed as param or the
  5266. // global singleton
  5267. if (!this.params.audioContext) {
  5268. window.WaveSurferAudioContext = null;
  5269. } else {
  5270. this.params.audioContext = null;
  5271. } // clear the offlineAudioContext
  5272. window.WaveSurferOfflineAudioContext = null;
  5273. } // disconnect resources used by setSinkId
  5274. if (this.sinkStreamDestination) {
  5275. this.sinkAudioElement.pause();
  5276. this.sinkAudioElement.srcObject = null;
  5277. this.sinkStreamDestination.disconnect();
  5278. this.sinkStreamDestination = null;
  5279. }
  5280. }
  5281. /**
  5282. * This is called when wavesurfer is destroyed
  5283. */
  5284. }, {
  5285. key: "destroy",
  5286. value: function destroy() {
  5287. if (!this.isPaused()) {
  5288. this.pause();
  5289. }
  5290. this.unAll();
  5291. this.buffer = null;
  5292. this.destroyed = true;
  5293. this.destroyWebAudio();
  5294. }
  5295. /**
  5296. * Loaded a decoded audio buffer
  5297. *
  5298. * @param {Object} buffer Decoded audio buffer to load
  5299. */
  5300. }, {
  5301. key: "load",
  5302. value: function load(buffer) {
  5303. this.startPosition = 0;
  5304. this.lastPlay = this.ac.currentTime;
  5305. this.buffer = buffer;
  5306. this.createSource();
  5307. }
  5308. /** @private */
  5309. }, {
  5310. key: "createSource",
  5311. value: function createSource() {
  5312. this.disconnectSource();
  5313. this.source = this.ac.createBufferSource(); // adjust for old browsers
  5314. this.source.start = this.source.start || this.source.noteGrainOn;
  5315. this.source.stop = this.source.stop || this.source.noteOff;
  5316. this.setPlaybackRate(this.playbackRate);
  5317. this.source.buffer = this.buffer;
  5318. this.source.connect(this.analyser);
  5319. }
  5320. /**
  5321. * @private
  5322. *
  5323. * some browsers require an explicit call to #resume before they will play back audio
  5324. */
  5325. }, {
  5326. key: "resumeAudioContext",
  5327. value: function resumeAudioContext() {
  5328. if (this.ac.state == 'suspended') {
  5329. this.ac.resume && this.ac.resume();
  5330. }
  5331. }
  5332. /**
  5333. * Used by `wavesurfer.isPlaying()` and `wavesurfer.playPause()`
  5334. *
  5335. * @return {boolean} Whether or not this backend is currently paused
  5336. */
  5337. }, {
  5338. key: "isPaused",
  5339. value: function isPaused() {
  5340. return this.state !== this.states[PLAYING];
  5341. }
  5342. /**
  5343. * Used by `wavesurfer.getDuration()`
  5344. *
  5345. * @return {number} Duration of loaded buffer
  5346. */
  5347. }, {
  5348. key: "getDuration",
  5349. value: function getDuration() {
  5350. if (this.explicitDuration) {
  5351. return this.explicitDuration;
  5352. }
  5353. if (!this.buffer) {
  5354. return 0;
  5355. }
  5356. return this.buffer.duration;
  5357. }
  5358. /**
  5359. * Used by `wavesurfer.seekTo()`
  5360. *
  5361. * @param {number} start Position to start at in seconds
  5362. * @param {number} end Position to end at in seconds
  5363. * @return {{start: number, end: number}} Object containing start and end
  5364. * positions
  5365. */
  5366. }, {
  5367. key: "seekTo",
  5368. value: function seekTo(start, end) {
  5369. if (!this.buffer) {
  5370. return;
  5371. }
  5372. this.scheduledPause = null;
  5373. if (start == null) {
  5374. start = this.getCurrentTime();
  5375. if (start >= this.getDuration()) {
  5376. start = 0;
  5377. }
  5378. }
  5379. if (end == null) {
  5380. end = this.getDuration();
  5381. }
  5382. this.startPosition = start;
  5383. this.lastPlay = this.ac.currentTime;
  5384. if (this.state === this.states[FINISHED]) {
  5385. this.setState(PAUSED);
  5386. }
  5387. return {
  5388. start: start,
  5389. end: end
  5390. };
  5391. }
  5392. /**
  5393. * Get the playback position in seconds
  5394. *
  5395. * @return {number} The playback position in seconds
  5396. */
  5397. }, {
  5398. key: "getPlayedTime",
  5399. value: function getPlayedTime() {
  5400. return (this.ac.currentTime - this.lastPlay) * this.playbackRate;
  5401. }
  5402. /**
  5403. * Plays the loaded audio region.
  5404. *
  5405. * @param {number} start Start offset in seconds, relative to the beginning
  5406. * of a clip.
  5407. * @param {number} end When to stop relative to the beginning of a clip.
  5408. */
  5409. }, {
  5410. key: "play",
  5411. value: function play(start, end) {
  5412. if (!this.buffer) {
  5413. return;
  5414. } // need to re-create source on each playback
  5415. this.createSource();
  5416. var adjustedTime = this.seekTo(start, end);
  5417. start = adjustedTime.start;
  5418. end = adjustedTime.end;
  5419. this.scheduledPause = end;
  5420. this.source.start(0, start);
  5421. this.resumeAudioContext();
  5422. this.setState(PLAYING);
  5423. this.fireEvent('play');
  5424. }
  5425. /**
  5426. * Pauses the loaded audio.
  5427. */
  5428. }, {
  5429. key: "pause",
  5430. value: function pause() {
  5431. this.scheduledPause = null;
  5432. this.startPosition += this.getPlayedTime();
  5433. try {
  5434. this.source && this.source.stop(0);
  5435. } catch (err) {// Calling stop can throw the following 2 errors:
  5436. // - RangeError (The value specified for when is negative.)
  5437. // - InvalidStateNode (The node has not been started by calling start().)
  5438. // We can safely ignore both errors, because:
  5439. // - The range is surely correct
  5440. // - The node might not have been started yet, in which case we just want to carry on without causing any trouble.
  5441. }
  5442. this.setState(PAUSED);
  5443. this.fireEvent('pause');
  5444. }
  5445. /**
  5446. * Returns the current time in seconds relative to the audio-clip's
  5447. * duration.
  5448. *
  5449. * @return {number} The current time in seconds
  5450. */
  5451. }, {
  5452. key: "getCurrentTime",
  5453. value: function getCurrentTime() {
  5454. return this.state.getCurrentTime.call(this);
  5455. }
  5456. /**
  5457. * Returns the current playback rate. (0=no playback, 1=normal playback)
  5458. *
  5459. * @return {number} The current playback rate
  5460. */
  5461. }, {
  5462. key: "getPlaybackRate",
  5463. value: function getPlaybackRate() {
  5464. return this.playbackRate;
  5465. }
  5466. /**
  5467. * Set the audio source playback rate.
  5468. *
  5469. * @param {number} value The playback rate to use
  5470. */
  5471. }, {
  5472. key: "setPlaybackRate",
  5473. value: function setPlaybackRate(value) {
  5474. this.playbackRate = value || 1;
  5475. this.source && this.source.playbackRate.setValueAtTime(this.playbackRate, this.ac.currentTime);
  5476. }
  5477. /**
  5478. * Set a point in seconds for playback to stop at.
  5479. *
  5480. * @param {number} end Position to end at
  5481. * @version 3.3.0
  5482. */
  5483. }, {
  5484. key: "setPlayEnd",
  5485. value: function setPlayEnd(end) {
  5486. this.scheduledPause = end;
  5487. }
  5488. }]);
  5489. return WebAudio;
  5490. }(util.Observer);
  5491. exports["default"] = WebAudio;
  5492. _defineProperty(WebAudio, "scriptBufferSize", 256);
  5493. module.exports = exports.default;
  5494. /***/ }),
  5495. /***/ "./node_modules/debounce/index.js":
  5496. /*!****************************************!*\
  5497. !*** ./node_modules/debounce/index.js ***!
  5498. \****************************************/
  5499. /***/ ((module) => {
  5500. /**
  5501. * Returns a function, that, as long as it continues to be invoked, will not
  5502. * be triggered. The function will be called after it stops being called for
  5503. * N milliseconds. If `immediate` is passed, trigger the function on the
  5504. * leading edge, instead of the trailing. The function also has a property 'clear'
  5505. * that is a function which will clear the timer to prevent previously scheduled executions.
  5506. *
  5507. * @source underscore.js
  5508. * @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
  5509. * @param {Function} function to wrap
  5510. * @param {Number} timeout in ms (`100`)
  5511. * @param {Boolean} whether to execute at the beginning (`false`)
  5512. * @api public
  5513. */
  5514. function debounce(func, wait, immediate){
  5515. var timeout, args, context, timestamp, result;
  5516. if (null == wait) wait = 100;
  5517. function later() {
  5518. var last = Date.now() - timestamp;
  5519. if (last < wait && last >= 0) {
  5520. timeout = setTimeout(later, wait - last);
  5521. } else {
  5522. timeout = null;
  5523. if (!immediate) {
  5524. result = func.apply(context, args);
  5525. context = args = null;
  5526. }
  5527. }
  5528. };
  5529. var debounced = function(){
  5530. context = this;
  5531. args = arguments;
  5532. timestamp = Date.now();
  5533. var callNow = immediate && !timeout;
  5534. if (!timeout) timeout = setTimeout(later, wait);
  5535. if (callNow) {
  5536. result = func.apply(context, args);
  5537. context = args = null;
  5538. }
  5539. return result;
  5540. };
  5541. debounced.clear = function() {
  5542. if (timeout) {
  5543. clearTimeout(timeout);
  5544. timeout = null;
  5545. }
  5546. };
  5547. debounced.flush = function() {
  5548. if (timeout) {
  5549. result = func.apply(context, args);
  5550. context = args = null;
  5551. clearTimeout(timeout);
  5552. timeout = null;
  5553. }
  5554. };
  5555. return debounced;
  5556. };
  5557. // Adds compatibility for ES modules
  5558. debounce.debounce = debounce;
  5559. module.exports = debounce;
  5560. /***/ })
  5561. /******/ });
  5562. /************************************************************************/
  5563. /******/ // The module cache
  5564. /******/ var __webpack_module_cache__ = {};
  5565. /******/
  5566. /******/ // The require function
  5567. /******/ function __webpack_require__(moduleId) {
  5568. /******/ // Check if module is in cache
  5569. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  5570. /******/ if (cachedModule !== undefined) {
  5571. /******/ return cachedModule.exports;
  5572. /******/ }
  5573. /******/ // Create a new module (and put it into the cache)
  5574. /******/ var module = __webpack_module_cache__[moduleId] = {
  5575. /******/ // no module.id needed
  5576. /******/ // no module.loaded needed
  5577. /******/ exports: {}
  5578. /******/ };
  5579. /******/
  5580. /******/ // Execute the module function
  5581. /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
  5582. /******/
  5583. /******/ // Return the exports of the module
  5584. /******/ return module.exports;
  5585. /******/ }
  5586. /******/
  5587. /************************************************************************/
  5588. /******/
  5589. /******/ // startup
  5590. /******/ // Load entry module and return exports
  5591. /******/ // This entry module is referenced by other modules so it can't be inlined
  5592. /******/ var __webpack_exports__ = __webpack_require__("./src/wavesurfer.js");
  5593. /******/
  5594. /******/ return __webpack_exports__;
  5595. /******/ })()
  5596. ;
  5597. });
  5598. //# sourceMappingURL=wavesurfer.js.map