RecordRTC.js 190 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211
  1. 'use strict';
  2. // Last time updated: 2021-03-09 3:20:22 AM UTC
  3. // ________________
  4. // RecordRTC v5.6.2
  5. // Open-Sourced: https://github.com/muaz-khan/RecordRTC
  6. // --------------------------------------------------
  7. // Muaz Khan - www.MuazKhan.com
  8. // MIT License - www.WebRTC-Experiment.com/licence
  9. // --------------------------------------------------
  10. // ____________
  11. // RecordRTC.js
  12. /**
  13. * {@link https://github.com/muaz-khan/RecordRTC|RecordRTC} is a WebRTC JavaScript library for audio/video as well as screen activity recording. It supports Chrome, Firefox, Opera, Android, and Microsoft Edge. Platforms: Linux, Mac and Windows.
  14. * @summary Record audio, video or screen inside the browser.
  15. * @license {@link https://github.com/muaz-khan/RecordRTC/blob/master/LICENSE|MIT}
  16. * @author {@link https://MuazKhan.com|Muaz Khan}
  17. * @typedef RecordRTC
  18. * @class
  19. * @example
  20. * var recorder = RecordRTC(mediaStream or [arrayOfMediaStream], {
  21. * type: 'video', // audio or video or gif or canvas
  22. * recorderType: MediaStreamRecorder || CanvasRecorder || StereoAudioRecorder || Etc
  23. * });
  24. * recorder.startRecording();
  25. * @see For further information:
  26. * @see {@link https://github.com/muaz-khan/RecordRTC|RecordRTC Source Code}
  27. * @param {MediaStream} mediaStream - Single media-stream object, array of media-streams, html-canvas-element, etc.
  28. * @param {object} config - {type:"video", recorderType: MediaStreamRecorder, disableLogs: true, numberOfAudioChannels: 1, bufferSize: 0, sampleRate: 0, desiredSampRate: 16000, video: HTMLVideoElement, etc.}
  29. */
  30. function RecordRTC(mediaStream, config) {
  31. if (!mediaStream) {
  32. throw 'First parameter is required.';
  33. }
  34. config = config || {
  35. type: 'video'
  36. };
  37. config = new RecordRTCConfiguration(mediaStream, config);
  38. // a reference to user's recordRTC object
  39. var self = this;
  40. function startRecording(config2) {
  41. if (!config.disableLogs) {
  42. console.log('RecordRTC version: ', self.version);
  43. }
  44. if (!!config2) {
  45. // allow users to set options using startRecording method
  46. // config2 is similar to main "config" object (second parameter over RecordRTC constructor)
  47. config = new RecordRTCConfiguration(mediaStream, config2);
  48. }
  49. if (!config.disableLogs) {
  50. console.log('started recording ' + config.type + ' stream.');
  51. }
  52. if (mediaRecorder) {
  53. mediaRecorder.clearRecordedData();
  54. mediaRecorder.record();
  55. setState('recording');
  56. if (self.recordingDuration) {
  57. handleRecordingDuration();
  58. }
  59. return self;
  60. }
  61. initRecorder(function() {
  62. if (self.recordingDuration) {
  63. handleRecordingDuration();
  64. }
  65. });
  66. return self;
  67. }
  68. function initRecorder(initCallback) {
  69. if (initCallback) {
  70. config.initCallback = function() {
  71. initCallback();
  72. initCallback = config.initCallback = null; // recorder.initRecorder should be call-backed once.
  73. };
  74. }
  75. var Recorder = new GetRecorderType(mediaStream, config);
  76. mediaRecorder = new Recorder(mediaStream, config);
  77. mediaRecorder.record();
  78. setState('recording');
  79. if (!config.disableLogs) {
  80. console.log('Initialized recorderType:', mediaRecorder.constructor.name, 'for output-type:', config.type);
  81. }
  82. }
  83. function stopRecording(callback) {
  84. callback = callback || function() {};
  85. if (!mediaRecorder) {
  86. warningLog();
  87. return;
  88. }
  89. if (self.state === 'paused') {
  90. self.resumeRecording();
  91. setTimeout(function() {
  92. stopRecording(callback);
  93. }, 1);
  94. return;
  95. }
  96. if (self.state !== 'recording' && !config.disableLogs) {
  97. console.warn('Recording state should be: "recording", however current state is: ', self.state);
  98. }
  99. if (!config.disableLogs) {
  100. console.log('Stopped recording ' + config.type + ' stream.');
  101. }
  102. if (config.type !== 'gif') {
  103. mediaRecorder.stop(_callback);
  104. } else {
  105. mediaRecorder.stop();
  106. _callback();
  107. }
  108. setState('stopped');
  109. function _callback(__blob) {
  110. if (!mediaRecorder) {
  111. if (typeof callback.call === 'function') {
  112. callback.call(self, '');
  113. } else {
  114. callback('');
  115. }
  116. return;
  117. }
  118. Object.keys(mediaRecorder).forEach(function(key) {
  119. if (typeof mediaRecorder[key] === 'function') {
  120. return;
  121. }
  122. self[key] = mediaRecorder[key];
  123. });
  124. var blob = mediaRecorder.blob;
  125. if (!blob) {
  126. if (__blob) {
  127. mediaRecorder.blob = blob = __blob;
  128. } else {
  129. throw 'Recording failed.';
  130. }
  131. }
  132. if (blob && !config.disableLogs) {
  133. console.log(blob.type, '->', bytesToSize(blob.size));
  134. }
  135. if (callback) {
  136. var url;
  137. try {
  138. url = URL.createObjectURL(blob);
  139. } catch (e) {}
  140. if (typeof callback.call === 'function') {
  141. callback.call(self, url);
  142. } else {
  143. callback(url);
  144. }
  145. }
  146. if (!config.autoWriteToDisk) {
  147. return;
  148. }
  149. getDataURL(function(dataURL) {
  150. var parameter = {};
  151. parameter[config.type + 'Blob'] = dataURL;
  152. DiskStorage.Store(parameter);
  153. });
  154. }
  155. }
  156. function pauseRecording() {
  157. if (!mediaRecorder) {
  158. warningLog();
  159. return;
  160. }
  161. if (self.state !== 'recording') {
  162. if (!config.disableLogs) {
  163. console.warn('Unable to pause the recording. Recording state: ', self.state);
  164. }
  165. return;
  166. }
  167. setState('paused');
  168. mediaRecorder.pause();
  169. if (!config.disableLogs) {
  170. console.log('Paused recording.');
  171. }
  172. }
  173. function resumeRecording() {
  174. if (!mediaRecorder) {
  175. warningLog();
  176. return;
  177. }
  178. if (self.state !== 'paused') {
  179. if (!config.disableLogs) {
  180. console.warn('Unable to resume the recording. Recording state: ', self.state);
  181. }
  182. return;
  183. }
  184. setState('recording');
  185. // not all libs have this method yet
  186. mediaRecorder.resume();
  187. if (!config.disableLogs) {
  188. console.log('Resumed recording.');
  189. }
  190. }
  191. function readFile(_blob) {
  192. postMessage(new FileReaderSync().readAsDataURL(_blob));
  193. }
  194. function getDataURL(callback, _mediaRecorder) {
  195. if (!callback) {
  196. throw 'Pass a callback function over getDataURL.';
  197. }
  198. var blob = _mediaRecorder ? _mediaRecorder.blob : (mediaRecorder || {}).blob;
  199. if (!blob) {
  200. if (!config.disableLogs) {
  201. console.warn('Blob encoder did not finish its job yet.');
  202. }
  203. setTimeout(function() {
  204. getDataURL(callback, _mediaRecorder);
  205. }, 1000);
  206. return;
  207. }
  208. if (typeof Worker !== 'undefined' && !navigator.mozGetUserMedia) {
  209. var webWorker = processInWebWorker(readFile);
  210. webWorker.onmessage = function(event) {
  211. callback(event.data);
  212. };
  213. webWorker.postMessage(blob);
  214. } else {
  215. var reader = new FileReader();
  216. reader.readAsDataURL(blob);
  217. reader.onload = function(event) {
  218. callback(event.target.result);
  219. };
  220. }
  221. function processInWebWorker(_function) {
  222. try {
  223. var blob = URL.createObjectURL(new Blob([_function.toString(),
  224. 'this.onmessage = function (eee) {' + _function.name + '(eee.data);}'
  225. ], {
  226. type: 'application/javascript'
  227. }));
  228. var worker = new Worker(blob);
  229. URL.revokeObjectURL(blob);
  230. return worker;
  231. } catch (e) {}
  232. }
  233. }
  234. function handleRecordingDuration(counter) {
  235. counter = counter || 0;
  236. if (self.state === 'paused') {
  237. setTimeout(function() {
  238. handleRecordingDuration(counter);
  239. }, 1000);
  240. return;
  241. }
  242. if (self.state === 'stopped') {
  243. return;
  244. }
  245. if (counter >= self.recordingDuration) {
  246. stopRecording(self.onRecordingStopped);
  247. return;
  248. }
  249. counter += 1000; // 1-second
  250. setTimeout(function() {
  251. handleRecordingDuration(counter);
  252. }, 1000);
  253. }
  254. function setState(state) {
  255. if (!self) {
  256. return;
  257. }
  258. self.state = state;
  259. if (typeof self.onStateChanged.call === 'function') {
  260. self.onStateChanged.call(self, state);
  261. } else {
  262. self.onStateChanged(state);
  263. }
  264. }
  265. var WARNING = 'It seems that recorder is destroyed or "startRecording" is not invoked for ' + config.type + ' recorder.';
  266. function warningLog() {
  267. if (config.disableLogs === true) {
  268. return;
  269. }
  270. console.warn(WARNING);
  271. }
  272. var mediaRecorder;
  273. var returnObject = {
  274. /**
  275. * This method starts the recording.
  276. * @method
  277. * @memberof RecordRTC
  278. * @instance
  279. * @example
  280. * var recorder = RecordRTC(mediaStream, {
  281. * type: 'video'
  282. * });
  283. * recorder.startRecording();
  284. */
  285. startRecording: startRecording,
  286. /**
  287. * This method stops the recording. It is strongly recommended to get "blob" or "URI" inside the callback to make sure all recorders finished their job.
  288. * @param {function} callback - Callback to get the recorded blob.
  289. * @method
  290. * @memberof RecordRTC
  291. * @instance
  292. * @example
  293. * recorder.stopRecording(function() {
  294. * // use either "this" or "recorder" object; both are identical
  295. * video.src = this.toURL();
  296. * var blob = this.getBlob();
  297. * });
  298. */
  299. stopRecording: stopRecording,
  300. /**
  301. * This method pauses the recording. You can resume recording using "resumeRecording" method.
  302. * @method
  303. * @memberof RecordRTC
  304. * @instance
  305. * @todo Firefox is unable to pause the recording. Fix it.
  306. * @example
  307. * recorder.pauseRecording(); // pause the recording
  308. * recorder.resumeRecording(); // resume again
  309. */
  310. pauseRecording: pauseRecording,
  311. /**
  312. * This method resumes the recording.
  313. * @method
  314. * @memberof RecordRTC
  315. * @instance
  316. * @example
  317. * recorder.pauseRecording(); // first of all, pause the recording
  318. * recorder.resumeRecording(); // now resume it
  319. */
  320. resumeRecording: resumeRecording,
  321. /**
  322. * This method initializes the recording.
  323. * @method
  324. * @memberof RecordRTC
  325. * @instance
  326. * @todo This method should be deprecated.
  327. * @example
  328. * recorder.initRecorder();
  329. */
  330. initRecorder: initRecorder,
  331. /**
  332. * Ask RecordRTC to auto-stop the recording after 5 minutes.
  333. * @method
  334. * @memberof RecordRTC
  335. * @instance
  336. * @example
  337. * var fiveMinutes = 5 * 1000 * 60;
  338. * recorder.setRecordingDuration(fiveMinutes, function() {
  339. * var blob = this.getBlob();
  340. * video.src = this.toURL();
  341. * });
  342. *
  343. * // or otherwise
  344. * recorder.setRecordingDuration(fiveMinutes).onRecordingStopped(function() {
  345. * var blob = this.getBlob();
  346. * video.src = this.toURL();
  347. * });
  348. */
  349. setRecordingDuration: function(recordingDuration, callback) {
  350. if (typeof recordingDuration === 'undefined') {
  351. throw 'recordingDuration is required.';
  352. }
  353. if (typeof recordingDuration !== 'number') {
  354. throw 'recordingDuration must be a number.';
  355. }
  356. self.recordingDuration = recordingDuration;
  357. self.onRecordingStopped = callback || function() {};
  358. return {
  359. onRecordingStopped: function(callback) {
  360. self.onRecordingStopped = callback;
  361. }
  362. };
  363. },
  364. /**
  365. * This method can be used to clear/reset all the recorded data.
  366. * @method
  367. * @memberof RecordRTC
  368. * @instance
  369. * @todo Figure out the difference between "reset" and "clearRecordedData" methods.
  370. * @example
  371. * recorder.clearRecordedData();
  372. */
  373. clearRecordedData: function() {
  374. if (!mediaRecorder) {
  375. warningLog();
  376. return;
  377. }
  378. mediaRecorder.clearRecordedData();
  379. if (!config.disableLogs) {
  380. console.log('Cleared old recorded data.');
  381. }
  382. },
  383. /**
  384. * Get the recorded blob. Use this method inside the "stopRecording" callback.
  385. * @method
  386. * @memberof RecordRTC
  387. * @instance
  388. * @example
  389. * recorder.stopRecording(function() {
  390. * var blob = this.getBlob();
  391. *
  392. * var file = new File([blob], 'filename.webm', {
  393. * type: 'video/webm'
  394. * });
  395. *
  396. * var formData = new FormData();
  397. * formData.append('file', file); // upload "File" object rather than a "Blob"
  398. * uploadToServer(formData);
  399. * });
  400. * @returns {Blob} Returns recorded data as "Blob" object.
  401. */
  402. getBlob: function() {
  403. if (!mediaRecorder) {
  404. warningLog();
  405. return;
  406. }
  407. return mediaRecorder.blob;
  408. },
  409. /**
  410. * Get data-URI instead of Blob.
  411. * @param {function} callback - Callback to get the Data-URI.
  412. * @method
  413. * @memberof RecordRTC
  414. * @instance
  415. * @example
  416. * recorder.stopRecording(function() {
  417. * recorder.getDataURL(function(dataURI) {
  418. * video.src = dataURI;
  419. * });
  420. * });
  421. */
  422. getDataURL: getDataURL,
  423. /**
  424. * Get virtual/temporary URL. Usage of this URL is limited to current tab.
  425. * @method
  426. * @memberof RecordRTC
  427. * @instance
  428. * @example
  429. * recorder.stopRecording(function() {
  430. * video.src = this.toURL();
  431. * });
  432. * @returns {String} Returns a virtual/temporary URL for the recorded "Blob".
  433. */
  434. toURL: function() {
  435. if (!mediaRecorder) {
  436. warningLog();
  437. return;
  438. }
  439. return URL.createObjectURL(mediaRecorder.blob);
  440. },
  441. /**
  442. * Get internal recording object (i.e. internal module) e.g. MutliStreamRecorder, MediaStreamRecorder, StereoAudioRecorder or WhammyRecorder etc.
  443. * @method
  444. * @memberof RecordRTC
  445. * @instance
  446. * @example
  447. * var internalRecorder = recorder.getInternalRecorder();
  448. * if(internalRecorder instanceof MultiStreamRecorder) {
  449. * internalRecorder.addStreams([newAudioStream]);
  450. * internalRecorder.resetVideoStreams([screenStream]);
  451. * }
  452. * @returns {Object} Returns internal recording object.
  453. */
  454. getInternalRecorder: function() {
  455. return mediaRecorder;
  456. },
  457. /**
  458. * Invoke save-as dialog to save the recorded blob into your disk.
  459. * @param {string} fileName - Set your own file name.
  460. * @method
  461. * @memberof RecordRTC
  462. * @instance
  463. * @example
  464. * recorder.stopRecording(function() {
  465. * this.save('file-name');
  466. *
  467. * // or manually:
  468. * invokeSaveAsDialog(this.getBlob(), 'filename.webm');
  469. * });
  470. */
  471. save: function(fileName) {
  472. if (!mediaRecorder) {
  473. warningLog();
  474. return;
  475. }
  476. invokeSaveAsDialog(mediaRecorder.blob, fileName);
  477. },
  478. /**
  479. * This method gets a blob from indexed-DB storage.
  480. * @param {function} callback - Callback to get the recorded blob.
  481. * @method
  482. * @memberof RecordRTC
  483. * @instance
  484. * @example
  485. * recorder.getFromDisk(function(dataURL) {
  486. * video.src = dataURL;
  487. * });
  488. */
  489. getFromDisk: function(callback) {
  490. if (!mediaRecorder) {
  491. warningLog();
  492. return;
  493. }
  494. RecordRTC.getFromDisk(config.type, callback);
  495. },
  496. /**
  497. * This method appends an array of webp images to the recorded video-blob. It takes an "array" object.
  498. * @type {Array.<Array>}
  499. * @param {Array} arrayOfWebPImages - Array of webp images.
  500. * @method
  501. * @memberof RecordRTC
  502. * @instance
  503. * @todo This method should be deprecated.
  504. * @example
  505. * var arrayOfWebPImages = [];
  506. * arrayOfWebPImages.push({
  507. * duration: index,
  508. * image: 'data:image/webp;base64,...'
  509. * });
  510. * recorder.setAdvertisementArray(arrayOfWebPImages);
  511. */
  512. setAdvertisementArray: function(arrayOfWebPImages) {
  513. config.advertisement = [];
  514. var length = arrayOfWebPImages.length;
  515. for (var i = 0; i < length; i++) {
  516. config.advertisement.push({
  517. duration: i,
  518. image: arrayOfWebPImages[i]
  519. });
  520. }
  521. },
  522. /**
  523. * It is equivalent to <code class="str">"recorder.getBlob()"</code> method. Usage of "getBlob" is recommended, though.
  524. * @property {Blob} blob - Recorded Blob can be accessed using this property.
  525. * @memberof RecordRTC
  526. * @instance
  527. * @readonly
  528. * @example
  529. * recorder.stopRecording(function() {
  530. * var blob = this.blob;
  531. *
  532. * // below one is recommended
  533. * var blob = this.getBlob();
  534. * });
  535. */
  536. blob: null,
  537. /**
  538. * This works only with {recorderType:StereoAudioRecorder}. Use this property on "stopRecording" to verify the encoder's sample-rates.
  539. * @property {number} bufferSize - Buffer-size used to encode the WAV container
  540. * @memberof RecordRTC
  541. * @instance
  542. * @readonly
  543. * @example
  544. * recorder.stopRecording(function() {
  545. * alert('Recorder used this buffer-size: ' + this.bufferSize);
  546. * });
  547. */
  548. bufferSize: 0,
  549. /**
  550. * This works only with {recorderType:StereoAudioRecorder}. Use this property on "stopRecording" to verify the encoder's sample-rates.
  551. * @property {number} sampleRate - Sample-rates used to encode the WAV container
  552. * @memberof RecordRTC
  553. * @instance
  554. * @readonly
  555. * @example
  556. * recorder.stopRecording(function() {
  557. * alert('Recorder used these sample-rates: ' + this.sampleRate);
  558. * });
  559. */
  560. sampleRate: 0,
  561. /**
  562. * {recorderType:StereoAudioRecorder} returns ArrayBuffer object.
  563. * @property {ArrayBuffer} buffer - Audio ArrayBuffer, supported only in Chrome.
  564. * @memberof RecordRTC
  565. * @instance
  566. * @readonly
  567. * @example
  568. * recorder.stopRecording(function() {
  569. * var arrayBuffer = this.buffer;
  570. * alert(arrayBuffer.byteLength);
  571. * });
  572. */
  573. buffer: null,
  574. /**
  575. * This method resets the recorder. So that you can reuse single recorder instance many times.
  576. * @method
  577. * @memberof RecordRTC
  578. * @instance
  579. * @example
  580. * recorder.reset();
  581. * recorder.startRecording();
  582. */
  583. reset: function() {
  584. if (self.state === 'recording' && !config.disableLogs) {
  585. console.warn('Stop an active recorder.');
  586. }
  587. if (mediaRecorder && typeof mediaRecorder.clearRecordedData === 'function') {
  588. mediaRecorder.clearRecordedData();
  589. }
  590. mediaRecorder = null;
  591. setState('inactive');
  592. self.blob = null;
  593. },
  594. /**
  595. * This method is called whenever recorder's state changes. Use this as an "event".
  596. * @property {String} state - A recorder's state can be: recording, paused, stopped or inactive.
  597. * @method
  598. * @memberof RecordRTC
  599. * @instance
  600. * @example
  601. * recorder.onStateChanged = function(state) {
  602. * console.log('Recorder state: ', state);
  603. * };
  604. */
  605. onStateChanged: function(state) {
  606. if (!config.disableLogs) {
  607. console.log('Recorder state changed:', state);
  608. }
  609. },
  610. /**
  611. * A recorder can have inactive, recording, paused or stopped states.
  612. * @property {String} state - A recorder's state can be: recording, paused, stopped or inactive.
  613. * @memberof RecordRTC
  614. * @static
  615. * @readonly
  616. * @example
  617. * // this looper function will keep you updated about the recorder's states.
  618. * (function looper() {
  619. * document.querySelector('h1').innerHTML = 'Recorder\'s state is: ' + recorder.state;
  620. * if(recorder.state === 'stopped') return; // ignore+stop
  621. * setTimeout(looper, 1000); // update after every 3-seconds
  622. * })();
  623. * recorder.startRecording();
  624. */
  625. state: 'inactive',
  626. /**
  627. * Get recorder's readonly state.
  628. * @method
  629. * @memberof RecordRTC
  630. * @example
  631. * var state = recorder.getState();
  632. * @returns {String} Returns recording state.
  633. */
  634. getState: function() {
  635. return self.state;
  636. },
  637. /**
  638. * Destroy RecordRTC instance. Clear all recorders and objects.
  639. * @method
  640. * @memberof RecordRTC
  641. * @example
  642. * recorder.destroy();
  643. */
  644. destroy: function() {
  645. var disableLogsCache = config.disableLogs;
  646. config = {
  647. disableLogs: true
  648. };
  649. self.reset();
  650. setState('destroyed');
  651. returnObject = self = null;
  652. if (Storage.AudioContextConstructor) {
  653. Storage.AudioContextConstructor.close();
  654. Storage.AudioContextConstructor = null;
  655. }
  656. config.disableLogs = disableLogsCache;
  657. if (!config.disableLogs) {
  658. console.log('RecordRTC is destroyed.');
  659. }
  660. },
  661. /**
  662. * RecordRTC version number
  663. * @property {String} version - Release version number.
  664. * @memberof RecordRTC
  665. * @static
  666. * @readonly
  667. * @example
  668. * alert(recorder.version);
  669. */
  670. version: '5.6.2'
  671. };
  672. if (!this) {
  673. self = returnObject;
  674. return returnObject;
  675. }
  676. // if someone wants to use RecordRTC with the "new" keyword.
  677. for (var prop in returnObject) {
  678. this[prop] = returnObject[prop];
  679. }
  680. self = this;
  681. return returnObject;
  682. }
  683. RecordRTC.version = '5.6.2';
  684. if (typeof module !== 'undefined' /* && !!module.exports*/ ) {
  685. module.exports = RecordRTC;
  686. }
  687. if (typeof define === 'function' && define.amd) {
  688. define('RecordRTC', [], function() {
  689. return RecordRTC;
  690. });
  691. }
  692. RecordRTC.getFromDisk = function(type, callback) {
  693. if (!callback) {
  694. throw 'callback is mandatory.';
  695. }
  696. console.log('Getting recorded ' + (type === 'all' ? 'blobs' : type + ' blob ') + ' from disk!');
  697. DiskStorage.Fetch(function(dataURL, _type) {
  698. if (type !== 'all' && _type === type + 'Blob' && callback) {
  699. callback(dataURL);
  700. }
  701. if (type === 'all' && callback) {
  702. callback(dataURL, _type.replace('Blob', ''));
  703. }
  704. });
  705. };
  706. /**
  707. * This method can be used to store recorded blobs into IndexedDB storage.
  708. * @param {object} options - {audio: Blob, video: Blob, gif: Blob}
  709. * @method
  710. * @memberof RecordRTC
  711. * @example
  712. * RecordRTC.writeToDisk({
  713. * audio: audioBlob,
  714. * video: videoBlob,
  715. * gif : gifBlob
  716. * });
  717. */
  718. RecordRTC.writeToDisk = function(options) {
  719. console.log('Writing recorded blob(s) to disk!');
  720. options = options || {};
  721. if (options.audio && options.video && options.gif) {
  722. options.audio.getDataURL(function(audioDataURL) {
  723. options.video.getDataURL(function(videoDataURL) {
  724. options.gif.getDataURL(function(gifDataURL) {
  725. DiskStorage.Store({
  726. audioBlob: audioDataURL,
  727. videoBlob: videoDataURL,
  728. gifBlob: gifDataURL
  729. });
  730. });
  731. });
  732. });
  733. } else if (options.audio && options.video) {
  734. options.audio.getDataURL(function(audioDataURL) {
  735. options.video.getDataURL(function(videoDataURL) {
  736. DiskStorage.Store({
  737. audioBlob: audioDataURL,
  738. videoBlob: videoDataURL
  739. });
  740. });
  741. });
  742. } else if (options.audio && options.gif) {
  743. options.audio.getDataURL(function(audioDataURL) {
  744. options.gif.getDataURL(function(gifDataURL) {
  745. DiskStorage.Store({
  746. audioBlob: audioDataURL,
  747. gifBlob: gifDataURL
  748. });
  749. });
  750. });
  751. } else if (options.video && options.gif) {
  752. options.video.getDataURL(function(videoDataURL) {
  753. options.gif.getDataURL(function(gifDataURL) {
  754. DiskStorage.Store({
  755. videoBlob: videoDataURL,
  756. gifBlob: gifDataURL
  757. });
  758. });
  759. });
  760. } else if (options.audio) {
  761. options.audio.getDataURL(function(audioDataURL) {
  762. DiskStorage.Store({
  763. audioBlob: audioDataURL
  764. });
  765. });
  766. } else if (options.video) {
  767. options.video.getDataURL(function(videoDataURL) {
  768. DiskStorage.Store({
  769. videoBlob: videoDataURL
  770. });
  771. });
  772. } else if (options.gif) {
  773. options.gif.getDataURL(function(gifDataURL) {
  774. DiskStorage.Store({
  775. gifBlob: gifDataURL
  776. });
  777. });
  778. }
  779. };
  780. // __________________________
  781. // RecordRTC-Configuration.js
  782. /**
  783. * {@link RecordRTCConfiguration} is an inner/private helper for {@link RecordRTC}.
  784. * @summary It configures the 2nd parameter passed over {@link RecordRTC} and returns a valid "config" object.
  785. * @license {@link https://github.com/muaz-khan/RecordRTC/blob/master/LICENSE|MIT}
  786. * @author {@link https://MuazKhan.com|Muaz Khan}
  787. * @typedef RecordRTCConfiguration
  788. * @class
  789. * @example
  790. * var options = RecordRTCConfiguration(mediaStream, options);
  791. * @see {@link https://github.com/muaz-khan/RecordRTC|RecordRTC Source Code}
  792. * @param {MediaStream} mediaStream - MediaStream object fetched using getUserMedia API or generated using captureStreamUntilEnded or WebAudio API.
  793. * @param {object} config - {type:"video", disableLogs: true, numberOfAudioChannels: 1, bufferSize: 0, sampleRate: 0, video: HTMLVideoElement, getNativeBlob:true, etc.}
  794. */
  795. function RecordRTCConfiguration(mediaStream, config) {
  796. if (!config.recorderType && !config.type) {
  797. if (!!config.audio && !!config.video) {
  798. config.type = 'video';
  799. } else if (!!config.audio && !config.video) {
  800. config.type = 'audio';
  801. }
  802. }
  803. if (config.recorderType && !config.type) {
  804. if (config.recorderType === WhammyRecorder || config.recorderType === CanvasRecorder || (typeof WebAssemblyRecorder !== 'undefined' && config.recorderType === WebAssemblyRecorder)) {
  805. config.type = 'video';
  806. } else if (config.recorderType === GifRecorder) {
  807. config.type = 'gif';
  808. } else if (config.recorderType === StereoAudioRecorder) {
  809. config.type = 'audio';
  810. } else if (config.recorderType === MediaStreamRecorder) {
  811. if (getTracks(mediaStream, 'audio').length && getTracks(mediaStream, 'video').length) {
  812. config.type = 'video';
  813. } else if (!getTracks(mediaStream, 'audio').length && getTracks(mediaStream, 'video').length) {
  814. config.type = 'video';
  815. } else if (getTracks(mediaStream, 'audio').length && !getTracks(mediaStream, 'video').length) {
  816. config.type = 'audio';
  817. } else {
  818. // config.type = 'UnKnown';
  819. }
  820. }
  821. }
  822. if (typeof MediaStreamRecorder !== 'undefined' && typeof MediaRecorder !== 'undefined' && 'requestData' in MediaRecorder.prototype) {
  823. if (!config.mimeType) {
  824. config.mimeType = 'video/webm';
  825. }
  826. if (!config.type) {
  827. config.type = config.mimeType.split('/')[0];
  828. }
  829. if (!config.bitsPerSecond) {
  830. // config.bitsPerSecond = 128000;
  831. }
  832. }
  833. // consider default type=audio
  834. if (!config.type) {
  835. if (config.mimeType) {
  836. config.type = config.mimeType.split('/')[0];
  837. }
  838. if (!config.type) {
  839. config.type = 'audio';
  840. }
  841. }
  842. return config;
  843. }
  844. // __________________
  845. // GetRecorderType.js
  846. /**
  847. * {@link GetRecorderType} is an inner/private helper for {@link RecordRTC}.
  848. * @summary It returns best recorder-type available for your browser.
  849. * @license {@link https://github.com/muaz-khan/RecordRTC/blob/master/LICENSE|MIT}
  850. * @author {@link https://MuazKhan.com|Muaz Khan}
  851. * @typedef GetRecorderType
  852. * @class
  853. * @example
  854. * var RecorderType = GetRecorderType(options);
  855. * var recorder = new RecorderType(options);
  856. * @see {@link https://github.com/muaz-khan/RecordRTC|RecordRTC Source Code}
  857. * @param {MediaStream} mediaStream - MediaStream object fetched using getUserMedia API or generated using captureStreamUntilEnded or WebAudio API.
  858. * @param {object} config - {type:"video", disableLogs: true, numberOfAudioChannels: 1, bufferSize: 0, sampleRate: 0, video: HTMLVideoElement, etc.}
  859. */
  860. function GetRecorderType(mediaStream, config) {
  861. var recorder;
  862. // StereoAudioRecorder can work with all three: Edge, Firefox and Chrome
  863. // todo: detect if it is Edge, then auto use: StereoAudioRecorder
  864. if (isChrome || isEdge || isOpera) {
  865. // Media Stream Recording API has not been implemented in chrome yet;
  866. // That's why using WebAudio API to record stereo audio in WAV format
  867. recorder = StereoAudioRecorder;
  868. }
  869. if (typeof MediaRecorder !== 'undefined' && 'requestData' in MediaRecorder.prototype && !isChrome) {
  870. recorder = MediaStreamRecorder;
  871. }
  872. // video recorder (in WebM format)
  873. if (config.type === 'video' && (isChrome || isOpera)) {
  874. recorder = WhammyRecorder;
  875. if (typeof WebAssemblyRecorder !== 'undefined' && typeof ReadableStream !== 'undefined') {
  876. recorder = WebAssemblyRecorder;
  877. }
  878. }
  879. // video recorder (in Gif format)
  880. if (config.type === 'gif') {
  881. recorder = GifRecorder;
  882. }
  883. // html2canvas recording!
  884. if (config.type === 'canvas') {
  885. recorder = CanvasRecorder;
  886. }
  887. if (isMediaRecorderCompatible() && recorder !== CanvasRecorder && recorder !== GifRecorder && typeof MediaRecorder !== 'undefined' && 'requestData' in MediaRecorder.prototype) {
  888. if (getTracks(mediaStream, 'video').length || getTracks(mediaStream, 'audio').length) {
  889. // audio-only recording
  890. if (config.type === 'audio') {
  891. if (typeof MediaRecorder.isTypeSupported === 'function' && MediaRecorder.isTypeSupported('audio/webm')) {
  892. recorder = MediaStreamRecorder;
  893. }
  894. // else recorder = StereoAudioRecorder;
  895. } else {
  896. // video or screen tracks
  897. if (typeof MediaRecorder.isTypeSupported === 'function' && MediaRecorder.isTypeSupported('video/webm')) {
  898. recorder = MediaStreamRecorder;
  899. }
  900. }
  901. }
  902. }
  903. if (mediaStream instanceof Array && mediaStream.length) {
  904. recorder = MultiStreamRecorder;
  905. }
  906. if (config.recorderType) {
  907. recorder = config.recorderType;
  908. }
  909. if (!config.disableLogs && !!recorder && !!recorder.name) {
  910. console.log('Using recorderType:', recorder.name || recorder.constructor.name);
  911. }
  912. if (!recorder && isSafari) {
  913. recorder = MediaStreamRecorder;
  914. }
  915. return recorder;
  916. }
  917. // _____________
  918. // MRecordRTC.js
  919. /**
  920. * MRecordRTC runs on top of {@link RecordRTC} to bring multiple recordings in a single place, by providing simple API.
  921. * @summary MRecordRTC stands for "Multiple-RecordRTC".
  922. * @license {@link https://github.com/muaz-khan/RecordRTC/blob/master/LICENSE|MIT}
  923. * @author {@link https://MuazKhan.com|Muaz Khan}
  924. * @typedef MRecordRTC
  925. * @class
  926. * @example
  927. * var recorder = new MRecordRTC();
  928. * recorder.addStream(MediaStream);
  929. * recorder.mediaType = {
  930. * audio: true, // or StereoAudioRecorder or MediaStreamRecorder
  931. * video: true, // or WhammyRecorder or MediaStreamRecorder or WebAssemblyRecorder or CanvasRecorder
  932. * gif: true // or GifRecorder
  933. * };
  934. * // mimeType is optional and should be set only in advance cases.
  935. * recorder.mimeType = {
  936. * audio: 'audio/wav',
  937. * video: 'video/webm',
  938. * gif: 'image/gif'
  939. * };
  940. * recorder.startRecording();
  941. * @see For further information:
  942. * @see {@link https://github.com/muaz-khan/RecordRTC/tree/master/MRecordRTC|MRecordRTC Source Code}
  943. * @param {MediaStream} mediaStream - MediaStream object fetched using getUserMedia API or generated using captureStreamUntilEnded or WebAudio API.
  944. * @requires {@link RecordRTC}
  945. */
  946. function MRecordRTC(mediaStream) {
  947. /**
  948. * This method attaches MediaStream object to {@link MRecordRTC}.
  949. * @param {MediaStream} mediaStream - A MediaStream object, either fetched using getUserMedia API, or generated using captureStreamUntilEnded or WebAudio API.
  950. * @method
  951. * @memberof MRecordRTC
  952. * @example
  953. * recorder.addStream(MediaStream);
  954. */
  955. this.addStream = function(_mediaStream) {
  956. if (_mediaStream) {
  957. mediaStream = _mediaStream;
  958. }
  959. };
  960. /**
  961. * This property can be used to set the recording type e.g. audio, or video, or gif, or canvas.
  962. * @property {object} mediaType - {audio: true, video: true, gif: true}
  963. * @memberof MRecordRTC
  964. * @example
  965. * var recorder = new MRecordRTC();
  966. * recorder.mediaType = {
  967. * audio: true, // TRUE or StereoAudioRecorder or MediaStreamRecorder
  968. * video: true, // TRUE or WhammyRecorder or MediaStreamRecorder or WebAssemblyRecorder or CanvasRecorder
  969. * gif : true // TRUE or GifRecorder
  970. * };
  971. */
  972. this.mediaType = {
  973. audio: true,
  974. video: true
  975. };
  976. /**
  977. * This method starts recording.
  978. * @method
  979. * @memberof MRecordRTC
  980. * @example
  981. * recorder.startRecording();
  982. */
  983. this.startRecording = function() {
  984. var mediaType = this.mediaType;
  985. var recorderType;
  986. var mimeType = this.mimeType || {
  987. audio: null,
  988. video: null,
  989. gif: null
  990. };
  991. if (typeof mediaType.audio !== 'function' && isMediaRecorderCompatible() && !getTracks(mediaStream, 'audio').length) {
  992. mediaType.audio = false;
  993. }
  994. if (typeof mediaType.video !== 'function' && isMediaRecorderCompatible() && !getTracks(mediaStream, 'video').length) {
  995. mediaType.video = false;
  996. }
  997. if (typeof mediaType.gif !== 'function' && isMediaRecorderCompatible() && !getTracks(mediaStream, 'video').length) {
  998. mediaType.gif = false;
  999. }
  1000. if (!mediaType.audio && !mediaType.video && !mediaType.gif) {
  1001. throw 'MediaStream must have either audio or video tracks.';
  1002. }
  1003. if (!!mediaType.audio) {
  1004. recorderType = null;
  1005. if (typeof mediaType.audio === 'function') {
  1006. recorderType = mediaType.audio;
  1007. }
  1008. this.audioRecorder = new RecordRTC(mediaStream, {
  1009. type: 'audio',
  1010. bufferSize: this.bufferSize,
  1011. sampleRate: this.sampleRate,
  1012. numberOfAudioChannels: this.numberOfAudioChannels || 2,
  1013. disableLogs: this.disableLogs,
  1014. recorderType: recorderType,
  1015. mimeType: mimeType.audio,
  1016. timeSlice: this.timeSlice,
  1017. onTimeStamp: this.onTimeStamp
  1018. });
  1019. if (!mediaType.video) {
  1020. this.audioRecorder.startRecording();
  1021. }
  1022. }
  1023. if (!!mediaType.video) {
  1024. recorderType = null;
  1025. if (typeof mediaType.video === 'function') {
  1026. recorderType = mediaType.video;
  1027. }
  1028. var newStream = mediaStream;
  1029. if (isMediaRecorderCompatible() && !!mediaType.audio && typeof mediaType.audio === 'function') {
  1030. var videoTrack = getTracks(mediaStream, 'video')[0];
  1031. if (isFirefox) {
  1032. newStream = new MediaStream();
  1033. newStream.addTrack(videoTrack);
  1034. if (recorderType && recorderType === WhammyRecorder) {
  1035. // Firefox does NOT supports webp-encoding yet
  1036. // But Firefox do supports WebAssemblyRecorder
  1037. recorderType = MediaStreamRecorder;
  1038. }
  1039. } else {
  1040. newStream = new MediaStream();
  1041. newStream.addTrack(videoTrack);
  1042. }
  1043. }
  1044. this.videoRecorder = new RecordRTC(newStream, {
  1045. type: 'video',
  1046. video: this.video,
  1047. canvas: this.canvas,
  1048. frameInterval: this.frameInterval || 10,
  1049. disableLogs: this.disableLogs,
  1050. recorderType: recorderType,
  1051. mimeType: mimeType.video,
  1052. timeSlice: this.timeSlice,
  1053. onTimeStamp: this.onTimeStamp,
  1054. workerPath: this.workerPath,
  1055. webAssemblyPath: this.webAssemblyPath,
  1056. frameRate: this.frameRate, // used by WebAssemblyRecorder; values: usually 30; accepts any.
  1057. bitrate: this.bitrate // used by WebAssemblyRecorder; values: 0 to 1000+
  1058. });
  1059. if (!mediaType.audio) {
  1060. this.videoRecorder.startRecording();
  1061. }
  1062. }
  1063. if (!!mediaType.audio && !!mediaType.video) {
  1064. var self = this;
  1065. var isSingleRecorder = isMediaRecorderCompatible() === true;
  1066. if (mediaType.audio instanceof StereoAudioRecorder && !!mediaType.video) {
  1067. isSingleRecorder = false;
  1068. } else if (mediaType.audio !== true && mediaType.video !== true && mediaType.audio !== mediaType.video) {
  1069. isSingleRecorder = false;
  1070. }
  1071. if (isSingleRecorder === true) {
  1072. self.audioRecorder = null;
  1073. self.videoRecorder.startRecording();
  1074. } else {
  1075. self.videoRecorder.initRecorder(function() {
  1076. self.audioRecorder.initRecorder(function() {
  1077. // Both recorders are ready to record things accurately
  1078. self.videoRecorder.startRecording();
  1079. self.audioRecorder.startRecording();
  1080. });
  1081. });
  1082. }
  1083. }
  1084. if (!!mediaType.gif) {
  1085. recorderType = null;
  1086. if (typeof mediaType.gif === 'function') {
  1087. recorderType = mediaType.gif;
  1088. }
  1089. this.gifRecorder = new RecordRTC(mediaStream, {
  1090. type: 'gif',
  1091. frameRate: this.frameRate || 200,
  1092. quality: this.quality || 10,
  1093. disableLogs: this.disableLogs,
  1094. recorderType: recorderType,
  1095. mimeType: mimeType.gif
  1096. });
  1097. this.gifRecorder.startRecording();
  1098. }
  1099. };
  1100. /**
  1101. * This method stops recording.
  1102. * @param {function} callback - Callback function is invoked when all encoders finished their jobs.
  1103. * @method
  1104. * @memberof MRecordRTC
  1105. * @example
  1106. * recorder.stopRecording(function(recording){
  1107. * var audioBlob = recording.audio;
  1108. * var videoBlob = recording.video;
  1109. * var gifBlob = recording.gif;
  1110. * });
  1111. */
  1112. this.stopRecording = function(callback) {
  1113. callback = callback || function() {};
  1114. if (this.audioRecorder) {
  1115. this.audioRecorder.stopRecording(function(blobURL) {
  1116. callback(blobURL, 'audio');
  1117. });
  1118. }
  1119. if (this.videoRecorder) {
  1120. this.videoRecorder.stopRecording(function(blobURL) {
  1121. callback(blobURL, 'video');
  1122. });
  1123. }
  1124. if (this.gifRecorder) {
  1125. this.gifRecorder.stopRecording(function(blobURL) {
  1126. callback(blobURL, 'gif');
  1127. });
  1128. }
  1129. };
  1130. /**
  1131. * This method pauses recording.
  1132. * @method
  1133. * @memberof MRecordRTC
  1134. * @example
  1135. * recorder.pauseRecording();
  1136. */
  1137. this.pauseRecording = function() {
  1138. if (this.audioRecorder) {
  1139. this.audioRecorder.pauseRecording();
  1140. }
  1141. if (this.videoRecorder) {
  1142. this.videoRecorder.pauseRecording();
  1143. }
  1144. if (this.gifRecorder) {
  1145. this.gifRecorder.pauseRecording();
  1146. }
  1147. };
  1148. /**
  1149. * This method resumes recording.
  1150. * @method
  1151. * @memberof MRecordRTC
  1152. * @example
  1153. * recorder.resumeRecording();
  1154. */
  1155. this.resumeRecording = function() {
  1156. if (this.audioRecorder) {
  1157. this.audioRecorder.resumeRecording();
  1158. }
  1159. if (this.videoRecorder) {
  1160. this.videoRecorder.resumeRecording();
  1161. }
  1162. if (this.gifRecorder) {
  1163. this.gifRecorder.resumeRecording();
  1164. }
  1165. };
  1166. /**
  1167. * This method can be used to manually get all recorded blobs.
  1168. * @param {function} callback - All recorded blobs are passed back to the "callback" function.
  1169. * @method
  1170. * @memberof MRecordRTC
  1171. * @example
  1172. * recorder.getBlob(function(recording){
  1173. * var audioBlob = recording.audio;
  1174. * var videoBlob = recording.video;
  1175. * var gifBlob = recording.gif;
  1176. * });
  1177. * // or
  1178. * var audioBlob = recorder.getBlob().audio;
  1179. * var videoBlob = recorder.getBlob().video;
  1180. */
  1181. this.getBlob = function(callback) {
  1182. var output = {};
  1183. if (this.audioRecorder) {
  1184. output.audio = this.audioRecorder.getBlob();
  1185. }
  1186. if (this.videoRecorder) {
  1187. output.video = this.videoRecorder.getBlob();
  1188. }
  1189. if (this.gifRecorder) {
  1190. output.gif = this.gifRecorder.getBlob();
  1191. }
  1192. if (callback) {
  1193. callback(output);
  1194. }
  1195. return output;
  1196. };
  1197. /**
  1198. * Destroy all recorder instances.
  1199. * @method
  1200. * @memberof MRecordRTC
  1201. * @example
  1202. * recorder.destroy();
  1203. */
  1204. this.destroy = function() {
  1205. if (this.audioRecorder) {
  1206. this.audioRecorder.destroy();
  1207. this.audioRecorder = null;
  1208. }
  1209. if (this.videoRecorder) {
  1210. this.videoRecorder.destroy();
  1211. this.videoRecorder = null;
  1212. }
  1213. if (this.gifRecorder) {
  1214. this.gifRecorder.destroy();
  1215. this.gifRecorder = null;
  1216. }
  1217. };
  1218. /**
  1219. * This method can be used to manually get all recorded blobs' DataURLs.
  1220. * @param {function} callback - All recorded blobs' DataURLs are passed back to the "callback" function.
  1221. * @method
  1222. * @memberof MRecordRTC
  1223. * @example
  1224. * recorder.getDataURL(function(recording){
  1225. * var audioDataURL = recording.audio;
  1226. * var videoDataURL = recording.video;
  1227. * var gifDataURL = recording.gif;
  1228. * });
  1229. */
  1230. this.getDataURL = function(callback) {
  1231. this.getBlob(function(blob) {
  1232. if (blob.audio && blob.video) {
  1233. getDataURL(blob.audio, function(_audioDataURL) {
  1234. getDataURL(blob.video, function(_videoDataURL) {
  1235. callback({
  1236. audio: _audioDataURL,
  1237. video: _videoDataURL
  1238. });
  1239. });
  1240. });
  1241. } else if (blob.audio) {
  1242. getDataURL(blob.audio, function(_audioDataURL) {
  1243. callback({
  1244. audio: _audioDataURL
  1245. });
  1246. });
  1247. } else if (blob.video) {
  1248. getDataURL(blob.video, function(_videoDataURL) {
  1249. callback({
  1250. video: _videoDataURL
  1251. });
  1252. });
  1253. }
  1254. });
  1255. function getDataURL(blob, callback00) {
  1256. if (typeof Worker !== 'undefined') {
  1257. var webWorker = processInWebWorker(function readFile(_blob) {
  1258. postMessage(new FileReaderSync().readAsDataURL(_blob));
  1259. });
  1260. webWorker.onmessage = function(event) {
  1261. callback00(event.data);
  1262. };
  1263. webWorker.postMessage(blob);
  1264. } else {
  1265. var reader = new FileReader();
  1266. reader.readAsDataURL(blob);
  1267. reader.onload = function(event) {
  1268. callback00(event.target.result);
  1269. };
  1270. }
  1271. }
  1272. function processInWebWorker(_function) {
  1273. var blob = URL.createObjectURL(new Blob([_function.toString(),
  1274. 'this.onmessage = function (eee) {' + _function.name + '(eee.data);}'
  1275. ], {
  1276. type: 'application/javascript'
  1277. }));
  1278. var worker = new Worker(blob);
  1279. var url;
  1280. if (typeof URL !== 'undefined') {
  1281. url = URL;
  1282. } else if (typeof webkitURL !== 'undefined') {
  1283. url = webkitURL;
  1284. } else {
  1285. throw 'Neither URL nor webkitURL detected.';
  1286. }
  1287. url.revokeObjectURL(blob);
  1288. return worker;
  1289. }
  1290. };
  1291. /**
  1292. * This method can be used to ask {@link MRecordRTC} to write all recorded blobs into IndexedDB storage.
  1293. * @method
  1294. * @memberof MRecordRTC
  1295. * @example
  1296. * recorder.writeToDisk();
  1297. */
  1298. this.writeToDisk = function() {
  1299. RecordRTC.writeToDisk({
  1300. audio: this.audioRecorder,
  1301. video: this.videoRecorder,
  1302. gif: this.gifRecorder
  1303. });
  1304. };
  1305. /**
  1306. * This method can be used to invoke a save-as dialog for all recorded blobs.
  1307. * @param {object} args - {audio: 'audio-name', video: 'video-name', gif: 'gif-name'}
  1308. * @method
  1309. * @memberof MRecordRTC
  1310. * @example
  1311. * recorder.save({
  1312. * audio: 'audio-file-name',
  1313. * video: 'video-file-name',
  1314. * gif : 'gif-file-name'
  1315. * });
  1316. */
  1317. this.save = function(args) {
  1318. args = args || {
  1319. audio: true,
  1320. video: true,
  1321. gif: true
  1322. };
  1323. if (!!args.audio && this.audioRecorder) {
  1324. this.audioRecorder.save(typeof args.audio === 'string' ? args.audio : '');
  1325. }
  1326. if (!!args.video && this.videoRecorder) {
  1327. this.videoRecorder.save(typeof args.video === 'string' ? args.video : '');
  1328. }
  1329. if (!!args.gif && this.gifRecorder) {
  1330. this.gifRecorder.save(typeof args.gif === 'string' ? args.gif : '');
  1331. }
  1332. };
  1333. }
  1334. /**
  1335. * This method can be used to get all recorded blobs from IndexedDB storage.
  1336. * @param {string} type - 'all' or 'audio' or 'video' or 'gif'
  1337. * @param {function} callback - Callback function to get all stored blobs.
  1338. * @method
  1339. * @memberof MRecordRTC
  1340. * @example
  1341. * MRecordRTC.getFromDisk('all', function(dataURL, type){
  1342. * if(type === 'audio') { }
  1343. * if(type === 'video') { }
  1344. * if(type === 'gif') { }
  1345. * });
  1346. */
  1347. MRecordRTC.getFromDisk = RecordRTC.getFromDisk;
  1348. /**
  1349. * This method can be used to store recorded blobs into IndexedDB storage.
  1350. * @param {object} options - {audio: Blob, video: Blob, gif: Blob}
  1351. * @method
  1352. * @memberof MRecordRTC
  1353. * @example
  1354. * MRecordRTC.writeToDisk({
  1355. * audio: audioBlob,
  1356. * video: videoBlob,
  1357. * gif : gifBlob
  1358. * });
  1359. */
  1360. MRecordRTC.writeToDisk = RecordRTC.writeToDisk;
  1361. if (typeof RecordRTC !== 'undefined') {
  1362. RecordRTC.MRecordRTC = MRecordRTC;
  1363. }
  1364. var browserFakeUserAgent = 'Fake/5.0 (FakeOS) AppleWebKit/123 (KHTML, like Gecko) Fake/12.3.4567.89 Fake/123.45';
  1365. (function(that) {
  1366. if (!that) {
  1367. return;
  1368. }
  1369. if (typeof window !== 'undefined') {
  1370. return;
  1371. }
  1372. if (typeof global === 'undefined') {
  1373. return;
  1374. }
  1375. global.navigator = {
  1376. userAgent: browserFakeUserAgent,
  1377. getUserMedia: function() {}
  1378. };
  1379. if (!global.console) {
  1380. global.console = {};
  1381. }
  1382. if (typeof global.console.log === 'undefined' || typeof global.console.error === 'undefined') {
  1383. global.console.error = global.console.log = global.console.log || function() {
  1384. console.log(arguments);
  1385. };
  1386. }
  1387. if (typeof document === 'undefined') {
  1388. /*global document:true */
  1389. that.document = {
  1390. documentElement: {
  1391. appendChild: function() {
  1392. return '';
  1393. }
  1394. }
  1395. };
  1396. document.createElement = document.captureStream = document.mozCaptureStream = function() {
  1397. var obj = {
  1398. getContext: function() {
  1399. return obj;
  1400. },
  1401. play: function() {},
  1402. pause: function() {},
  1403. drawImage: function() {},
  1404. toDataURL: function() {
  1405. return '';
  1406. },
  1407. style: {}
  1408. };
  1409. return obj;
  1410. };
  1411. that.HTMLVideoElement = function() {};
  1412. }
  1413. if (typeof location === 'undefined') {
  1414. /*global location:true */
  1415. that.location = {
  1416. protocol: 'file:',
  1417. href: '',
  1418. hash: ''
  1419. };
  1420. }
  1421. if (typeof screen === 'undefined') {
  1422. /*global screen:true */
  1423. that.screen = {
  1424. width: 0,
  1425. height: 0
  1426. };
  1427. }
  1428. if (typeof URL === 'undefined') {
  1429. /*global screen:true */
  1430. that.URL = {
  1431. createObjectURL: function() {
  1432. return '';
  1433. },
  1434. revokeObjectURL: function() {
  1435. return '';
  1436. }
  1437. };
  1438. }
  1439. /*global window:true */
  1440. that.window = global;
  1441. })(typeof global !== 'undefined' ? global : null);
  1442. // _____________________________
  1443. // Cross-Browser-Declarations.js
  1444. // animation-frame used in WebM recording
  1445. /*jshint -W079 */
  1446. var requestAnimationFrame = window.requestAnimationFrame;
  1447. if (typeof requestAnimationFrame === 'undefined') {
  1448. if (typeof webkitRequestAnimationFrame !== 'undefined') {
  1449. /*global requestAnimationFrame:true */
  1450. requestAnimationFrame = webkitRequestAnimationFrame;
  1451. } else if (typeof mozRequestAnimationFrame !== 'undefined') {
  1452. /*global requestAnimationFrame:true */
  1453. requestAnimationFrame = mozRequestAnimationFrame;
  1454. } else if (typeof msRequestAnimationFrame !== 'undefined') {
  1455. /*global requestAnimationFrame:true */
  1456. requestAnimationFrame = msRequestAnimationFrame;
  1457. } else if (typeof requestAnimationFrame === 'undefined') {
  1458. // via: https://gist.github.com/paulirish/1579671
  1459. var lastTime = 0;
  1460. /*global requestAnimationFrame:true */
  1461. requestAnimationFrame = function(callback, element) {
  1462. var currTime = new Date().getTime();
  1463. var timeToCall = Math.max(0, 16 - (currTime - lastTime));
  1464. var id = setTimeout(function() {
  1465. callback(currTime + timeToCall);
  1466. }, timeToCall);
  1467. lastTime = currTime + timeToCall;
  1468. return id;
  1469. };
  1470. }
  1471. }
  1472. /*jshint -W079 */
  1473. var cancelAnimationFrame = window.cancelAnimationFrame;
  1474. if (typeof cancelAnimationFrame === 'undefined') {
  1475. if (typeof webkitCancelAnimationFrame !== 'undefined') {
  1476. /*global cancelAnimationFrame:true */
  1477. cancelAnimationFrame = webkitCancelAnimationFrame;
  1478. } else if (typeof mozCancelAnimationFrame !== 'undefined') {
  1479. /*global cancelAnimationFrame:true */
  1480. cancelAnimationFrame = mozCancelAnimationFrame;
  1481. } else if (typeof msCancelAnimationFrame !== 'undefined') {
  1482. /*global cancelAnimationFrame:true */
  1483. cancelAnimationFrame = msCancelAnimationFrame;
  1484. } else if (typeof cancelAnimationFrame === 'undefined') {
  1485. /*global cancelAnimationFrame:true */
  1486. cancelAnimationFrame = function(id) {
  1487. clearTimeout(id);
  1488. };
  1489. }
  1490. }
  1491. // WebAudio API representer
  1492. var AudioContext = window.AudioContext;
  1493. if (typeof AudioContext === 'undefined') {
  1494. if (typeof webkitAudioContext !== 'undefined') {
  1495. /*global AudioContext:true */
  1496. AudioContext = webkitAudioContext;
  1497. }
  1498. if (typeof mozAudioContext !== 'undefined') {
  1499. /*global AudioContext:true */
  1500. AudioContext = mozAudioContext;
  1501. }
  1502. }
  1503. /*jshint -W079 */
  1504. var URL = window.URL;
  1505. if (typeof URL === 'undefined' && typeof webkitURL !== 'undefined') {
  1506. /*global URL:true */
  1507. URL = webkitURL;
  1508. }
  1509. if (typeof navigator !== 'undefined' && typeof navigator.getUserMedia === 'undefined') { // maybe window.navigator?
  1510. if (typeof navigator.webkitGetUserMedia !== 'undefined') {
  1511. navigator.getUserMedia = navigator.webkitGetUserMedia;
  1512. }
  1513. if (typeof navigator.mozGetUserMedia !== 'undefined') {
  1514. navigator.getUserMedia = navigator.mozGetUserMedia;
  1515. }
  1516. }
  1517. var isEdge = navigator.userAgent.indexOf('Edge') !== -1 && (!!navigator.msSaveBlob || !!navigator.msSaveOrOpenBlob);
  1518. var isOpera = !!window.opera || navigator.userAgent.indexOf('OPR/') !== -1;
  1519. var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1 && ('netscape' in window) && / rv:/.test(navigator.userAgent);
  1520. var isChrome = (!isOpera && !isEdge && !!navigator.webkitGetUserMedia) || isElectron() || navigator.userAgent.toLowerCase().indexOf('chrome/') !== -1;
  1521. var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  1522. if (isSafari && !isChrome && navigator.userAgent.indexOf('CriOS') !== -1) {
  1523. isSafari = false;
  1524. isChrome = true;
  1525. }
  1526. var MediaStream = window.MediaStream;
  1527. if (typeof MediaStream === 'undefined' && typeof webkitMediaStream !== 'undefined') {
  1528. MediaStream = webkitMediaStream;
  1529. }
  1530. /*global MediaStream:true */
  1531. if (typeof MediaStream !== 'undefined') {
  1532. // override "stop" method for all browsers
  1533. if (typeof MediaStream.prototype.stop === 'undefined') {
  1534. MediaStream.prototype.stop = function() {
  1535. this.getTracks().forEach(function(track) {
  1536. track.stop();
  1537. });
  1538. };
  1539. }
  1540. }
  1541. // below function via: http://goo.gl/B3ae8c
  1542. /**
  1543. * Return human-readable file size.
  1544. * @param {number} bytes - Pass bytes and get formatted string.
  1545. * @returns {string} - formatted string
  1546. * @example
  1547. * bytesToSize(1024*1024*5) === '5 GB'
  1548. * @see {@link https://github.com/muaz-khan/RecordRTC|RecordRTC Source Code}
  1549. */
  1550. function bytesToSize(bytes) {
  1551. var k = 1000;
  1552. var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  1553. if (bytes === 0) {
  1554. return '0 Bytes';
  1555. }
  1556. var i = parseInt(Math.floor(Math.log(bytes) / Math.log(k)), 10);
  1557. return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
  1558. }
  1559. /**
  1560. * @param {Blob} file - File or Blob object. This parameter is required.
  1561. * @param {string} fileName - Optional file name e.g. "Recorded-Video.webm"
  1562. * @example
  1563. * invokeSaveAsDialog(blob or file, [optional] fileName);
  1564. * @see {@link https://github.com/muaz-khan/RecordRTC|RecordRTC Source Code}
  1565. */
  1566. function invokeSaveAsDialog(file, fileName) {
  1567. if (!file) {
  1568. throw 'Blob object is required.';
  1569. }
  1570. if (!file.type) {
  1571. try {
  1572. file.type = 'video/webm';
  1573. } catch (e) {}
  1574. }
  1575. var fileExtension = (file.type || 'video/webm').split('/')[1];
  1576. if (fileExtension.indexOf(';') !== -1) {
  1577. // extended mimetype, e.g. 'video/webm;codecs=vp8,opus'
  1578. fileExtension = fileExtension.split(';')[0];
  1579. }
  1580. if (fileName && fileName.indexOf('.') !== -1) {
  1581. var splitted = fileName.split('.');
  1582. fileName = splitted[0];
  1583. fileExtension = splitted[1];
  1584. }
  1585. var fileFullName = (fileName || (Math.round(Math.random() * 9999999999) + 888888888)) + '.' + fileExtension;
  1586. if (typeof navigator.msSaveOrOpenBlob !== 'undefined') {
  1587. return navigator.msSaveOrOpenBlob(file, fileFullName);
  1588. } else if (typeof navigator.msSaveBlob !== 'undefined') {
  1589. return navigator.msSaveBlob(file, fileFullName);
  1590. }
  1591. var hyperlink = document.createElement('a');
  1592. hyperlink.href = URL.createObjectURL(file);
  1593. hyperlink.download = fileFullName;
  1594. hyperlink.style = 'display:none;opacity:0;color:transparent;';
  1595. (document.body || document.documentElement).appendChild(hyperlink);
  1596. if (typeof hyperlink.click === 'function') {
  1597. hyperlink.click();
  1598. } else {
  1599. hyperlink.target = '_blank';
  1600. hyperlink.dispatchEvent(new MouseEvent('click', {
  1601. view: window,
  1602. bubbles: true,
  1603. cancelable: true
  1604. }));
  1605. }
  1606. URL.revokeObjectURL(hyperlink.href);
  1607. }
  1608. /**
  1609. * from: https://github.com/cheton/is-electron/blob/master/index.js
  1610. **/
  1611. function isElectron() {
  1612. // Renderer process
  1613. if (typeof window !== 'undefined' && typeof window.process === 'object' && window.process.type === 'renderer') {
  1614. return true;
  1615. }
  1616. // Main process
  1617. if (typeof process !== 'undefined' && typeof process.versions === 'object' && !!process.versions.electron) {
  1618. return true;
  1619. }
  1620. // Detect the user agent when the `nodeIntegration` option is set to true
  1621. if (typeof navigator === 'object' && typeof navigator.userAgent === 'string' && navigator.userAgent.indexOf('Electron') >= 0) {
  1622. return true;
  1623. }
  1624. return false;
  1625. }
  1626. function getTracks(stream, kind) {
  1627. if (!stream || !stream.getTracks) {
  1628. return [];
  1629. }
  1630. return stream.getTracks().filter(function(t) {
  1631. return t.kind === (kind || 'audio');
  1632. });
  1633. }
  1634. function setSrcObject(stream, element) {
  1635. if ('srcObject' in element) {
  1636. element.srcObject = stream;
  1637. } else if ('mozSrcObject' in element) {
  1638. element.mozSrcObject = stream;
  1639. } else {
  1640. element.srcObject = stream;
  1641. }
  1642. }
  1643. /**
  1644. * @param {Blob} file - File or Blob object.
  1645. * @param {function} callback - Callback function.
  1646. * @example
  1647. * getSeekableBlob(blob or file, callback);
  1648. * @see {@link https://github.com/muaz-khan/RecordRTC|RecordRTC Source Code}
  1649. */
  1650. function getSeekableBlob(inputBlob, callback) {
  1651. // EBML.js copyrights goes to: https://github.com/legokichi/ts-ebml
  1652. if (typeof EBML === 'undefined') {
  1653. throw new Error('Please link: https://www.webrtc-experiment.com/EBML.js');
  1654. }
  1655. var reader = new EBML.Reader();
  1656. var decoder = new EBML.Decoder();
  1657. var tools = EBML.tools;
  1658. var fileReader = new FileReader();
  1659. fileReader.onload = function(e) {
  1660. var ebmlElms = decoder.decode(this.result);
  1661. ebmlElms.forEach(function(element) {
  1662. reader.read(element);
  1663. });
  1664. reader.stop();
  1665. var refinedMetadataBuf = tools.makeMetadataSeekable(reader.metadatas, reader.duration, reader.cues);
  1666. var body = this.result.slice(reader.metadataSize);
  1667. var newBlob = new Blob([refinedMetadataBuf, body], {
  1668. type: 'video/webm'
  1669. });
  1670. callback(newBlob);
  1671. };
  1672. fileReader.readAsArrayBuffer(inputBlob);
  1673. }
  1674. if (typeof RecordRTC !== 'undefined') {
  1675. RecordRTC.invokeSaveAsDialog = invokeSaveAsDialog;
  1676. RecordRTC.getTracks = getTracks;
  1677. RecordRTC.getSeekableBlob = getSeekableBlob;
  1678. RecordRTC.bytesToSize = bytesToSize;
  1679. RecordRTC.isElectron = isElectron;
  1680. }
  1681. // __________ (used to handle stuff like http://goo.gl/xmE5eg) issue #129
  1682. // Storage.js
  1683. /**
  1684. * Storage is a standalone object used by {@link RecordRTC} to store reusable objects e.g. "new AudioContext".
  1685. * @license {@link https://github.com/muaz-khan/RecordRTC/blob/master/LICENSE|MIT}
  1686. * @author {@link https://MuazKhan.com|Muaz Khan}
  1687. * @example
  1688. * Storage.AudioContext === webkitAudioContext
  1689. * @property {webkitAudioContext} AudioContext - Keeps a reference to AudioContext object.
  1690. * @see {@link https://github.com/muaz-khan/RecordRTC|RecordRTC Source Code}
  1691. */
  1692. var Storage = {};
  1693. if (typeof AudioContext !== 'undefined') {
  1694. Storage.AudioContext = AudioContext;
  1695. } else if (typeof webkitAudioContext !== 'undefined') {
  1696. Storage.AudioContext = webkitAudioContext;
  1697. }
  1698. if (typeof RecordRTC !== 'undefined') {
  1699. RecordRTC.Storage = Storage;
  1700. }
  1701. function isMediaRecorderCompatible() {
  1702. if (isFirefox || isSafari || isEdge) {
  1703. return true;
  1704. }
  1705. var nVer = navigator.appVersion;
  1706. var nAgt = navigator.userAgent;
  1707. var fullVersion = '' + parseFloat(navigator.appVersion);
  1708. var majorVersion = parseInt(navigator.appVersion, 10);
  1709. var nameOffset, verOffset, ix;
  1710. if (isChrome || isOpera) {
  1711. verOffset = nAgt.indexOf('Chrome');
  1712. fullVersion = nAgt.substring(verOffset + 7);
  1713. }
  1714. // trim the fullVersion string at semicolon/space if present
  1715. if ((ix = fullVersion.indexOf(';')) !== -1) {
  1716. fullVersion = fullVersion.substring(0, ix);
  1717. }
  1718. if ((ix = fullVersion.indexOf(' ')) !== -1) {
  1719. fullVersion = fullVersion.substring(0, ix);
  1720. }
  1721. majorVersion = parseInt('' + fullVersion, 10);
  1722. if (isNaN(majorVersion)) {
  1723. fullVersion = '' + parseFloat(navigator.appVersion);
  1724. majorVersion = parseInt(navigator.appVersion, 10);
  1725. }
  1726. return majorVersion >= 49;
  1727. }
  1728. // ______________________
  1729. // MediaStreamRecorder.js
  1730. /**
  1731. * MediaStreamRecorder is an abstraction layer for {@link https://w3c.github.io/mediacapture-record/MediaRecorder.html|MediaRecorder API}. It is used by {@link RecordRTC} to record MediaStream(s) in both Chrome and Firefox.
  1732. * @summary Runs top over {@link https://w3c.github.io/mediacapture-record/MediaRecorder.html|MediaRecorder API}.
  1733. * @license {@link https://github.com/muaz-khan/RecordRTC/blob/master/LICENSE|MIT}
  1734. * @author {@link https://github.com/muaz-khan|Muaz Khan}
  1735. * @typedef MediaStreamRecorder
  1736. * @class
  1737. * @example
  1738. * var config = {
  1739. * mimeType: 'video/webm', // vp8, vp9, h264, mkv, opus/vorbis
  1740. * audioBitsPerSecond : 256 * 8 * 1024,
  1741. * videoBitsPerSecond : 256 * 8 * 1024,
  1742. * bitsPerSecond: 256 * 8 * 1024, // if this is provided, skip above two
  1743. * checkForInactiveTracks: true,
  1744. * timeSlice: 1000, // concatenate intervals based blobs
  1745. * ondataavailable: function() {} // get intervals based blobs
  1746. * }
  1747. * var recorder = new MediaStreamRecorder(mediaStream, config);
  1748. * recorder.record();
  1749. * recorder.stop(function(blob) {
  1750. * video.src = URL.createObjectURL(blob);
  1751. *
  1752. * // or
  1753. * var blob = recorder.blob;
  1754. * });
  1755. * @see {@link https://github.com/muaz-khan/RecordRTC|RecordRTC Source Code}
  1756. * @param {MediaStream} mediaStream - MediaStream object fetched using getUserMedia API or generated using captureStreamUntilEnded or WebAudio API.
  1757. * @param {object} config - {disableLogs:true, initCallback: function, mimeType: "video/webm", timeSlice: 1000}
  1758. * @throws Will throw an error if first argument "MediaStream" is missing. Also throws error if "MediaRecorder API" are not supported by the browser.
  1759. */
  1760. function MediaStreamRecorder(mediaStream, config) {
  1761. var self = this;
  1762. if (typeof mediaStream === 'undefined') {
  1763. throw 'First argument "MediaStream" is required.';
  1764. }
  1765. if (typeof MediaRecorder === 'undefined') {
  1766. throw 'Your browser does not support the Media Recorder API. Please try other modules e.g. WhammyRecorder or StereoAudioRecorder.';
  1767. }
  1768. config = config || {
  1769. // bitsPerSecond: 256 * 8 * 1024,
  1770. mimeType: 'video/webm'
  1771. };
  1772. if (config.type === 'audio') {
  1773. if (getTracks(mediaStream, 'video').length && getTracks(mediaStream, 'audio').length) {
  1774. var stream;
  1775. if (!!navigator.mozGetUserMedia) {
  1776. stream = new MediaStream();
  1777. stream.addTrack(getTracks(mediaStream, 'audio')[0]);
  1778. } else {
  1779. // webkitMediaStream
  1780. stream = new MediaStream(getTracks(mediaStream, 'audio'));
  1781. }
  1782. mediaStream = stream;
  1783. }
  1784. if (!config.mimeType || config.mimeType.toString().toLowerCase().indexOf('audio') === -1) {
  1785. config.mimeType = isChrome ? 'audio/webm' : 'audio/ogg';
  1786. }
  1787. if (config.mimeType && config.mimeType.toString().toLowerCase() !== 'audio/ogg' && !!navigator.mozGetUserMedia) {
  1788. // forcing better codecs on Firefox (via #166)
  1789. config.mimeType = 'audio/ogg';
  1790. }
  1791. }
  1792. var arrayOfBlobs = [];
  1793. /**
  1794. * This method returns array of blobs. Use only with "timeSlice". Its useful to preview recording anytime, without using the "stop" method.
  1795. * @method
  1796. * @memberof MediaStreamRecorder
  1797. * @example
  1798. * var arrayOfBlobs = recorder.getArrayOfBlobs();
  1799. * @returns {Array} Returns array of recorded blobs.
  1800. */
  1801. this.getArrayOfBlobs = function() {
  1802. return arrayOfBlobs;
  1803. };
  1804. /**
  1805. * This method records MediaStream.
  1806. * @method
  1807. * @memberof MediaStreamRecorder
  1808. * @example
  1809. * recorder.record();
  1810. */
  1811. this.record = function() {
  1812. // set defaults
  1813. self.blob = null;
  1814. self.clearRecordedData();
  1815. self.timestamps = [];
  1816. allStates = [];
  1817. arrayOfBlobs = [];
  1818. var recorderHints = config;
  1819. if (!config.disableLogs) {
  1820. console.log('Passing following config over MediaRecorder API.', recorderHints);
  1821. }
  1822. if (mediaRecorder) {
  1823. // mandatory to make sure Firefox doesn't fails to record streams 3-4 times without reloading the page.
  1824. mediaRecorder = null;
  1825. }
  1826. if (isChrome && !isMediaRecorderCompatible()) {
  1827. // to support video-only recording on stable
  1828. recorderHints = 'video/vp8';
  1829. }
  1830. if (typeof MediaRecorder.isTypeSupported === 'function' && recorderHints.mimeType) {
  1831. if (!MediaRecorder.isTypeSupported(recorderHints.mimeType)) {
  1832. if (!config.disableLogs) {
  1833. console.warn('MediaRecorder API seems unable to record mimeType:', recorderHints.mimeType);
  1834. }
  1835. recorderHints.mimeType = config.type === 'audio' ? 'audio/webm' : 'video/webm';
  1836. }
  1837. }
  1838. // using MediaRecorder API here
  1839. try {
  1840. mediaRecorder = new MediaRecorder(mediaStream, recorderHints);
  1841. // reset
  1842. config.mimeType = recorderHints.mimeType;
  1843. } catch (e) {
  1844. // chrome-based fallback
  1845. mediaRecorder = new MediaRecorder(mediaStream);
  1846. }
  1847. // old hack?
  1848. if (recorderHints.mimeType && !MediaRecorder.isTypeSupported && 'canRecordMimeType' in mediaRecorder && mediaRecorder.canRecordMimeType(recorderHints.mimeType) === false) {
  1849. if (!config.disableLogs) {
  1850. console.warn('MediaRecorder API seems unable to record mimeType:', recorderHints.mimeType);
  1851. }
  1852. }
  1853. // Dispatching OnDataAvailable Handler
  1854. mediaRecorder.ondataavailable = function(e) {
  1855. if (e.data) {
  1856. allStates.push('ondataavailable: ' + bytesToSize(e.data.size));
  1857. }
  1858. if (typeof config.timeSlice === 'number') {
  1859. if (e.data && e.data.size) {
  1860. arrayOfBlobs.push(e.data);
  1861. updateTimeStamp();
  1862. if (typeof config.ondataavailable === 'function') {
  1863. // intervals based blobs
  1864. var blob = config.getNativeBlob ? e.data : new Blob([e.data], {
  1865. type: getMimeType(recorderHints)
  1866. });
  1867. config.ondataavailable(blob);
  1868. }
  1869. }
  1870. return;
  1871. }
  1872. if (!e.data || !e.data.size || e.data.size < 100 || self.blob) {
  1873. // make sure that stopRecording always getting fired
  1874. // even if there is invalid data
  1875. if (self.recordingCallback) {
  1876. self.recordingCallback(new Blob([], {
  1877. type: getMimeType(recorderHints)
  1878. }));
  1879. self.recordingCallback = null;
  1880. }
  1881. return;
  1882. }
  1883. self.blob = config.getNativeBlob ? e.data : new Blob([e.data], {
  1884. type: getMimeType(recorderHints)
  1885. });
  1886. if (self.recordingCallback) {
  1887. self.recordingCallback(self.blob);
  1888. self.recordingCallback = null;
  1889. }
  1890. };
  1891. mediaRecorder.onstart = function() {
  1892. allStates.push('started');
  1893. };
  1894. mediaRecorder.onpause = function() {
  1895. allStates.push('paused');
  1896. };
  1897. mediaRecorder.onresume = function() {
  1898. allStates.push('resumed');
  1899. };
  1900. mediaRecorder.onstop = function() {
  1901. allStates.push('stopped');
  1902. };
  1903. mediaRecorder.onerror = function(error) {
  1904. if (!error) {
  1905. return;
  1906. }
  1907. if (!error.name) {
  1908. error.name = 'UnknownError';
  1909. }
  1910. allStates.push('error: ' + error);
  1911. if (!config.disableLogs) {
  1912. // via: https://w3c.github.io/mediacapture-record/MediaRecorder.html#exception-summary
  1913. if (error.name.toString().toLowerCase().indexOf('invalidstate') !== -1) {
  1914. console.error('The MediaRecorder is not in a state in which the proposed operation is allowed to be executed.', error);
  1915. } else if (error.name.toString().toLowerCase().indexOf('notsupported') !== -1) {
  1916. console.error('MIME type (', recorderHints.mimeType, ') is not supported.', error);
  1917. } else if (error.name.toString().toLowerCase().indexOf('security') !== -1) {
  1918. console.error('MediaRecorder security error', error);
  1919. }
  1920. // older code below
  1921. else if (error.name === 'OutOfMemory') {
  1922. console.error('The UA has exhaused the available memory. User agents SHOULD provide as much additional information as possible in the message attribute.', error);
  1923. } else if (error.name === 'IllegalStreamModification') {
  1924. console.error('A modification to the stream has occurred that makes it impossible to continue recording. An example would be the addition of a Track while recording is occurring. User agents SHOULD provide as much additional information as possible in the message attribute.', error);
  1925. } else if (error.name === 'OtherRecordingError') {
  1926. console.error('Used for an fatal error other than those listed above. User agents SHOULD provide as much additional information as possible in the message attribute.', error);
  1927. } else if (error.name === 'GenericError') {
  1928. console.error('The UA cannot provide the codec or recording option that has been requested.', error);
  1929. } else {
  1930. console.error('MediaRecorder Error', error);
  1931. }
  1932. }
  1933. (function(looper) {
  1934. if (!self.manuallyStopped && mediaRecorder && mediaRecorder.state === 'inactive') {
  1935. delete config.timeslice;
  1936. // 10 minutes, enough?
  1937. mediaRecorder.start(10 * 60 * 1000);
  1938. return;
  1939. }
  1940. setTimeout(looper, 1000);
  1941. })();
  1942. if (mediaRecorder.state !== 'inactive' && mediaRecorder.state !== 'stopped') {
  1943. mediaRecorder.stop();
  1944. }
  1945. };
  1946. if (typeof config.timeSlice === 'number') {
  1947. updateTimeStamp();
  1948. mediaRecorder.start(config.timeSlice);
  1949. } else {
  1950. // default is 60 minutes; enough?
  1951. // use config => {timeSlice: 1000} otherwise
  1952. mediaRecorder.start(3.6e+6);
  1953. }
  1954. if (config.initCallback) {
  1955. config.initCallback(); // old code
  1956. }
  1957. };
  1958. /**
  1959. * @property {Array} timestamps - Array of time stamps
  1960. * @memberof MediaStreamRecorder
  1961. * @example
  1962. * console.log(recorder.timestamps);
  1963. */
  1964. this.timestamps = [];
  1965. function updateTimeStamp() {
  1966. self.timestamps.push(new Date().getTime());
  1967. if (typeof config.onTimeStamp === 'function') {
  1968. config.onTimeStamp(self.timestamps[self.timestamps.length - 1], self.timestamps);
  1969. }
  1970. }
  1971. function getMimeType(secondObject) {
  1972. if (mediaRecorder && mediaRecorder.mimeType) {
  1973. return mediaRecorder.mimeType;
  1974. }
  1975. return secondObject.mimeType || 'video/webm';
  1976. }
  1977. /**
  1978. * This method stops recording MediaStream.
  1979. * @param {function} callback - Callback function, that is used to pass recorded blob back to the callee.
  1980. * @method
  1981. * @memberof MediaStreamRecorder
  1982. * @example
  1983. * recorder.stop(function(blob) {
  1984. * video.src = URL.createObjectURL(blob);
  1985. * });
  1986. */
  1987. this.stop = function(callback) {
  1988. callback = callback || function() {};
  1989. self.manuallyStopped = true; // used inside the mediaRecorder.onerror
  1990. if (!mediaRecorder) {
  1991. return;
  1992. }
  1993. this.recordingCallback = callback;
  1994. if (mediaRecorder.state === 'recording') {
  1995. mediaRecorder.stop();
  1996. }
  1997. if (typeof config.timeSlice === 'number') {
  1998. setTimeout(function() {
  1999. self.blob = new Blob(arrayOfBlobs, {
  2000. type: getMimeType(config)
  2001. });
  2002. self.recordingCallback(self.blob);
  2003. }, 100);
  2004. }
  2005. };
  2006. /**
  2007. * This method pauses the recording process.
  2008. * @method
  2009. * @memberof MediaStreamRecorder
  2010. * @example
  2011. * recorder.pause();
  2012. */
  2013. this.pause = function() {
  2014. if (!mediaRecorder) {
  2015. return;
  2016. }
  2017. if (mediaRecorder.state === 'recording') {
  2018. mediaRecorder.pause();
  2019. }
  2020. };
  2021. /**
  2022. * This method resumes the recording process.
  2023. * @method
  2024. * @memberof MediaStreamRecorder
  2025. * @example
  2026. * recorder.resume();
  2027. */
  2028. this.resume = function() {
  2029. if (!mediaRecorder) {
  2030. return;
  2031. }
  2032. if (mediaRecorder.state === 'paused') {
  2033. mediaRecorder.resume();
  2034. }
  2035. };
  2036. /**
  2037. * This method resets currently recorded data.
  2038. * @method
  2039. * @memberof MediaStreamRecorder
  2040. * @example
  2041. * recorder.clearRecordedData();
  2042. */
  2043. this.clearRecordedData = function() {
  2044. if (mediaRecorder && mediaRecorder.state === 'recording') {
  2045. self.stop(clearRecordedDataCB);
  2046. }
  2047. clearRecordedDataCB();
  2048. };
  2049. function clearRecordedDataCB() {
  2050. arrayOfBlobs = [];
  2051. mediaRecorder = null;
  2052. self.timestamps = [];
  2053. }
  2054. // Reference to "MediaRecorder" object
  2055. var mediaRecorder;
  2056. /**
  2057. * Access to native MediaRecorder API
  2058. * @method
  2059. * @memberof MediaStreamRecorder
  2060. * @instance
  2061. * @example
  2062. * var internal = recorder.getInternalRecorder();
  2063. * internal.ondataavailable = function() {}; // override
  2064. * internal.stream, internal.onpause, internal.onstop, etc.
  2065. * @returns {Object} Returns internal recording object.
  2066. */
  2067. this.getInternalRecorder = function() {
  2068. return mediaRecorder;
  2069. };
  2070. function isMediaStreamActive() {
  2071. if ('active' in mediaStream) {
  2072. if (!mediaStream.active) {
  2073. return false;
  2074. }
  2075. } else if ('ended' in mediaStream) { // old hack
  2076. if (mediaStream.ended) {
  2077. return false;
  2078. }
  2079. }
  2080. return true;
  2081. }
  2082. /**
  2083. * @property {Blob} blob - Recorded data as "Blob" object.
  2084. * @memberof MediaStreamRecorder
  2085. * @example
  2086. * recorder.stop(function() {
  2087. * var blob = recorder.blob;
  2088. * });
  2089. */
  2090. this.blob = null;
  2091. /**
  2092. * Get MediaRecorder readonly state.
  2093. * @method
  2094. * @memberof MediaStreamRecorder
  2095. * @example
  2096. * var state = recorder.getState();
  2097. * @returns {String} Returns recording state.
  2098. */
  2099. this.getState = function() {
  2100. if (!mediaRecorder) {
  2101. return 'inactive';
  2102. }
  2103. return mediaRecorder.state || 'inactive';
  2104. };
  2105. // list of all recording states
  2106. var allStates = [];
  2107. /**
  2108. * Get MediaRecorder all recording states.
  2109. * @method
  2110. * @memberof MediaStreamRecorder
  2111. * @example
  2112. * var state = recorder.getAllStates();
  2113. * @returns {Array} Returns all recording states
  2114. */
  2115. this.getAllStates = function() {
  2116. return allStates;
  2117. };
  2118. // if any Track within the MediaStream is muted or not enabled at any time,
  2119. // the browser will only record black frames
  2120. // or silence since that is the content produced by the Track
  2121. // so we need to stopRecording as soon as any single track ends.
  2122. if (typeof config.checkForInactiveTracks === 'undefined') {
  2123. config.checkForInactiveTracks = false; // disable to minimize CPU usage
  2124. }
  2125. var self = this;
  2126. // this method checks if media stream is stopped
  2127. // or if any track is ended.
  2128. (function looper() {
  2129. if (!mediaRecorder || config.checkForInactiveTracks === false) {
  2130. return;
  2131. }
  2132. if (isMediaStreamActive() === false) {
  2133. if (!config.disableLogs) {
  2134. console.log('MediaStream seems stopped.');
  2135. }
  2136. self.stop();
  2137. return;
  2138. }
  2139. setTimeout(looper, 1000); // check every second
  2140. })();
  2141. // for debugging
  2142. this.name = 'MediaStreamRecorder';
  2143. this.toString = function() {
  2144. return this.name;
  2145. };
  2146. }
  2147. if (typeof RecordRTC !== 'undefined') {
  2148. RecordRTC.MediaStreamRecorder = MediaStreamRecorder;
  2149. }
  2150. // source code from: http://typedarray.org/wp-content/projects/WebAudioRecorder/script.js
  2151. // https://github.com/mattdiamond/Recorderjs#license-mit
  2152. // ______________________
  2153. // StereoAudioRecorder.js
  2154. /**
  2155. * StereoAudioRecorder is a standalone class used by {@link RecordRTC} to bring "stereo" audio-recording in chrome.
  2156. * @summary JavaScript standalone object for stereo audio recording.
  2157. * @license {@link https://github.com/muaz-khan/RecordRTC/blob/master/LICENSE|MIT}
  2158. * @author {@link https://MuazKhan.com|Muaz Khan}
  2159. * @typedef StereoAudioRecorder
  2160. * @class
  2161. * @example
  2162. * var recorder = new StereoAudioRecorder(MediaStream, {
  2163. * sampleRate: 44100,
  2164. * bufferSize: 4096
  2165. * });
  2166. * recorder.record();
  2167. * recorder.stop(function(blob) {
  2168. * video.src = URL.createObjectURL(blob);
  2169. * });
  2170. * @see {@link https://github.com/muaz-khan/RecordRTC|RecordRTC Source Code}
  2171. * @param {MediaStream} mediaStream - MediaStream object fetched using getUserMedia API or generated using captureStreamUntilEnded or WebAudio API.
  2172. * @param {object} config - {sampleRate: 44100, bufferSize: 4096, numberOfAudioChannels: 1, etc.}
  2173. */
  2174. function StereoAudioRecorder(mediaStream, config) {
  2175. if (!getTracks(mediaStream, 'audio').length) {
  2176. throw 'Your stream has no audio tracks.';
  2177. }
  2178. config = config || {};
  2179. var self = this;
  2180. // variables
  2181. var leftchannel = [];
  2182. var rightchannel = [];
  2183. var recording = false;
  2184. var recordingLength = 0;
  2185. var jsAudioNode;
  2186. var numberOfAudioChannels = 2;
  2187. /**
  2188. * Set sample rates such as 8K or 16K. Reference: http://stackoverflow.com/a/28977136/552182
  2189. * @property {number} desiredSampRate - Desired Bits per sample * 1000
  2190. * @memberof StereoAudioRecorder
  2191. * @instance
  2192. * @example
  2193. * var recorder = StereoAudioRecorder(mediaStream, {
  2194. * desiredSampRate: 16 * 1000 // bits-per-sample * 1000
  2195. * });
  2196. */
  2197. var desiredSampRate = config.desiredSampRate;
  2198. // backward compatibility
  2199. if (config.leftChannel === true) {
  2200. numberOfAudioChannels = 1;
  2201. }
  2202. if (config.numberOfAudioChannels === 1) {
  2203. numberOfAudioChannels = 1;
  2204. }
  2205. if (!numberOfAudioChannels || numberOfAudioChannels < 1) {
  2206. numberOfAudioChannels = 2;
  2207. }
  2208. if (!config.disableLogs) {
  2209. console.log('StereoAudioRecorder is set to record number of channels: ' + numberOfAudioChannels);
  2210. }
  2211. // if any Track within the MediaStream is muted or not enabled at any time,
  2212. // the browser will only record black frames
  2213. // or silence since that is the content produced by the Track
  2214. // so we need to stopRecording as soon as any single track ends.
  2215. if (typeof config.checkForInactiveTracks === 'undefined') {
  2216. config.checkForInactiveTracks = true;
  2217. }
  2218. function isMediaStreamActive() {
  2219. if (config.checkForInactiveTracks === false) {
  2220. // always return "true"
  2221. return true;
  2222. }
  2223. if ('active' in mediaStream) {
  2224. if (!mediaStream.active) {
  2225. return false;
  2226. }
  2227. } else if ('ended' in mediaStream) { // old hack
  2228. if (mediaStream.ended) {
  2229. return false;
  2230. }
  2231. }
  2232. return true;
  2233. }
  2234. /**
  2235. * This method records MediaStream.
  2236. * @method
  2237. * @memberof StereoAudioRecorder
  2238. * @example
  2239. * recorder.record();
  2240. */
  2241. this.record = function() {
  2242. if (isMediaStreamActive() === false) {
  2243. throw 'Please make sure MediaStream is active.';
  2244. }
  2245. resetVariables();
  2246. isAudioProcessStarted = isPaused = false;
  2247. recording = true;
  2248. if (typeof config.timeSlice !== 'undefined') {
  2249. looper();
  2250. }
  2251. };
  2252. function mergeLeftRightBuffers(config, callback) {
  2253. function mergeAudioBuffers(config, cb) {
  2254. var numberOfAudioChannels = config.numberOfAudioChannels;
  2255. // todo: "slice(0)" --- is it causes loop? Should be removed?
  2256. var leftBuffers = config.leftBuffers.slice(0);
  2257. var rightBuffers = config.rightBuffers.slice(0);
  2258. var sampleRate = config.sampleRate;
  2259. var internalInterleavedLength = config.internalInterleavedLength;
  2260. var desiredSampRate = config.desiredSampRate;
  2261. if (numberOfAudioChannels === 2) {
  2262. leftBuffers = mergeBuffers(leftBuffers, internalInterleavedLength);
  2263. rightBuffers = mergeBuffers(rightBuffers, internalInterleavedLength);
  2264. if (desiredSampRate) {
  2265. leftBuffers = interpolateArray(leftBuffers, desiredSampRate, sampleRate);
  2266. rightBuffers = interpolateArray(rightBuffers, desiredSampRate, sampleRate);
  2267. }
  2268. }
  2269. if (numberOfAudioChannels === 1) {
  2270. leftBuffers = mergeBuffers(leftBuffers, internalInterleavedLength);
  2271. if (desiredSampRate) {
  2272. leftBuffers = interpolateArray(leftBuffers, desiredSampRate, sampleRate);
  2273. }
  2274. }
  2275. // set sample rate as desired sample rate
  2276. if (desiredSampRate) {
  2277. sampleRate = desiredSampRate;
  2278. }
  2279. // for changing the sampling rate, reference:
  2280. // http://stackoverflow.com/a/28977136/552182
  2281. function interpolateArray(data, newSampleRate, oldSampleRate) {
  2282. var fitCount = Math.round(data.length * (newSampleRate / oldSampleRate));
  2283. var newData = [];
  2284. var springFactor = Number((data.length - 1) / (fitCount - 1));
  2285. newData[0] = data[0];
  2286. for (var i = 1; i < fitCount - 1; i++) {
  2287. var tmp = i * springFactor;
  2288. var before = Number(Math.floor(tmp)).toFixed();
  2289. var after = Number(Math.ceil(tmp)).toFixed();
  2290. var atPoint = tmp - before;
  2291. newData[i] = linearInterpolate(data[before], data[after], atPoint);
  2292. }
  2293. newData[fitCount - 1] = data[data.length - 1];
  2294. return newData;
  2295. }
  2296. function linearInterpolate(before, after, atPoint) {
  2297. return before + (after - before) * atPoint;
  2298. }
  2299. function mergeBuffers(channelBuffer, rLength) {
  2300. var result = new Float64Array(rLength);
  2301. var offset = 0;
  2302. var lng = channelBuffer.length;
  2303. for (var i = 0; i < lng; i++) {
  2304. var buffer = channelBuffer[i];
  2305. result.set(buffer, offset);
  2306. offset += buffer.length;
  2307. }
  2308. return result;
  2309. }
  2310. function interleave(leftChannel, rightChannel) {
  2311. var length = leftChannel.length + rightChannel.length;
  2312. var result = new Float64Array(length);
  2313. var inputIndex = 0;
  2314. for (var index = 0; index < length;) {
  2315. result[index++] = leftChannel[inputIndex];
  2316. result[index++] = rightChannel[inputIndex];
  2317. inputIndex++;
  2318. }
  2319. return result;
  2320. }
  2321. function writeUTFBytes(view, offset, string) {
  2322. var lng = string.length;
  2323. for (var i = 0; i < lng; i++) {
  2324. view.setUint8(offset + i, string.charCodeAt(i));
  2325. }
  2326. }
  2327. // interleave both channels together
  2328. var interleaved;
  2329. if (numberOfAudioChannels === 2) {
  2330. interleaved = interleave(leftBuffers, rightBuffers);
  2331. }
  2332. if (numberOfAudioChannels === 1) {
  2333. interleaved = leftBuffers;
  2334. }
  2335. var interleavedLength = interleaved.length;
  2336. // create wav file
  2337. var resultingBufferLength = 44 + interleavedLength * 2;
  2338. var buffer = new ArrayBuffer(resultingBufferLength);
  2339. var view = new DataView(buffer);
  2340. // RIFF chunk descriptor/identifier
  2341. writeUTFBytes(view, 0, 'RIFF');
  2342. // RIFF chunk length
  2343. // changed "44" to "36" via #401
  2344. view.setUint32(4, 36 + interleavedLength * 2, true);
  2345. // RIFF type
  2346. writeUTFBytes(view, 8, 'WAVE');
  2347. // format chunk identifier
  2348. // FMT sub-chunk
  2349. writeUTFBytes(view, 12, 'fmt ');
  2350. // format chunk length
  2351. view.setUint32(16, 16, true);
  2352. // sample format (raw)
  2353. view.setUint16(20, 1, true);
  2354. // stereo (2 channels)
  2355. view.setUint16(22, numberOfAudioChannels, true);
  2356. // sample rate
  2357. view.setUint32(24, sampleRate, true);
  2358. // byte rate (sample rate * block align)
  2359. view.setUint32(28, sampleRate * numberOfAudioChannels * 2, true);
  2360. // block align (channel count * bytes per sample)
  2361. view.setUint16(32, numberOfAudioChannels * 2, true);
  2362. // bits per sample
  2363. view.setUint16(34, 16, true);
  2364. // data sub-chunk
  2365. // data chunk identifier
  2366. writeUTFBytes(view, 36, 'data');
  2367. // data chunk length
  2368. view.setUint32(40, interleavedLength * 2, true);
  2369. // write the PCM samples
  2370. var lng = interleavedLength;
  2371. var index = 44;
  2372. var volume = 1;
  2373. for (var i = 0; i < lng; i++) {
  2374. view.setInt16(index, interleaved[i] * (0x7FFF * volume), true);
  2375. index += 2;
  2376. }
  2377. if (cb) {
  2378. return cb({
  2379. buffer: buffer,
  2380. view: view
  2381. });
  2382. }
  2383. postMessage({
  2384. buffer: buffer,
  2385. view: view
  2386. });
  2387. }
  2388. if (config.noWorker) {
  2389. mergeAudioBuffers(config, function(data) {
  2390. callback(data.buffer, data.view);
  2391. });
  2392. return;
  2393. }
  2394. var webWorker = processInWebWorker(mergeAudioBuffers);
  2395. webWorker.onmessage = function(event) {
  2396. callback(event.data.buffer, event.data.view);
  2397. // release memory
  2398. URL.revokeObjectURL(webWorker.workerURL);
  2399. // kill webworker (or Chrome will kill your page after ~25 calls)
  2400. webWorker.terminate();
  2401. };
  2402. webWorker.postMessage(config);
  2403. }
  2404. function processInWebWorker(_function) {
  2405. var workerURL = URL.createObjectURL(new Blob([_function.toString(),
  2406. ';this.onmessage = function (eee) {' + _function.name + '(eee.data);}'
  2407. ], {
  2408. type: 'application/javascript'
  2409. }));
  2410. var worker = new Worker(workerURL);
  2411. worker.workerURL = workerURL;
  2412. return worker;
  2413. }
  2414. /**
  2415. * This method stops recording MediaStream.
  2416. * @param {function} callback - Callback function, that is used to pass recorded blob back to the callee.
  2417. * @method
  2418. * @memberof StereoAudioRecorder
  2419. * @example
  2420. * recorder.stop(function(blob) {
  2421. * video.src = URL.createObjectURL(blob);
  2422. * });
  2423. */
  2424. this.stop = function(callback) {
  2425. callback = callback || function() {};
  2426. // stop recording
  2427. recording = false;
  2428. mergeLeftRightBuffers({
  2429. desiredSampRate: desiredSampRate,
  2430. sampleRate: sampleRate,
  2431. numberOfAudioChannels: numberOfAudioChannels,
  2432. internalInterleavedLength: recordingLength,
  2433. leftBuffers: leftchannel,
  2434. rightBuffers: numberOfAudioChannels === 1 ? [] : rightchannel,
  2435. noWorker: config.noWorker
  2436. }, function(buffer, view) {
  2437. /**
  2438. * @property {Blob} blob - The recorded blob object.
  2439. * @memberof StereoAudioRecorder
  2440. * @example
  2441. * recorder.stop(function(){
  2442. * var blob = recorder.blob;
  2443. * });
  2444. */
  2445. self.blob = new Blob([view], {
  2446. type: 'audio/wav'
  2447. });
  2448. /**
  2449. * @property {ArrayBuffer} buffer - The recorded buffer object.
  2450. * @memberof StereoAudioRecorder
  2451. * @example
  2452. * recorder.stop(function(){
  2453. * var buffer = recorder.buffer;
  2454. * });
  2455. */
  2456. self.buffer = new ArrayBuffer(view.buffer.byteLength);
  2457. /**
  2458. * @property {DataView} view - The recorded data-view object.
  2459. * @memberof StereoAudioRecorder
  2460. * @example
  2461. * recorder.stop(function(){
  2462. * var view = recorder.view;
  2463. * });
  2464. */
  2465. self.view = view;
  2466. self.sampleRate = desiredSampRate || sampleRate;
  2467. self.bufferSize = bufferSize;
  2468. // recorded audio length
  2469. self.length = recordingLength;
  2470. isAudioProcessStarted = false;
  2471. if (callback) {
  2472. callback(self.blob);
  2473. }
  2474. });
  2475. };
  2476. if (typeof RecordRTC.Storage === 'undefined') {
  2477. RecordRTC.Storage = {
  2478. AudioContextConstructor: null,
  2479. AudioContext: window.AudioContext || window.webkitAudioContext
  2480. };
  2481. }
  2482. if (!RecordRTC.Storage.AudioContextConstructor || RecordRTC.Storage.AudioContextConstructor.state === 'closed') {
  2483. RecordRTC.Storage.AudioContextConstructor = new RecordRTC.Storage.AudioContext();
  2484. }
  2485. var context = RecordRTC.Storage.AudioContextConstructor;
  2486. // creates an audio node from the microphone incoming stream
  2487. var audioInput = context.createMediaStreamSource(mediaStream);
  2488. var legalBufferValues = [0, 256, 512, 1024, 2048, 4096, 8192, 16384];
  2489. /**
  2490. * From the spec: This value controls how frequently the audioprocess event is
  2491. * dispatched and how many sample-frames need to be processed each call.
  2492. * Lower values for buffer size will result in a lower (better) latency.
  2493. * Higher values will be necessary to avoid audio breakup and glitches
  2494. * The size of the buffer (in sample-frames) which needs to
  2495. * be processed each time onprocessaudio is called.
  2496. * Legal values are (256, 512, 1024, 2048, 4096, 8192, 16384).
  2497. * @property {number} bufferSize - Buffer-size for how frequently the audioprocess event is dispatched.
  2498. * @memberof StereoAudioRecorder
  2499. * @example
  2500. * recorder = new StereoAudioRecorder(mediaStream, {
  2501. * bufferSize: 4096
  2502. * });
  2503. */
  2504. // "0" means, let chrome decide the most accurate buffer-size for current platform.
  2505. var bufferSize = typeof config.bufferSize === 'undefined' ? 4096 : config.bufferSize;
  2506. if (legalBufferValues.indexOf(bufferSize) === -1) {
  2507. if (!config.disableLogs) {
  2508. console.log('Legal values for buffer-size are ' + JSON.stringify(legalBufferValues, null, '\t'));
  2509. }
  2510. }
  2511. if (context.createJavaScriptNode) {
  2512. jsAudioNode = context.createJavaScriptNode(bufferSize, numberOfAudioChannels, numberOfAudioChannels);
  2513. } else if (context.createScriptProcessor) {
  2514. jsAudioNode = context.createScriptProcessor(bufferSize, numberOfAudioChannels, numberOfAudioChannels);
  2515. } else {
  2516. throw 'WebAudio API has no support on this browser.';
  2517. }
  2518. // connect the stream to the script processor
  2519. audioInput.connect(jsAudioNode);
  2520. if (!config.bufferSize) {
  2521. bufferSize = jsAudioNode.bufferSize; // device buffer-size
  2522. }
  2523. /**
  2524. * The sample rate (in sample-frames per second) at which the
  2525. * AudioContext handles audio. It is assumed that all AudioNodes
  2526. * in the context run at this rate. In making this assumption,
  2527. * sample-rate converters or "varispeed" processors are not supported
  2528. * in real-time processing.
  2529. * The sampleRate parameter describes the sample-rate of the
  2530. * linear PCM audio data in the buffer in sample-frames per second.
  2531. * An implementation must support sample-rates in at least
  2532. * the range 22050 to 96000.
  2533. * @property {number} sampleRate - Buffer-size for how frequently the audioprocess event is dispatched.
  2534. * @memberof StereoAudioRecorder
  2535. * @example
  2536. * recorder = new StereoAudioRecorder(mediaStream, {
  2537. * sampleRate: 44100
  2538. * });
  2539. */
  2540. var sampleRate = typeof config.sampleRate !== 'undefined' ? config.sampleRate : context.sampleRate || 44100;
  2541. if (sampleRate < 22050 || sampleRate > 96000) {
  2542. // Ref: http://stackoverflow.com/a/26303918/552182
  2543. if (!config.disableLogs) {
  2544. console.log('sample-rate must be under range 22050 and 96000.');
  2545. }
  2546. }
  2547. if (!config.disableLogs) {
  2548. if (config.desiredSampRate) {
  2549. console.log('Desired sample-rate: ' + config.desiredSampRate);
  2550. }
  2551. }
  2552. var isPaused = false;
  2553. /**
  2554. * This method pauses the recording process.
  2555. * @method
  2556. * @memberof StereoAudioRecorder
  2557. * @example
  2558. * recorder.pause();
  2559. */
  2560. this.pause = function() {
  2561. isPaused = true;
  2562. };
  2563. /**
  2564. * This method resumes the recording process.
  2565. * @method
  2566. * @memberof StereoAudioRecorder
  2567. * @example
  2568. * recorder.resume();
  2569. */
  2570. this.resume = function() {
  2571. if (isMediaStreamActive() === false) {
  2572. throw 'Please make sure MediaStream is active.';
  2573. }
  2574. if (!recording) {
  2575. if (!config.disableLogs) {
  2576. console.log('Seems recording has been restarted.');
  2577. }
  2578. this.record();
  2579. return;
  2580. }
  2581. isPaused = false;
  2582. };
  2583. /**
  2584. * This method resets currently recorded data.
  2585. * @method
  2586. * @memberof StereoAudioRecorder
  2587. * @example
  2588. * recorder.clearRecordedData();
  2589. */
  2590. this.clearRecordedData = function() {
  2591. config.checkForInactiveTracks = false;
  2592. if (recording) {
  2593. this.stop(clearRecordedDataCB);
  2594. }
  2595. clearRecordedDataCB();
  2596. };
  2597. function resetVariables() {
  2598. leftchannel = [];
  2599. rightchannel = [];
  2600. recordingLength = 0;
  2601. isAudioProcessStarted = false;
  2602. recording = false;
  2603. isPaused = false;
  2604. context = null;
  2605. self.leftchannel = leftchannel;
  2606. self.rightchannel = rightchannel;
  2607. self.numberOfAudioChannels = numberOfAudioChannels;
  2608. self.desiredSampRate = desiredSampRate;
  2609. self.sampleRate = sampleRate;
  2610. self.recordingLength = recordingLength;
  2611. intervalsBasedBuffers = {
  2612. left: [],
  2613. right: [],
  2614. recordingLength: 0
  2615. };
  2616. }
  2617. function clearRecordedDataCB() {
  2618. if (jsAudioNode) {
  2619. jsAudioNode.onaudioprocess = null;
  2620. jsAudioNode.disconnect();
  2621. jsAudioNode = null;
  2622. }
  2623. if (audioInput) {
  2624. audioInput.disconnect();
  2625. audioInput = null;
  2626. }
  2627. resetVariables();
  2628. }
  2629. // for debugging
  2630. this.name = 'StereoAudioRecorder';
  2631. this.toString = function() {
  2632. return this.name;
  2633. };
  2634. var isAudioProcessStarted = false;
  2635. function onAudioProcessDataAvailable(e) {
  2636. if (isPaused) {
  2637. return;
  2638. }
  2639. if (isMediaStreamActive() === false) {
  2640. if (!config.disableLogs) {
  2641. console.log('MediaStream seems stopped.');
  2642. }
  2643. jsAudioNode.disconnect();
  2644. recording = false;
  2645. }
  2646. if (!recording) {
  2647. if (audioInput) {
  2648. audioInput.disconnect();
  2649. audioInput = null;
  2650. }
  2651. return;
  2652. }
  2653. /**
  2654. * This method is called on "onaudioprocess" event's first invocation.
  2655. * @method {function} onAudioProcessStarted
  2656. * @memberof StereoAudioRecorder
  2657. * @example
  2658. * recorder.onAudioProcessStarted: function() { };
  2659. */
  2660. if (!isAudioProcessStarted) {
  2661. isAudioProcessStarted = true;
  2662. if (config.onAudioProcessStarted) {
  2663. config.onAudioProcessStarted();
  2664. }
  2665. if (config.initCallback) {
  2666. config.initCallback();
  2667. }
  2668. }
  2669. var left = e.inputBuffer.getChannelData(0);
  2670. // we clone the samples
  2671. var chLeft = new Float32Array(left);
  2672. leftchannel.push(chLeft);
  2673. if (numberOfAudioChannels === 2) {
  2674. var right = e.inputBuffer.getChannelData(1);
  2675. var chRight = new Float32Array(right);
  2676. rightchannel.push(chRight);
  2677. }
  2678. recordingLength += bufferSize;
  2679. // export raw PCM
  2680. self.recordingLength = recordingLength;
  2681. if (typeof config.timeSlice !== 'undefined') {
  2682. intervalsBasedBuffers.recordingLength += bufferSize;
  2683. intervalsBasedBuffers.left.push(chLeft);
  2684. if (numberOfAudioChannels === 2) {
  2685. intervalsBasedBuffers.right.push(chRight);
  2686. }
  2687. }
  2688. }
  2689. jsAudioNode.onaudioprocess = onAudioProcessDataAvailable;
  2690. // to prevent self audio to be connected with speakers
  2691. if (context.createMediaStreamDestination) {
  2692. jsAudioNode.connect(context.createMediaStreamDestination());
  2693. } else {
  2694. jsAudioNode.connect(context.destination);
  2695. }
  2696. // export raw PCM
  2697. this.leftchannel = leftchannel;
  2698. this.rightchannel = rightchannel;
  2699. this.numberOfAudioChannels = numberOfAudioChannels;
  2700. this.desiredSampRate = desiredSampRate;
  2701. this.sampleRate = sampleRate;
  2702. self.recordingLength = recordingLength;
  2703. // helper for intervals based blobs
  2704. var intervalsBasedBuffers = {
  2705. left: [],
  2706. right: [],
  2707. recordingLength: 0
  2708. };
  2709. // this looper is used to support intervals based blobs (via timeSlice+ondataavailable)
  2710. function looper() {
  2711. if (!recording || typeof config.ondataavailable !== 'function' || typeof config.timeSlice === 'undefined') {
  2712. return;
  2713. }
  2714. if (intervalsBasedBuffers.left.length) {
  2715. mergeLeftRightBuffers({
  2716. desiredSampRate: desiredSampRate,
  2717. sampleRate: sampleRate,
  2718. numberOfAudioChannels: numberOfAudioChannels,
  2719. internalInterleavedLength: intervalsBasedBuffers.recordingLength,
  2720. leftBuffers: intervalsBasedBuffers.left,
  2721. rightBuffers: numberOfAudioChannels === 1 ? [] : intervalsBasedBuffers.right
  2722. }, function(buffer, view) {
  2723. var blob = new Blob([view], {
  2724. type: 'audio/wav'
  2725. });
  2726. config.ondataavailable(blob);
  2727. setTimeout(looper, config.timeSlice);
  2728. });
  2729. intervalsBasedBuffers = {
  2730. left: [],
  2731. right: [],
  2732. recordingLength: 0
  2733. };
  2734. } else {
  2735. setTimeout(looper, config.timeSlice);
  2736. }
  2737. }
  2738. }
  2739. if (typeof RecordRTC !== 'undefined') {
  2740. RecordRTC.StereoAudioRecorder = StereoAudioRecorder;
  2741. }
  2742. // _________________
  2743. // CanvasRecorder.js
  2744. /**
  2745. * CanvasRecorder is a standalone class used by {@link RecordRTC} to bring HTML5-Canvas recording into video WebM. It uses HTML2Canvas library and runs top over {@link Whammy}.
  2746. * @summary HTML2Canvas recording into video WebM.
  2747. * @license {@link https://github.com/muaz-khan/RecordRTC/blob/master/LICENSE|MIT}
  2748. * @author {@link https://MuazKhan.com|Muaz Khan}
  2749. * @typedef CanvasRecorder
  2750. * @class
  2751. * @example
  2752. * var recorder = new CanvasRecorder(htmlElement, { disableLogs: true, useWhammyRecorder: true });
  2753. * recorder.record();
  2754. * recorder.stop(function(blob) {
  2755. * video.src = URL.createObjectURL(blob);
  2756. * });
  2757. * @see {@link https://github.com/muaz-khan/RecordRTC|RecordRTC Source Code}
  2758. * @param {HTMLElement} htmlElement - querySelector/getElementById/getElementsByTagName[0]/etc.
  2759. * @param {object} config - {disableLogs:true, initCallback: function}
  2760. */
  2761. function CanvasRecorder(htmlElement, config) {
  2762. if (typeof html2canvas === 'undefined') {
  2763. throw 'Please link: https://www.webrtc-experiment.com/screenshot.js';
  2764. }
  2765. config = config || {};
  2766. if (!config.frameInterval) {
  2767. config.frameInterval = 10;
  2768. }
  2769. // via DetectRTC.js
  2770. var isCanvasSupportsStreamCapturing = false;
  2771. ['captureStream', 'mozCaptureStream', 'webkitCaptureStream'].forEach(function(item) {
  2772. if (item in document.createElement('canvas')) {
  2773. isCanvasSupportsStreamCapturing = true;
  2774. }
  2775. });
  2776. var _isChrome = (!!window.webkitRTCPeerConnection || !!window.webkitGetUserMedia) && !!window.chrome;
  2777. var chromeVersion = 50;
  2778. var matchArray = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);
  2779. if (_isChrome && matchArray && matchArray[2]) {
  2780. chromeVersion = parseInt(matchArray[2], 10);
  2781. }
  2782. if (_isChrome && chromeVersion < 52) {
  2783. isCanvasSupportsStreamCapturing = false;
  2784. }
  2785. if (config.useWhammyRecorder) {
  2786. isCanvasSupportsStreamCapturing = false;
  2787. }
  2788. var globalCanvas, mediaStreamRecorder;
  2789. if (isCanvasSupportsStreamCapturing) {
  2790. if (!config.disableLogs) {
  2791. console.log('Your browser supports both MediRecorder API and canvas.captureStream!');
  2792. }
  2793. if (htmlElement instanceof HTMLCanvasElement) {
  2794. globalCanvas = htmlElement;
  2795. } else if (htmlElement instanceof CanvasRenderingContext2D) {
  2796. globalCanvas = htmlElement.canvas;
  2797. } else {
  2798. throw 'Please pass either HTMLCanvasElement or CanvasRenderingContext2D.';
  2799. }
  2800. } else if (!!navigator.mozGetUserMedia) {
  2801. if (!config.disableLogs) {
  2802. console.error('Canvas recording is NOT supported in Firefox.');
  2803. }
  2804. }
  2805. var isRecording;
  2806. /**
  2807. * This method records Canvas.
  2808. * @method
  2809. * @memberof CanvasRecorder
  2810. * @example
  2811. * recorder.record();
  2812. */
  2813. this.record = function() {
  2814. isRecording = true;
  2815. if (isCanvasSupportsStreamCapturing && !config.useWhammyRecorder) {
  2816. // CanvasCaptureMediaStream
  2817. var canvasMediaStream;
  2818. if ('captureStream' in globalCanvas) {
  2819. canvasMediaStream = globalCanvas.captureStream(25); // 25 FPS
  2820. } else if ('mozCaptureStream' in globalCanvas) {
  2821. canvasMediaStream = globalCanvas.mozCaptureStream(25);
  2822. } else if ('webkitCaptureStream' in globalCanvas) {
  2823. canvasMediaStream = globalCanvas.webkitCaptureStream(25);
  2824. }
  2825. try {
  2826. var mdStream = new MediaStream();
  2827. mdStream.addTrack(getTracks(canvasMediaStream, 'video')[0]);
  2828. canvasMediaStream = mdStream;
  2829. } catch (e) {}
  2830. if (!canvasMediaStream) {
  2831. throw 'captureStream API are NOT available.';
  2832. }
  2833. // Note: Jan 18, 2016 status is that,
  2834. // Firefox MediaRecorder API can't record CanvasCaptureMediaStream object.
  2835. mediaStreamRecorder = new MediaStreamRecorder(canvasMediaStream, {
  2836. mimeType: config.mimeType || 'video/webm'
  2837. });
  2838. mediaStreamRecorder.record();
  2839. } else {
  2840. whammy.frames = [];
  2841. lastTime = new Date().getTime();
  2842. drawCanvasFrame();
  2843. }
  2844. if (config.initCallback) {
  2845. config.initCallback();
  2846. }
  2847. };
  2848. this.getWebPImages = function(callback) {
  2849. if (htmlElement.nodeName.toLowerCase() !== 'canvas') {
  2850. callback();
  2851. return;
  2852. }
  2853. var framesLength = whammy.frames.length;
  2854. whammy.frames.forEach(function(frame, idx) {
  2855. var framesRemaining = framesLength - idx;
  2856. if (!config.disableLogs) {
  2857. console.log(framesRemaining + '/' + framesLength + ' frames remaining');
  2858. }
  2859. if (config.onEncodingCallback) {
  2860. config.onEncodingCallback(framesRemaining, framesLength);
  2861. }
  2862. var webp = frame.image.toDataURL('image/webp', 1);
  2863. whammy.frames[idx].image = webp;
  2864. });
  2865. if (!config.disableLogs) {
  2866. console.log('Generating WebM');
  2867. }
  2868. callback();
  2869. };
  2870. /**
  2871. * This method stops recording Canvas.
  2872. * @param {function} callback - Callback function, that is used to pass recorded blob back to the callee.
  2873. * @method
  2874. * @memberof CanvasRecorder
  2875. * @example
  2876. * recorder.stop(function(blob) {
  2877. * video.src = URL.createObjectURL(blob);
  2878. * });
  2879. */
  2880. this.stop = function(callback) {
  2881. isRecording = false;
  2882. var that = this;
  2883. if (isCanvasSupportsStreamCapturing && mediaStreamRecorder) {
  2884. mediaStreamRecorder.stop(callback);
  2885. return;
  2886. }
  2887. this.getWebPImages(function() {
  2888. /**
  2889. * @property {Blob} blob - Recorded frames in video/webm blob.
  2890. * @memberof CanvasRecorder
  2891. * @example
  2892. * recorder.stop(function() {
  2893. * var blob = recorder.blob;
  2894. * });
  2895. */
  2896. whammy.compile(function(blob) {
  2897. if (!config.disableLogs) {
  2898. console.log('Recording finished!');
  2899. }
  2900. that.blob = blob;
  2901. if (that.blob.forEach) {
  2902. that.blob = new Blob([], {
  2903. type: 'video/webm'
  2904. });
  2905. }
  2906. if (callback) {
  2907. callback(that.blob);
  2908. }
  2909. whammy.frames = [];
  2910. });
  2911. });
  2912. };
  2913. var isPausedRecording = false;
  2914. /**
  2915. * This method pauses the recording process.
  2916. * @method
  2917. * @memberof CanvasRecorder
  2918. * @example
  2919. * recorder.pause();
  2920. */
  2921. this.pause = function() {
  2922. isPausedRecording = true;
  2923. if (mediaStreamRecorder instanceof MediaStreamRecorder) {
  2924. mediaStreamRecorder.pause();
  2925. return;
  2926. }
  2927. };
  2928. /**
  2929. * This method resumes the recording process.
  2930. * @method
  2931. * @memberof CanvasRecorder
  2932. * @example
  2933. * recorder.resume();
  2934. */
  2935. this.resume = function() {
  2936. isPausedRecording = false;
  2937. if (mediaStreamRecorder instanceof MediaStreamRecorder) {
  2938. mediaStreamRecorder.resume();
  2939. return;
  2940. }
  2941. if (!isRecording) {
  2942. this.record();
  2943. }
  2944. };
  2945. /**
  2946. * This method resets currently recorded data.
  2947. * @method
  2948. * @memberof CanvasRecorder
  2949. * @example
  2950. * recorder.clearRecordedData();
  2951. */
  2952. this.clearRecordedData = function() {
  2953. if (isRecording) {
  2954. this.stop(clearRecordedDataCB);
  2955. }
  2956. clearRecordedDataCB();
  2957. };
  2958. function clearRecordedDataCB() {
  2959. whammy.frames = [];
  2960. isRecording = false;
  2961. isPausedRecording = false;
  2962. }
  2963. // for debugging
  2964. this.name = 'CanvasRecorder';
  2965. this.toString = function() {
  2966. return this.name;
  2967. };
  2968. function cloneCanvas() {
  2969. //create a new canvas
  2970. var newCanvas = document.createElement('canvas');
  2971. var context = newCanvas.getContext('2d');
  2972. //set dimensions
  2973. newCanvas.width = htmlElement.width;
  2974. newCanvas.height = htmlElement.height;
  2975. //apply the old canvas to the new one
  2976. context.drawImage(htmlElement, 0, 0);
  2977. //return the new canvas
  2978. return newCanvas;
  2979. }
  2980. function drawCanvasFrame() {
  2981. if (isPausedRecording) {
  2982. lastTime = new Date().getTime();
  2983. return setTimeout(drawCanvasFrame, 500);
  2984. }
  2985. if (htmlElement.nodeName.toLowerCase() === 'canvas') {
  2986. var duration = new Date().getTime() - lastTime;
  2987. // via #206, by Jack i.e. @Seymourr
  2988. lastTime = new Date().getTime();
  2989. whammy.frames.push({
  2990. image: cloneCanvas(),
  2991. duration: duration
  2992. });
  2993. if (isRecording) {
  2994. setTimeout(drawCanvasFrame, config.frameInterval);
  2995. }
  2996. return;
  2997. }
  2998. html2canvas(htmlElement, {
  2999. grabMouse: typeof config.showMousePointer === 'undefined' || config.showMousePointer,
  3000. onrendered: function(canvas) {
  3001. var duration = new Date().getTime() - lastTime;
  3002. if (!duration) {
  3003. return setTimeout(drawCanvasFrame, config.frameInterval);
  3004. }
  3005. // via #206, by Jack i.e. @Seymourr
  3006. lastTime = new Date().getTime();
  3007. whammy.frames.push({
  3008. image: canvas.toDataURL('image/webp', 1),
  3009. duration: duration
  3010. });
  3011. if (isRecording) {
  3012. setTimeout(drawCanvasFrame, config.frameInterval);
  3013. }
  3014. }
  3015. });
  3016. }
  3017. var lastTime = new Date().getTime();
  3018. var whammy = new Whammy.Video(100);
  3019. }
  3020. if (typeof RecordRTC !== 'undefined') {
  3021. RecordRTC.CanvasRecorder = CanvasRecorder;
  3022. }
  3023. // _________________
  3024. // WhammyRecorder.js
  3025. /**
  3026. * WhammyRecorder is a standalone class used by {@link RecordRTC} to bring video recording in Chrome. It runs top over {@link Whammy}.
  3027. * @summary Video recording feature in Chrome.
  3028. * @license {@link https://github.com/muaz-khan/RecordRTC/blob/master/LICENSE|MIT}
  3029. * @author {@link https://MuazKhan.com|Muaz Khan}
  3030. * @typedef WhammyRecorder
  3031. * @class
  3032. * @example
  3033. * var recorder = new WhammyRecorder(mediaStream);
  3034. * recorder.record();
  3035. * recorder.stop(function(blob) {
  3036. * video.src = URL.createObjectURL(blob);
  3037. * });
  3038. * @see {@link https://github.com/muaz-khan/RecordRTC|RecordRTC Source Code}
  3039. * @param {MediaStream} mediaStream - MediaStream object fetched using getUserMedia API or generated using captureStreamUntilEnded or WebAudio API.
  3040. * @param {object} config - {disableLogs: true, initCallback: function, video: HTMLVideoElement, etc.}
  3041. */
  3042. function WhammyRecorder(mediaStream, config) {
  3043. config = config || {};
  3044. if (!config.frameInterval) {
  3045. config.frameInterval = 10;
  3046. }
  3047. if (!config.disableLogs) {
  3048. console.log('Using frames-interval:', config.frameInterval);
  3049. }
  3050. /**
  3051. * This method records video.
  3052. * @method
  3053. * @memberof WhammyRecorder
  3054. * @example
  3055. * recorder.record();
  3056. */
  3057. this.record = function() {
  3058. if (!config.width) {
  3059. config.width = 320;
  3060. }
  3061. if (!config.height) {
  3062. config.height = 240;
  3063. }
  3064. if (!config.video) {
  3065. config.video = {
  3066. width: config.width,
  3067. height: config.height
  3068. };
  3069. }
  3070. if (!config.canvas) {
  3071. config.canvas = {
  3072. width: config.width,
  3073. height: config.height
  3074. };
  3075. }
  3076. canvas.width = config.canvas.width || 320;
  3077. canvas.height = config.canvas.height || 240;
  3078. context = canvas.getContext('2d');
  3079. // setting defaults
  3080. if (config.video && config.video instanceof HTMLVideoElement) {
  3081. video = config.video.cloneNode();
  3082. if (config.initCallback) {
  3083. config.initCallback();
  3084. }
  3085. } else {
  3086. video = document.createElement('video');
  3087. setSrcObject(mediaStream, video);
  3088. video.onloadedmetadata = function() { // "onloadedmetadata" may NOT work in FF?
  3089. if (config.initCallback) {
  3090. config.initCallback();
  3091. }
  3092. };
  3093. video.width = config.video.width;
  3094. video.height = config.video.height;
  3095. }
  3096. video.muted = true;
  3097. video.play();
  3098. lastTime = new Date().getTime();
  3099. whammy = new Whammy.Video();
  3100. if (!config.disableLogs) {
  3101. console.log('canvas resolutions', canvas.width, '*', canvas.height);
  3102. console.log('video width/height', video.width || canvas.width, '*', video.height || canvas.height);
  3103. }
  3104. drawFrames(config.frameInterval);
  3105. };
  3106. /**
  3107. * Draw and push frames to Whammy
  3108. * @param {integer} frameInterval - set minimum interval (in milliseconds) between each time we push a frame to Whammy
  3109. */
  3110. function drawFrames(frameInterval) {
  3111. frameInterval = typeof frameInterval !== 'undefined' ? frameInterval : 10;
  3112. var duration = new Date().getTime() - lastTime;
  3113. if (!duration) {
  3114. return setTimeout(drawFrames, frameInterval, frameInterval);
  3115. }
  3116. if (isPausedRecording) {
  3117. lastTime = new Date().getTime();
  3118. return setTimeout(drawFrames, 100);
  3119. }
  3120. // via #206, by Jack i.e. @Seymourr
  3121. lastTime = new Date().getTime();
  3122. if (video.paused) {
  3123. // via: https://github.com/muaz-khan/WebRTC-Experiment/pull/316
  3124. // Tweak for Android Chrome
  3125. video.play();
  3126. }
  3127. context.drawImage(video, 0, 0, canvas.width, canvas.height);
  3128. whammy.frames.push({
  3129. duration: duration,
  3130. image: canvas.toDataURL('image/webp')
  3131. });
  3132. if (!isStopDrawing) {
  3133. setTimeout(drawFrames, frameInterval, frameInterval);
  3134. }
  3135. }
  3136. function asyncLoop(o) {
  3137. var i = -1,
  3138. length = o.length;
  3139. (function loop() {
  3140. i++;
  3141. if (i === length) {
  3142. o.callback();
  3143. return;
  3144. }
  3145. // "setTimeout" added by Jim McLeod
  3146. setTimeout(function() {
  3147. o.functionToLoop(loop, i);
  3148. }, 1);
  3149. })();
  3150. }
  3151. /**
  3152. * remove black frames from the beginning to the specified frame
  3153. * @param {Array} _frames - array of frames to be checked
  3154. * @param {number} _framesToCheck - number of frame until check will be executed (-1 - will drop all frames until frame not matched will be found)
  3155. * @param {number} _pixTolerance - 0 - very strict (only black pixel color) ; 1 - all
  3156. * @param {number} _frameTolerance - 0 - very strict (only black frame color) ; 1 - all
  3157. * @returns {Array} - array of frames
  3158. */
  3159. // pull#293 by @volodalexey
  3160. function dropBlackFrames(_frames, _framesToCheck, _pixTolerance, _frameTolerance, callback) {
  3161. var localCanvas = document.createElement('canvas');
  3162. localCanvas.width = canvas.width;
  3163. localCanvas.height = canvas.height;
  3164. var context2d = localCanvas.getContext('2d');
  3165. var resultFrames = [];
  3166. var checkUntilNotBlack = _framesToCheck === -1;
  3167. var endCheckFrame = (_framesToCheck && _framesToCheck > 0 && _framesToCheck <= _frames.length) ?
  3168. _framesToCheck : _frames.length;
  3169. var sampleColor = {
  3170. r: 0,
  3171. g: 0,
  3172. b: 0
  3173. };
  3174. var maxColorDifference = Math.sqrt(
  3175. Math.pow(255, 2) +
  3176. Math.pow(255, 2) +
  3177. Math.pow(255, 2)
  3178. );
  3179. var pixTolerance = _pixTolerance && _pixTolerance >= 0 && _pixTolerance <= 1 ? _pixTolerance : 0;
  3180. var frameTolerance = _frameTolerance && _frameTolerance >= 0 && _frameTolerance <= 1 ? _frameTolerance : 0;
  3181. var doNotCheckNext = false;
  3182. asyncLoop({
  3183. length: endCheckFrame,
  3184. functionToLoop: function(loop, f) {
  3185. var matchPixCount, endPixCheck, maxPixCount;
  3186. var finishImage = function() {
  3187. if (!doNotCheckNext && maxPixCount - matchPixCount <= maxPixCount * frameTolerance) {
  3188. // console.log('removed black frame : ' + f + ' ; frame duration ' + _frames[f].duration);
  3189. } else {
  3190. // console.log('frame is passed : ' + f);
  3191. if (checkUntilNotBlack) {
  3192. doNotCheckNext = true;
  3193. }
  3194. resultFrames.push(_frames[f]);
  3195. }
  3196. loop();
  3197. };
  3198. if (!doNotCheckNext) {
  3199. var image = new Image();
  3200. image.onload = function() {
  3201. context2d.drawImage(image, 0, 0, canvas.width, canvas.height);
  3202. var imageData = context2d.getImageData(0, 0, canvas.width, canvas.height);
  3203. matchPixCount = 0;
  3204. endPixCheck = imageData.data.length;
  3205. maxPixCount = imageData.data.length / 4;
  3206. for (var pix = 0; pix < endPixCheck; pix += 4) {
  3207. var currentColor = {
  3208. r: imageData.data[pix],
  3209. g: imageData.data[pix + 1],
  3210. b: imageData.data[pix + 2]
  3211. };
  3212. var colorDifference = Math.sqrt(
  3213. Math.pow(currentColor.r - sampleColor.r, 2) +
  3214. Math.pow(currentColor.g - sampleColor.g, 2) +
  3215. Math.pow(currentColor.b - sampleColor.b, 2)
  3216. );
  3217. // difference in color it is difference in color vectors (r1,g1,b1) <=> (r2,g2,b2)
  3218. if (colorDifference <= maxColorDifference * pixTolerance) {
  3219. matchPixCount++;
  3220. }
  3221. }
  3222. finishImage();
  3223. };
  3224. image.src = _frames[f].image;
  3225. } else {
  3226. finishImage();
  3227. }
  3228. },
  3229. callback: function() {
  3230. resultFrames = resultFrames.concat(_frames.slice(endCheckFrame));
  3231. if (resultFrames.length <= 0) {
  3232. // at least one last frame should be available for next manipulation
  3233. // if total duration of all frames will be < 1000 than ffmpeg doesn't work well...
  3234. resultFrames.push(_frames[_frames.length - 1]);
  3235. }
  3236. callback(resultFrames);
  3237. }
  3238. });
  3239. }
  3240. var isStopDrawing = false;
  3241. /**
  3242. * This method stops recording video.
  3243. * @param {function} callback - Callback function, that is used to pass recorded blob back to the callee.
  3244. * @method
  3245. * @memberof WhammyRecorder
  3246. * @example
  3247. * recorder.stop(function(blob) {
  3248. * video.src = URL.createObjectURL(blob);
  3249. * });
  3250. */
  3251. this.stop = function(callback) {
  3252. callback = callback || function() {};
  3253. isStopDrawing = true;
  3254. var _this = this;
  3255. // analyse of all frames takes some time!
  3256. setTimeout(function() {
  3257. // e.g. dropBlackFrames(frames, 10, 1, 1) - will cut all 10 frames
  3258. // e.g. dropBlackFrames(frames, 10, 0.5, 0.5) - will analyse 10 frames
  3259. // e.g. dropBlackFrames(frames, 10) === dropBlackFrames(frames, 10, 0, 0) - will analyse 10 frames with strict black color
  3260. dropBlackFrames(whammy.frames, -1, null, null, function(frames) {
  3261. whammy.frames = frames;
  3262. // to display advertisement images!
  3263. if (config.advertisement && config.advertisement.length) {
  3264. whammy.frames = config.advertisement.concat(whammy.frames);
  3265. }
  3266. /**
  3267. * @property {Blob} blob - Recorded frames in video/webm blob.
  3268. * @memberof WhammyRecorder
  3269. * @example
  3270. * recorder.stop(function() {
  3271. * var blob = recorder.blob;
  3272. * });
  3273. */
  3274. whammy.compile(function(blob) {
  3275. _this.blob = blob;
  3276. if (_this.blob.forEach) {
  3277. _this.blob = new Blob([], {
  3278. type: 'video/webm'
  3279. });
  3280. }
  3281. if (callback) {
  3282. callback(_this.blob);
  3283. }
  3284. });
  3285. });
  3286. }, 10);
  3287. };
  3288. var isPausedRecording = false;
  3289. /**
  3290. * This method pauses the recording process.
  3291. * @method
  3292. * @memberof WhammyRecorder
  3293. * @example
  3294. * recorder.pause();
  3295. */
  3296. this.pause = function() {
  3297. isPausedRecording = true;
  3298. };
  3299. /**
  3300. * This method resumes the recording process.
  3301. * @method
  3302. * @memberof WhammyRecorder
  3303. * @example
  3304. * recorder.resume();
  3305. */
  3306. this.resume = function() {
  3307. isPausedRecording = false;
  3308. if (isStopDrawing) {
  3309. this.record();
  3310. }
  3311. };
  3312. /**
  3313. * This method resets currently recorded data.
  3314. * @method
  3315. * @memberof WhammyRecorder
  3316. * @example
  3317. * recorder.clearRecordedData();
  3318. */
  3319. this.clearRecordedData = function() {
  3320. if (!isStopDrawing) {
  3321. this.stop(clearRecordedDataCB);
  3322. }
  3323. clearRecordedDataCB();
  3324. };
  3325. function clearRecordedDataCB() {
  3326. whammy.frames = [];
  3327. isStopDrawing = true;
  3328. isPausedRecording = false;
  3329. }
  3330. // for debugging
  3331. this.name = 'WhammyRecorder';
  3332. this.toString = function() {
  3333. return this.name;
  3334. };
  3335. var canvas = document.createElement('canvas');
  3336. var context = canvas.getContext('2d');
  3337. var video;
  3338. var lastTime;
  3339. var whammy;
  3340. }
  3341. if (typeof RecordRTC !== 'undefined') {
  3342. RecordRTC.WhammyRecorder = WhammyRecorder;
  3343. }
  3344. // https://github.com/antimatter15/whammy/blob/master/LICENSE
  3345. // _________
  3346. // Whammy.js
  3347. // todo: Firefox now supports webp for webm containers!
  3348. // their MediaRecorder implementation works well!
  3349. // should we provide an option to record via Whammy.js or MediaRecorder API is a better solution?
  3350. /**
  3351. * Whammy is a standalone class used by {@link RecordRTC} to bring video recording in Chrome. It is written by {@link https://github.com/antimatter15|antimatter15}
  3352. * @summary A real time javascript webm encoder based on a canvas hack.
  3353. * @license {@link https://github.com/muaz-khan/RecordRTC/blob/master/LICENSE|MIT}
  3354. * @author {@link https://MuazKhan.com|Muaz Khan}
  3355. * @typedef Whammy
  3356. * @class
  3357. * @example
  3358. * var recorder = new Whammy().Video(15);
  3359. * recorder.add(context || canvas || dataURL);
  3360. * var output = recorder.compile();
  3361. * @see {@link https://github.com/muaz-khan/RecordRTC|RecordRTC Source Code}
  3362. */
  3363. var Whammy = (function() {
  3364. // a more abstract-ish API
  3365. function WhammyVideo(duration) {
  3366. this.frames = [];
  3367. this.duration = duration || 1;
  3368. this.quality = 0.8;
  3369. }
  3370. /**
  3371. * Pass Canvas or Context or image/webp(string) to {@link Whammy} encoder.
  3372. * @method
  3373. * @memberof Whammy
  3374. * @example
  3375. * recorder = new Whammy().Video(0.8, 100);
  3376. * recorder.add(canvas || context || 'image/webp');
  3377. * @param {string} frame - Canvas || Context || image/webp
  3378. * @param {number} duration - Stick a duration (in milliseconds)
  3379. */
  3380. WhammyVideo.prototype.add = function(frame, duration) {
  3381. if ('canvas' in frame) { //CanvasRenderingContext2D
  3382. frame = frame.canvas;
  3383. }
  3384. if ('toDataURL' in frame) {
  3385. frame = frame.toDataURL('image/webp', this.quality);
  3386. }
  3387. if (!(/^data:image\/webp;base64,/ig).test(frame)) {
  3388. throw 'Input must be formatted properly as a base64 encoded DataURI of type image/webp';
  3389. }
  3390. this.frames.push({
  3391. image: frame,
  3392. duration: duration || this.duration
  3393. });
  3394. };
  3395. function processInWebWorker(_function) {
  3396. var blob = URL.createObjectURL(new Blob([_function.toString(),
  3397. 'this.onmessage = function (eee) {' + _function.name + '(eee.data);}'
  3398. ], {
  3399. type: 'application/javascript'
  3400. }));
  3401. var worker = new Worker(blob);
  3402. URL.revokeObjectURL(blob);
  3403. return worker;
  3404. }
  3405. function whammyInWebWorker(frames) {
  3406. function ArrayToWebM(frames) {
  3407. var info = checkFrames(frames);
  3408. if (!info) {
  3409. return [];
  3410. }
  3411. var clusterMaxDuration = 30000;
  3412. var EBML = [{
  3413. 'id': 0x1a45dfa3, // EBML
  3414. 'data': [{
  3415. 'data': 1,
  3416. 'id': 0x4286 // EBMLVersion
  3417. }, {
  3418. 'data': 1,
  3419. 'id': 0x42f7 // EBMLReadVersion
  3420. }, {
  3421. 'data': 4,
  3422. 'id': 0x42f2 // EBMLMaxIDLength
  3423. }, {
  3424. 'data': 8,
  3425. 'id': 0x42f3 // EBMLMaxSizeLength
  3426. }, {
  3427. 'data': 'webm',
  3428. 'id': 0x4282 // DocType
  3429. }, {
  3430. 'data': 2,
  3431. 'id': 0x4287 // DocTypeVersion
  3432. }, {
  3433. 'data': 2,
  3434. 'id': 0x4285 // DocTypeReadVersion
  3435. }]
  3436. }, {
  3437. 'id': 0x18538067, // Segment
  3438. 'data': [{
  3439. 'id': 0x1549a966, // Info
  3440. 'data': [{
  3441. 'data': 1e6, //do things in millisecs (num of nanosecs for duration scale)
  3442. 'id': 0x2ad7b1 // TimecodeScale
  3443. }, {
  3444. 'data': 'whammy',
  3445. 'id': 0x4d80 // MuxingApp
  3446. }, {
  3447. 'data': 'whammy',
  3448. 'id': 0x5741 // WritingApp
  3449. }, {
  3450. 'data': doubleToString(info.duration),
  3451. 'id': 0x4489 // Duration
  3452. }]
  3453. }, {
  3454. 'id': 0x1654ae6b, // Tracks
  3455. 'data': [{
  3456. 'id': 0xae, // TrackEntry
  3457. 'data': [{
  3458. 'data': 1,
  3459. 'id': 0xd7 // TrackNumber
  3460. }, {
  3461. 'data': 1,
  3462. 'id': 0x73c5 // TrackUID
  3463. }, {
  3464. 'data': 0,
  3465. 'id': 0x9c // FlagLacing
  3466. }, {
  3467. 'data': 'und',
  3468. 'id': 0x22b59c // Language
  3469. }, {
  3470. 'data': 'V_VP8',
  3471. 'id': 0x86 // CodecID
  3472. }, {
  3473. 'data': 'VP8',
  3474. 'id': 0x258688 // CodecName
  3475. }, {
  3476. 'data': 1,
  3477. 'id': 0x83 // TrackType
  3478. }, {
  3479. 'id': 0xe0, // Video
  3480. 'data': [{
  3481. 'data': info.width,
  3482. 'id': 0xb0 // PixelWidth
  3483. }, {
  3484. 'data': info.height,
  3485. 'id': 0xba // PixelHeight
  3486. }]
  3487. }]
  3488. }]
  3489. }]
  3490. }];
  3491. //Generate clusters (max duration)
  3492. var frameNumber = 0;
  3493. var clusterTimecode = 0;
  3494. while (frameNumber < frames.length) {
  3495. var clusterFrames = [];
  3496. var clusterDuration = 0;
  3497. do {
  3498. clusterFrames.push(frames[frameNumber]);
  3499. clusterDuration += frames[frameNumber].duration;
  3500. frameNumber++;
  3501. } while (frameNumber < frames.length && clusterDuration < clusterMaxDuration);
  3502. var clusterCounter = 0;
  3503. var cluster = {
  3504. 'id': 0x1f43b675, // Cluster
  3505. 'data': getClusterData(clusterTimecode, clusterCounter, clusterFrames)
  3506. }; //Add cluster to segment
  3507. EBML[1].data.push(cluster);
  3508. clusterTimecode += clusterDuration;
  3509. }
  3510. return generateEBML(EBML);
  3511. }
  3512. function getClusterData(clusterTimecode, clusterCounter, clusterFrames) {
  3513. return [{
  3514. 'data': clusterTimecode,
  3515. 'id': 0xe7 // Timecode
  3516. }].concat(clusterFrames.map(function(webp) {
  3517. var block = makeSimpleBlock({
  3518. discardable: 0,
  3519. frame: webp.data.slice(4),
  3520. invisible: 0,
  3521. keyframe: 1,
  3522. lacing: 0,
  3523. trackNum: 1,
  3524. timecode: Math.round(clusterCounter)
  3525. });
  3526. clusterCounter += webp.duration;
  3527. return {
  3528. data: block,
  3529. id: 0xa3
  3530. };
  3531. }));
  3532. }
  3533. // sums the lengths of all the frames and gets the duration
  3534. function checkFrames(frames) {
  3535. if (!frames[0]) {
  3536. postMessage({
  3537. error: 'Something went wrong. Maybe WebP format is not supported in the current browser.'
  3538. });
  3539. return;
  3540. }
  3541. var width = frames[0].width,
  3542. height = frames[0].height,
  3543. duration = frames[0].duration;
  3544. for (var i = 1; i < frames.length; i++) {
  3545. duration += frames[i].duration;
  3546. }
  3547. return {
  3548. duration: duration,
  3549. width: width,
  3550. height: height
  3551. };
  3552. }
  3553. function numToBuffer(num) {
  3554. var parts = [];
  3555. while (num > 0) {
  3556. parts.push(num & 0xff);
  3557. num = num >> 8;
  3558. }
  3559. return new Uint8Array(parts.reverse());
  3560. }
  3561. function strToBuffer(str) {
  3562. return new Uint8Array(str.split('').map(function(e) {
  3563. return e.charCodeAt(0);
  3564. }));
  3565. }
  3566. function bitsToBuffer(bits) {
  3567. var data = [];
  3568. var pad = (bits.length % 8) ? (new Array(1 + 8 - (bits.length % 8))).join('0') : '';
  3569. bits = pad + bits;
  3570. for (var i = 0; i < bits.length; i += 8) {
  3571. data.push(parseInt(bits.substr(i, 8), 2));
  3572. }
  3573. return new Uint8Array(data);
  3574. }
  3575. function generateEBML(json) {
  3576. var ebml = [];
  3577. for (var i = 0; i < json.length; i++) {
  3578. var data = json[i].data;
  3579. if (typeof data === 'object') {
  3580. data = generateEBML(data);
  3581. }
  3582. if (typeof data === 'number') {
  3583. data = bitsToBuffer(data.toString(2));
  3584. }
  3585. if (typeof data === 'string') {
  3586. data = strToBuffer(data);
  3587. }
  3588. var len = data.size || data.byteLength || data.length;
  3589. var zeroes = Math.ceil(Math.ceil(Math.log(len) / Math.log(2)) / 8);
  3590. var sizeToString = len.toString(2);
  3591. var padded = (new Array((zeroes * 7 + 7 + 1) - sizeToString.length)).join('0') + sizeToString;
  3592. var size = (new Array(zeroes)).join('0') + '1' + padded;
  3593. ebml.push(numToBuffer(json[i].id));
  3594. ebml.push(bitsToBuffer(size));
  3595. ebml.push(data);
  3596. }
  3597. return new Blob(ebml, {
  3598. type: 'video/webm'
  3599. });
  3600. }
  3601. function toBinStrOld(bits) {
  3602. var data = '';
  3603. var pad = (bits.length % 8) ? (new Array(1 + 8 - (bits.length % 8))).join('0') : '';
  3604. bits = pad + bits;
  3605. for (var i = 0; i < bits.length; i += 8) {
  3606. data += String.fromCharCode(parseInt(bits.substr(i, 8), 2));
  3607. }
  3608. return data;
  3609. }
  3610. function makeSimpleBlock(data) {
  3611. var flags = 0;
  3612. if (data.keyframe) {
  3613. flags |= 128;
  3614. }
  3615. if (data.invisible) {
  3616. flags |= 8;
  3617. }
  3618. if (data.lacing) {
  3619. flags |= (data.lacing << 1);
  3620. }
  3621. if (data.discardable) {
  3622. flags |= 1;
  3623. }
  3624. if (data.trackNum > 127) {
  3625. throw 'TrackNumber > 127 not supported';
  3626. }
  3627. var out = [data.trackNum | 0x80, data.timecode >> 8, data.timecode & 0xff, flags].map(function(e) {
  3628. return String.fromCharCode(e);
  3629. }).join('') + data.frame;
  3630. return out;
  3631. }
  3632. function parseWebP(riff) {
  3633. var VP8 = riff.RIFF[0].WEBP[0];
  3634. var frameStart = VP8.indexOf('\x9d\x01\x2a'); // A VP8 keyframe starts with the 0x9d012a header
  3635. for (var i = 0, c = []; i < 4; i++) {
  3636. c[i] = VP8.charCodeAt(frameStart + 3 + i);
  3637. }
  3638. var width, height, tmp;
  3639. //the code below is literally copied verbatim from the bitstream spec
  3640. tmp = (c[1] << 8) | c[0];
  3641. width = tmp & 0x3FFF;
  3642. tmp = (c[3] << 8) | c[2];
  3643. height = tmp & 0x3FFF;
  3644. return {
  3645. width: width,
  3646. height: height,
  3647. data: VP8,
  3648. riff: riff
  3649. };
  3650. }
  3651. function getStrLength(string, offset) {
  3652. return parseInt(string.substr(offset + 4, 4).split('').map(function(i) {
  3653. var unpadded = i.charCodeAt(0).toString(2);
  3654. return (new Array(8 - unpadded.length + 1)).join('0') + unpadded;
  3655. }).join(''), 2);
  3656. }
  3657. function parseRIFF(string) {
  3658. var offset = 0;
  3659. var chunks = {};
  3660. while (offset < string.length) {
  3661. var id = string.substr(offset, 4);
  3662. var len = getStrLength(string, offset);
  3663. var data = string.substr(offset + 4 + 4, len);
  3664. offset += 4 + 4 + len;
  3665. chunks[id] = chunks[id] || [];
  3666. if (id === 'RIFF' || id === 'LIST') {
  3667. chunks[id].push(parseRIFF(data));
  3668. } else {
  3669. chunks[id].push(data);
  3670. }
  3671. }
  3672. return chunks;
  3673. }
  3674. function doubleToString(num) {
  3675. return [].slice.call(
  3676. new Uint8Array((new Float64Array([num])).buffer), 0).map(function(e) {
  3677. return String.fromCharCode(e);
  3678. }).reverse().join('');
  3679. }
  3680. var webm = new ArrayToWebM(frames.map(function(frame) {
  3681. var webp = parseWebP(parseRIFF(atob(frame.image.slice(23))));
  3682. webp.duration = frame.duration;
  3683. return webp;
  3684. }));
  3685. postMessage(webm);
  3686. }
  3687. /**
  3688. * Encodes frames in WebM container. It uses WebWorkinvoke to invoke 'ArrayToWebM' method.
  3689. * @param {function} callback - Callback function, that is used to pass recorded blob back to the callee.
  3690. * @method
  3691. * @memberof Whammy
  3692. * @example
  3693. * recorder = new Whammy().Video(0.8, 100);
  3694. * recorder.compile(function(blob) {
  3695. * // blob.size - blob.type
  3696. * });
  3697. */
  3698. WhammyVideo.prototype.compile = function(callback) {
  3699. var webWorker = processInWebWorker(whammyInWebWorker);
  3700. webWorker.onmessage = function(event) {
  3701. if (event.data.error) {
  3702. console.error(event.data.error);
  3703. return;
  3704. }
  3705. callback(event.data);
  3706. };
  3707. webWorker.postMessage(this.frames);
  3708. };
  3709. return {
  3710. /**
  3711. * A more abstract-ish API.
  3712. * @method
  3713. * @memberof Whammy
  3714. * @example
  3715. * recorder = new Whammy().Video(0.8, 100);
  3716. * @param {?number} speed - 0.8
  3717. * @param {?number} quality - 100
  3718. */
  3719. Video: WhammyVideo
  3720. };
  3721. })();
  3722. if (typeof RecordRTC !== 'undefined') {
  3723. RecordRTC.Whammy = Whammy;
  3724. }
  3725. // ______________ (indexed-db)
  3726. // DiskStorage.js
  3727. /**
  3728. * DiskStorage is a standalone object used by {@link RecordRTC} to store recorded blobs in IndexedDB storage.
  3729. * @summary Writing blobs into IndexedDB.
  3730. * @license {@link https://github.com/muaz-khan/RecordRTC/blob/master/LICENSE|MIT}
  3731. * @author {@link https://MuazKhan.com|Muaz Khan}
  3732. * @example
  3733. * DiskStorage.Store({
  3734. * audioBlob: yourAudioBlob,
  3735. * videoBlob: yourVideoBlob,
  3736. * gifBlob : yourGifBlob
  3737. * });
  3738. * DiskStorage.Fetch(function(dataURL, type) {
  3739. * if(type === 'audioBlob') { }
  3740. * if(type === 'videoBlob') { }
  3741. * if(type === 'gifBlob') { }
  3742. * });
  3743. * // DiskStorage.dataStoreName = 'recordRTC';
  3744. * // DiskStorage.onError = function(error) { };
  3745. * @property {function} init - This method must be called once to initialize IndexedDB ObjectStore. Though, it is auto-used internally.
  3746. * @property {function} Fetch - This method fetches stored blobs from IndexedDB.
  3747. * @property {function} Store - This method stores blobs in IndexedDB.
  3748. * @property {function} onError - This function is invoked for any known/unknown error.
  3749. * @property {string} dataStoreName - Name of the ObjectStore created in IndexedDB storage.
  3750. * @see {@link https://github.com/muaz-khan/RecordRTC|RecordRTC Source Code}
  3751. */
  3752. var DiskStorage = {
  3753. /**
  3754. * This method must be called once to initialize IndexedDB ObjectStore. Though, it is auto-used internally.
  3755. * @method
  3756. * @memberof DiskStorage
  3757. * @internal
  3758. * @example
  3759. * DiskStorage.init();
  3760. */
  3761. init: function() {
  3762. var self = this;
  3763. if (typeof indexedDB === 'undefined' || typeof indexedDB.open === 'undefined') {
  3764. console.error('IndexedDB API are not available in this browser.');
  3765. return;
  3766. }
  3767. var dbVersion = 1;
  3768. var dbName = this.dbName || location.href.replace(/\/|:|#|%|\.|\[|\]/g, ''),
  3769. db;
  3770. var request = indexedDB.open(dbName, dbVersion);
  3771. function createObjectStore(dataBase) {
  3772. dataBase.createObjectStore(self.dataStoreName);
  3773. }
  3774. function putInDB() {
  3775. var transaction = db.transaction([self.dataStoreName], 'readwrite');
  3776. if (self.videoBlob) {
  3777. transaction.objectStore(self.dataStoreName).put(self.videoBlob, 'videoBlob');
  3778. }
  3779. if (self.gifBlob) {
  3780. transaction.objectStore(self.dataStoreName).put(self.gifBlob, 'gifBlob');
  3781. }
  3782. if (self.audioBlob) {
  3783. transaction.objectStore(self.dataStoreName).put(self.audioBlob, 'audioBlob');
  3784. }
  3785. function getFromStore(portionName) {
  3786. transaction.objectStore(self.dataStoreName).get(portionName).onsuccess = function(event) {
  3787. if (self.callback) {
  3788. self.callback(event.target.result, portionName);
  3789. }
  3790. };
  3791. }
  3792. getFromStore('audioBlob');
  3793. getFromStore('videoBlob');
  3794. getFromStore('gifBlob');
  3795. }
  3796. request.onerror = self.onError;
  3797. request.onsuccess = function() {
  3798. db = request.result;
  3799. db.onerror = self.onError;
  3800. if (db.setVersion) {
  3801. if (db.version !== dbVersion) {
  3802. var setVersion = db.setVersion(dbVersion);
  3803. setVersion.onsuccess = function() {
  3804. createObjectStore(db);
  3805. putInDB();
  3806. };
  3807. } else {
  3808. putInDB();
  3809. }
  3810. } else {
  3811. putInDB();
  3812. }
  3813. };
  3814. request.onupgradeneeded = function(event) {
  3815. createObjectStore(event.target.result);
  3816. };
  3817. },
  3818. /**
  3819. * This method fetches stored blobs from IndexedDB.
  3820. * @method
  3821. * @memberof DiskStorage
  3822. * @internal
  3823. * @example
  3824. * DiskStorage.Fetch(function(dataURL, type) {
  3825. * if(type === 'audioBlob') { }
  3826. * if(type === 'videoBlob') { }
  3827. * if(type === 'gifBlob') { }
  3828. * });
  3829. */
  3830. Fetch: function(callback) {
  3831. this.callback = callback;
  3832. this.init();
  3833. return this;
  3834. },
  3835. /**
  3836. * This method stores blobs in IndexedDB.
  3837. * @method
  3838. * @memberof DiskStorage
  3839. * @internal
  3840. * @example
  3841. * DiskStorage.Store({
  3842. * audioBlob: yourAudioBlob,
  3843. * videoBlob: yourVideoBlob,
  3844. * gifBlob : yourGifBlob
  3845. * });
  3846. */
  3847. Store: function(config) {
  3848. this.audioBlob = config.audioBlob;
  3849. this.videoBlob = config.videoBlob;
  3850. this.gifBlob = config.gifBlob;
  3851. this.init();
  3852. return this;
  3853. },
  3854. /**
  3855. * This function is invoked for any known/unknown error.
  3856. * @method
  3857. * @memberof DiskStorage
  3858. * @internal
  3859. * @example
  3860. * DiskStorage.onError = function(error){
  3861. * alerot( JSON.stringify(error) );
  3862. * };
  3863. */
  3864. onError: function(error) {
  3865. console.error(JSON.stringify(error, null, '\t'));
  3866. },
  3867. /**
  3868. * @property {string} dataStoreName - Name of the ObjectStore created in IndexedDB storage.
  3869. * @memberof DiskStorage
  3870. * @internal
  3871. * @example
  3872. * DiskStorage.dataStoreName = 'recordRTC';
  3873. */
  3874. dataStoreName: 'recordRTC',
  3875. dbName: null
  3876. };
  3877. if (typeof RecordRTC !== 'undefined') {
  3878. RecordRTC.DiskStorage = DiskStorage;
  3879. }
  3880. // ______________
  3881. // GifRecorder.js
  3882. /**
  3883. * GifRecorder is standalone calss used by {@link RecordRTC} to record video or canvas into animated gif.
  3884. * @license {@link https://github.com/muaz-khan/RecordRTC/blob/master/LICENSE|MIT}
  3885. * @author {@link https://MuazKhan.com|Muaz Khan}
  3886. * @typedef GifRecorder
  3887. * @class
  3888. * @example
  3889. * var recorder = new GifRecorder(mediaStream || canvas || context, { onGifPreview: function, onGifRecordingStarted: function, width: 1280, height: 720, frameRate: 200, quality: 10 });
  3890. * recorder.record();
  3891. * recorder.stop(function(blob) {
  3892. * img.src = URL.createObjectURL(blob);
  3893. * });
  3894. * @see {@link https://github.com/muaz-khan/RecordRTC|RecordRTC Source Code}
  3895. * @param {MediaStream} mediaStream - MediaStream object or HTMLCanvasElement or CanvasRenderingContext2D.
  3896. * @param {object} config - {disableLogs:true, initCallback: function, width: 320, height: 240, frameRate: 200, quality: 10}
  3897. */
  3898. function GifRecorder(mediaStream, config) {
  3899. if (typeof GIFEncoder === 'undefined') {
  3900. var script = document.createElement('script');
  3901. script.src = 'https://www.webrtc-experiment.com/gif-recorder.js';
  3902. (document.body || document.documentElement).appendChild(script);
  3903. }
  3904. config = config || {};
  3905. var isHTMLObject = mediaStream instanceof CanvasRenderingContext2D || mediaStream instanceof HTMLCanvasElement;
  3906. /**
  3907. * This method records MediaStream.
  3908. * @method
  3909. * @memberof GifRecorder
  3910. * @example
  3911. * recorder.record();
  3912. */
  3913. this.record = function() {
  3914. if (typeof GIFEncoder === 'undefined') {
  3915. setTimeout(self.record, 1000);
  3916. return;
  3917. }
  3918. if (!isLoadedMetaData) {
  3919. setTimeout(self.record, 1000);
  3920. return;
  3921. }
  3922. if (!isHTMLObject) {
  3923. if (!config.width) {
  3924. config.width = video.offsetWidth || 320;
  3925. }
  3926. if (!config.height) {
  3927. config.height = video.offsetHeight || 240;
  3928. }
  3929. if (!config.video) {
  3930. config.video = {
  3931. width: config.width,
  3932. height: config.height
  3933. };
  3934. }
  3935. if (!config.canvas) {
  3936. config.canvas = {
  3937. width: config.width,
  3938. height: config.height
  3939. };
  3940. }
  3941. canvas.width = config.canvas.width || 320;
  3942. canvas.height = config.canvas.height || 240;
  3943. video.width = config.video.width || 320;
  3944. video.height = config.video.height || 240;
  3945. }
  3946. // external library to record as GIF images
  3947. gifEncoder = new GIFEncoder();
  3948. // void setRepeat(int iter)
  3949. // Sets the number of times the set of GIF frames should be played.
  3950. // Default is 1; 0 means play indefinitely.
  3951. gifEncoder.setRepeat(0);
  3952. // void setFrameRate(Number fps)
  3953. // Sets frame rate in frames per second.
  3954. // Equivalent to setDelay(1000/fps).
  3955. // Using "setDelay" instead of "setFrameRate"
  3956. gifEncoder.setDelay(config.frameRate || 200);
  3957. // void setQuality(int quality)
  3958. // Sets quality of color quantization (conversion of images to the
  3959. // maximum 256 colors allowed by the GIF specification).
  3960. // Lower values (minimum = 1) produce better colors,
  3961. // but slow processing significantly. 10 is the default,
  3962. // and produces good color mapping at reasonable speeds.
  3963. // Values greater than 20 do not yield significant improvements in speed.
  3964. gifEncoder.setQuality(config.quality || 10);
  3965. // Boolean start()
  3966. // This writes the GIF Header and returns false if it fails.
  3967. gifEncoder.start();
  3968. if (typeof config.onGifRecordingStarted === 'function') {
  3969. config.onGifRecordingStarted();
  3970. }
  3971. startTime = Date.now();
  3972. function drawVideoFrame(time) {
  3973. if (self.clearedRecordedData === true) {
  3974. return;
  3975. }
  3976. if (isPausedRecording) {
  3977. return setTimeout(function() {
  3978. drawVideoFrame(time);
  3979. }, 100);
  3980. }
  3981. lastAnimationFrame = requestAnimationFrame(drawVideoFrame);
  3982. if (typeof lastFrameTime === undefined) {
  3983. lastFrameTime = time;
  3984. }
  3985. // ~10 fps
  3986. if (time - lastFrameTime < 90) {
  3987. return;
  3988. }
  3989. if (!isHTMLObject && video.paused) {
  3990. // via: https://github.com/muaz-khan/WebRTC-Experiment/pull/316
  3991. // Tweak for Android Chrome
  3992. video.play();
  3993. }
  3994. if (!isHTMLObject) {
  3995. context.drawImage(video, 0, 0, canvas.width, canvas.height);
  3996. }
  3997. if (config.onGifPreview) {
  3998. config.onGifPreview(canvas.toDataURL('image/png'));
  3999. }
  4000. gifEncoder.addFrame(context);
  4001. lastFrameTime = time;
  4002. }
  4003. lastAnimationFrame = requestAnimationFrame(drawVideoFrame);
  4004. if (config.initCallback) {
  4005. config.initCallback();
  4006. }
  4007. };
  4008. /**
  4009. * This method stops recording MediaStream.
  4010. * @param {function} callback - Callback function, that is used to pass recorded blob back to the callee.
  4011. * @method
  4012. * @memberof GifRecorder
  4013. * @example
  4014. * recorder.stop(function(blob) {
  4015. * img.src = URL.createObjectURL(blob);
  4016. * });
  4017. */
  4018. this.stop = function(callback) {
  4019. callback = callback || function() {};
  4020. if (lastAnimationFrame) {
  4021. cancelAnimationFrame(lastAnimationFrame);
  4022. }
  4023. endTime = Date.now();
  4024. /**
  4025. * @property {Blob} blob - The recorded blob object.
  4026. * @memberof GifRecorder
  4027. * @example
  4028. * recorder.stop(function(){
  4029. * var blob = recorder.blob;
  4030. * });
  4031. */
  4032. this.blob = new Blob([new Uint8Array(gifEncoder.stream().bin)], {
  4033. type: 'image/gif'
  4034. });
  4035. callback(this.blob);
  4036. // bug: find a way to clear old recorded blobs
  4037. gifEncoder.stream().bin = [];
  4038. };
  4039. var isPausedRecording = false;
  4040. /**
  4041. * This method pauses the recording process.
  4042. * @method
  4043. * @memberof GifRecorder
  4044. * @example
  4045. * recorder.pause();
  4046. */
  4047. this.pause = function() {
  4048. isPausedRecording = true;
  4049. };
  4050. /**
  4051. * This method resumes the recording process.
  4052. * @method
  4053. * @memberof GifRecorder
  4054. * @example
  4055. * recorder.resume();
  4056. */
  4057. this.resume = function() {
  4058. isPausedRecording = false;
  4059. };
  4060. /**
  4061. * This method resets currently recorded data.
  4062. * @method
  4063. * @memberof GifRecorder
  4064. * @example
  4065. * recorder.clearRecordedData();
  4066. */
  4067. this.clearRecordedData = function() {
  4068. self.clearedRecordedData = true;
  4069. clearRecordedDataCB();
  4070. };
  4071. function clearRecordedDataCB() {
  4072. if (gifEncoder) {
  4073. gifEncoder.stream().bin = [];
  4074. }
  4075. }
  4076. // for debugging
  4077. this.name = 'GifRecorder';
  4078. this.toString = function() {
  4079. return this.name;
  4080. };
  4081. var canvas = document.createElement('canvas');
  4082. var context = canvas.getContext('2d');
  4083. if (isHTMLObject) {
  4084. if (mediaStream instanceof CanvasRenderingContext2D) {
  4085. context = mediaStream;
  4086. canvas = context.canvas;
  4087. } else if (mediaStream instanceof HTMLCanvasElement) {
  4088. context = mediaStream.getContext('2d');
  4089. canvas = mediaStream;
  4090. }
  4091. }
  4092. var isLoadedMetaData = true;
  4093. if (!isHTMLObject) {
  4094. var video = document.createElement('video');
  4095. video.muted = true;
  4096. video.autoplay = true;
  4097. video.playsInline = true;
  4098. isLoadedMetaData = false;
  4099. video.onloadedmetadata = function() {
  4100. isLoadedMetaData = true;
  4101. };
  4102. setSrcObject(mediaStream, video);
  4103. video.play();
  4104. }
  4105. var lastAnimationFrame = null;
  4106. var startTime, endTime, lastFrameTime;
  4107. var gifEncoder;
  4108. var self = this;
  4109. }
  4110. if (typeof RecordRTC !== 'undefined') {
  4111. RecordRTC.GifRecorder = GifRecorder;
  4112. }
  4113. // Last time updated: 2019-06-21 4:09:42 AM UTC
  4114. // ________________________
  4115. // MultiStreamsMixer v1.2.2
  4116. // Open-Sourced: https://github.com/muaz-khan/MultiStreamsMixer
  4117. // --------------------------------------------------
  4118. // Muaz Khan - www.MuazKhan.com
  4119. // MIT License - www.WebRTC-Experiment.com/licence
  4120. // --------------------------------------------------
  4121. function MultiStreamsMixer(arrayOfMediaStreams, elementClass) {
  4122. var browserFakeUserAgent = 'Fake/5.0 (FakeOS) AppleWebKit/123 (KHTML, like Gecko) Fake/12.3.4567.89 Fake/123.45';
  4123. (function(that) {
  4124. if (typeof RecordRTC !== 'undefined') {
  4125. return;
  4126. }
  4127. if (!that) {
  4128. return;
  4129. }
  4130. if (typeof window !== 'undefined') {
  4131. return;
  4132. }
  4133. if (typeof global === 'undefined') {
  4134. return;
  4135. }
  4136. global.navigator = {
  4137. userAgent: browserFakeUserAgent,
  4138. getUserMedia: function() {}
  4139. };
  4140. if (!global.console) {
  4141. global.console = {};
  4142. }
  4143. if (typeof global.console.log === 'undefined' || typeof global.console.error === 'undefined') {
  4144. global.console.error = global.console.log = global.console.log || function() {
  4145. console.log(arguments);
  4146. };
  4147. }
  4148. if (typeof document === 'undefined') {
  4149. /*global document:true */
  4150. that.document = {
  4151. documentElement: {
  4152. appendChild: function() {
  4153. return '';
  4154. }
  4155. }
  4156. };
  4157. document.createElement = document.captureStream = document.mozCaptureStream = function() {
  4158. var obj = {
  4159. getContext: function() {
  4160. return obj;
  4161. },
  4162. play: function() {},
  4163. pause: function() {},
  4164. drawImage: function() {},
  4165. toDataURL: function() {
  4166. return '';
  4167. },
  4168. style: {}
  4169. };
  4170. return obj;
  4171. };
  4172. that.HTMLVideoElement = function() {};
  4173. }
  4174. if (typeof location === 'undefined') {
  4175. /*global location:true */
  4176. that.location = {
  4177. protocol: 'file:',
  4178. href: '',
  4179. hash: ''
  4180. };
  4181. }
  4182. if (typeof screen === 'undefined') {
  4183. /*global screen:true */
  4184. that.screen = {
  4185. width: 0,
  4186. height: 0
  4187. };
  4188. }
  4189. if (typeof URL === 'undefined') {
  4190. /*global screen:true */
  4191. that.URL = {
  4192. createObjectURL: function() {
  4193. return '';
  4194. },
  4195. revokeObjectURL: function() {
  4196. return '';
  4197. }
  4198. };
  4199. }
  4200. /*global window:true */
  4201. that.window = global;
  4202. })(typeof global !== 'undefined' ? global : null);
  4203. // requires: chrome://flags/#enable-experimental-web-platform-features
  4204. elementClass = elementClass || 'multi-streams-mixer';
  4205. var videos = [];
  4206. var isStopDrawingFrames = false;
  4207. var canvas = document.createElement('canvas');
  4208. var context = canvas.getContext('2d');
  4209. canvas.style.opacity = 0;
  4210. canvas.style.position = 'absolute';
  4211. canvas.style.zIndex = -1;
  4212. canvas.style.top = '-1000em';
  4213. canvas.style.left = '-1000em';
  4214. canvas.className = elementClass;
  4215. (document.body || document.documentElement).appendChild(canvas);
  4216. this.disableLogs = false;
  4217. this.frameInterval = 10;
  4218. this.width = 360;
  4219. this.height = 240;
  4220. // use gain node to prevent echo
  4221. this.useGainNode = true;
  4222. var self = this;
  4223. // _____________________________
  4224. // Cross-Browser-Declarations.js
  4225. // WebAudio API representer
  4226. var AudioContext = window.AudioContext;
  4227. if (typeof AudioContext === 'undefined') {
  4228. if (typeof webkitAudioContext !== 'undefined') {
  4229. /*global AudioContext:true */
  4230. AudioContext = webkitAudioContext;
  4231. }
  4232. if (typeof mozAudioContext !== 'undefined') {
  4233. /*global AudioContext:true */
  4234. AudioContext = mozAudioContext;
  4235. }
  4236. }
  4237. /*jshint -W079 */
  4238. var URL = window.URL;
  4239. if (typeof URL === 'undefined' && typeof webkitURL !== 'undefined') {
  4240. /*global URL:true */
  4241. URL = webkitURL;
  4242. }
  4243. if (typeof navigator !== 'undefined' && typeof navigator.getUserMedia === 'undefined') { // maybe window.navigator?
  4244. if (typeof navigator.webkitGetUserMedia !== 'undefined') {
  4245. navigator.getUserMedia = navigator.webkitGetUserMedia;
  4246. }
  4247. if (typeof navigator.mozGetUserMedia !== 'undefined') {
  4248. navigator.getUserMedia = navigator.mozGetUserMedia;
  4249. }
  4250. }
  4251. var MediaStream = window.MediaStream;
  4252. if (typeof MediaStream === 'undefined' && typeof webkitMediaStream !== 'undefined') {
  4253. MediaStream = webkitMediaStream;
  4254. }
  4255. /*global MediaStream:true */
  4256. if (typeof MediaStream !== 'undefined') {
  4257. // override "stop" method for all browsers
  4258. if (typeof MediaStream.prototype.stop === 'undefined') {
  4259. MediaStream.prototype.stop = function() {
  4260. this.getTracks().forEach(function(track) {
  4261. track.stop();
  4262. });
  4263. };
  4264. }
  4265. }
  4266. var Storage = {};
  4267. if (typeof AudioContext !== 'undefined') {
  4268. Storage.AudioContext = AudioContext;
  4269. } else if (typeof webkitAudioContext !== 'undefined') {
  4270. Storage.AudioContext = webkitAudioContext;
  4271. }
  4272. function setSrcObject(stream, element) {
  4273. if ('srcObject' in element) {
  4274. element.srcObject = stream;
  4275. } else if ('mozSrcObject' in element) {
  4276. element.mozSrcObject = stream;
  4277. } else {
  4278. element.srcObject = stream;
  4279. }
  4280. }
  4281. this.startDrawingFrames = function() {
  4282. drawVideosToCanvas();
  4283. };
  4284. function drawVideosToCanvas() {
  4285. if (isStopDrawingFrames) {
  4286. return;
  4287. }
  4288. var videosLength = videos.length;
  4289. var fullcanvas = false;
  4290. var remaining = [];
  4291. videos.forEach(function(video) {
  4292. if (!video.stream) {
  4293. video.stream = {};
  4294. }
  4295. if (video.stream.fullcanvas) {
  4296. fullcanvas = video;
  4297. } else {
  4298. // todo: video.stream.active or video.stream.live to fix blank frames issues?
  4299. remaining.push(video);
  4300. }
  4301. });
  4302. if (fullcanvas) {
  4303. canvas.width = fullcanvas.stream.width;
  4304. canvas.height = fullcanvas.stream.height;
  4305. } else if (remaining.length) {
  4306. canvas.width = videosLength > 1 ? remaining[0].width * 2 : remaining[0].width;
  4307. var height = 1;
  4308. if (videosLength === 3 || videosLength === 4) {
  4309. height = 2;
  4310. }
  4311. if (videosLength === 5 || videosLength === 6) {
  4312. height = 3;
  4313. }
  4314. if (videosLength === 7 || videosLength === 8) {
  4315. height = 4;
  4316. }
  4317. if (videosLength === 9 || videosLength === 10) {
  4318. height = 5;
  4319. }
  4320. canvas.height = remaining[0].height * height;
  4321. } else {
  4322. canvas.width = self.width || 360;
  4323. canvas.height = self.height || 240;
  4324. }
  4325. if (fullcanvas && fullcanvas instanceof HTMLVideoElement) {
  4326. drawImage(fullcanvas);
  4327. }
  4328. remaining.forEach(function(video, idx) {
  4329. drawImage(video, idx);
  4330. });
  4331. setTimeout(drawVideosToCanvas, self.frameInterval);
  4332. }
  4333. function drawImage(video, idx) {
  4334. if (isStopDrawingFrames) {
  4335. return;
  4336. }
  4337. var x = 0;
  4338. var y = 0;
  4339. var width = video.width;
  4340. var height = video.height;
  4341. if (idx === 1) {
  4342. x = video.width;
  4343. }
  4344. if (idx === 2) {
  4345. y = video.height;
  4346. }
  4347. if (idx === 3) {
  4348. x = video.width;
  4349. y = video.height;
  4350. }
  4351. if (idx === 4) {
  4352. y = video.height * 2;
  4353. }
  4354. if (idx === 5) {
  4355. x = video.width;
  4356. y = video.height * 2;
  4357. }
  4358. if (idx === 6) {
  4359. y = video.height * 3;
  4360. }
  4361. if (idx === 7) {
  4362. x = video.width;
  4363. y = video.height * 3;
  4364. }
  4365. if (typeof video.stream.left !== 'undefined') {
  4366. x = video.stream.left;
  4367. }
  4368. if (typeof video.stream.top !== 'undefined') {
  4369. y = video.stream.top;
  4370. }
  4371. if (typeof video.stream.width !== 'undefined') {
  4372. width = video.stream.width;
  4373. }
  4374. if (typeof video.stream.height !== 'undefined') {
  4375. height = video.stream.height;
  4376. }
  4377. context.drawImage(video, x, y, width, height);
  4378. if (typeof video.stream.onRender === 'function') {
  4379. video.stream.onRender(context, x, y, width, height, idx);
  4380. }
  4381. }
  4382. function getMixedStream() {
  4383. isStopDrawingFrames = false;
  4384. var mixedVideoStream = getMixedVideoStream();
  4385. var mixedAudioStream = getMixedAudioStream();
  4386. if (mixedAudioStream) {
  4387. mixedAudioStream.getTracks().filter(function(t) {
  4388. return t.kind === 'audio';
  4389. }).forEach(function(track) {
  4390. mixedVideoStream.addTrack(track);
  4391. });
  4392. }
  4393. var fullcanvas;
  4394. arrayOfMediaStreams.forEach(function(stream) {
  4395. if (stream.fullcanvas) {
  4396. fullcanvas = true;
  4397. }
  4398. });
  4399. // mixedVideoStream.prototype.appendStreams = appendStreams;
  4400. // mixedVideoStream.prototype.resetVideoStreams = resetVideoStreams;
  4401. // mixedVideoStream.prototype.clearRecordedData = clearRecordedData;
  4402. return mixedVideoStream;
  4403. }
  4404. function getMixedVideoStream() {
  4405. resetVideoStreams();
  4406. var capturedStream;
  4407. if ('captureStream' in canvas) {
  4408. capturedStream = canvas.captureStream();
  4409. } else if ('mozCaptureStream' in canvas) {
  4410. capturedStream = canvas.mozCaptureStream();
  4411. } else if (!self.disableLogs) {
  4412. console.error('Upgrade to latest Chrome or otherwise enable this flag: chrome://flags/#enable-experimental-web-platform-features');
  4413. }
  4414. var videoStream = new MediaStream();
  4415. capturedStream.getTracks().filter(function(t) {
  4416. return t.kind === 'video';
  4417. }).forEach(function(track) {
  4418. videoStream.addTrack(track);
  4419. });
  4420. canvas.stream = videoStream;
  4421. return videoStream;
  4422. }
  4423. function getMixedAudioStream() {
  4424. // via: @pehrsons
  4425. if (!Storage.AudioContextConstructor) {
  4426. Storage.AudioContextConstructor = new Storage.AudioContext();
  4427. }
  4428. self.audioContext = Storage.AudioContextConstructor;
  4429. self.audioSources = [];
  4430. if (self.useGainNode === true) {
  4431. self.gainNode = self.audioContext.createGain();
  4432. self.gainNode.connect(self.audioContext.destination);
  4433. self.gainNode.gain.value = 0; // don't hear self
  4434. }
  4435. var audioTracksLength = 0;
  4436. arrayOfMediaStreams.forEach(function(stream) {
  4437. if (!stream.getTracks().filter(function(t) {
  4438. return t.kind === 'audio';
  4439. }).length) {
  4440. return;
  4441. }
  4442. audioTracksLength++;
  4443. var audioSource = self.audioContext.createMediaStreamSource(stream);
  4444. if (self.useGainNode === true) {
  4445. audioSource.connect(self.gainNode);
  4446. }
  4447. self.audioSources.push(audioSource);
  4448. });
  4449. if (!audioTracksLength) {
  4450. // because "self.audioContext" is not initialized
  4451. // that's why we've to ignore rest of the code
  4452. return;
  4453. }
  4454. self.audioDestination = self.audioContext.createMediaStreamDestination();
  4455. self.audioSources.forEach(function(audioSource) {
  4456. audioSource.connect(self.audioDestination);
  4457. });
  4458. return self.audioDestination.stream;
  4459. }
  4460. function getVideo(stream) {
  4461. var video = document.createElement('video');
  4462. setSrcObject(stream, video);
  4463. video.className = elementClass;
  4464. video.muted = true;
  4465. video.volume = 0;
  4466. video.width = stream.width || self.width || 360;
  4467. video.height = stream.height || self.height || 240;
  4468. video.play();
  4469. return video;
  4470. }
  4471. this.appendStreams = function(streams) {
  4472. if (!streams) {
  4473. throw 'First parameter is required.';
  4474. }
  4475. if (!(streams instanceof Array)) {
  4476. streams = [streams];
  4477. }
  4478. streams.forEach(function(stream) {
  4479. var newStream = new MediaStream();
  4480. if (stream.getTracks().filter(function(t) {
  4481. return t.kind === 'video';
  4482. }).length) {
  4483. var video = getVideo(stream);
  4484. video.stream = stream;
  4485. videos.push(video);
  4486. newStream.addTrack(stream.getTracks().filter(function(t) {
  4487. return t.kind === 'video';
  4488. })[0]);
  4489. }
  4490. if (stream.getTracks().filter(function(t) {
  4491. return t.kind === 'audio';
  4492. }).length) {
  4493. var audioSource = self.audioContext.createMediaStreamSource(stream);
  4494. self.audioDestination = self.audioContext.createMediaStreamDestination();
  4495. audioSource.connect(self.audioDestination);
  4496. newStream.addTrack(self.audioDestination.stream.getTracks().filter(function(t) {
  4497. return t.kind === 'audio';
  4498. })[0]);
  4499. }
  4500. arrayOfMediaStreams.push(newStream);
  4501. });
  4502. };
  4503. this.releaseStreams = function() {
  4504. videos = [];
  4505. isStopDrawingFrames = true;
  4506. if (self.gainNode) {
  4507. self.gainNode.disconnect();
  4508. self.gainNode = null;
  4509. }
  4510. if (self.audioSources.length) {
  4511. self.audioSources.forEach(function(source) {
  4512. source.disconnect();
  4513. });
  4514. self.audioSources = [];
  4515. }
  4516. if (self.audioDestination) {
  4517. self.audioDestination.disconnect();
  4518. self.audioDestination = null;
  4519. }
  4520. if (self.audioContext) {
  4521. self.audioContext.close();
  4522. }
  4523. self.audioContext = null;
  4524. context.clearRect(0, 0, canvas.width, canvas.height);
  4525. if (canvas.stream) {
  4526. canvas.stream.stop();
  4527. canvas.stream = null;
  4528. }
  4529. };
  4530. this.resetVideoStreams = function(streams) {
  4531. if (streams && !(streams instanceof Array)) {
  4532. streams = [streams];
  4533. }
  4534. resetVideoStreams(streams);
  4535. };
  4536. function resetVideoStreams(streams) {
  4537. videos = [];
  4538. streams = streams || arrayOfMediaStreams;
  4539. // via: @adrian-ber
  4540. streams.forEach(function(stream) {
  4541. if (!stream.getTracks().filter(function(t) {
  4542. return t.kind === 'video';
  4543. }).length) {
  4544. return;
  4545. }
  4546. var video = getVideo(stream);
  4547. video.stream = stream;
  4548. videos.push(video);
  4549. });
  4550. }
  4551. // for debugging
  4552. this.name = 'MultiStreamsMixer';
  4553. this.toString = function() {
  4554. return this.name;
  4555. };
  4556. this.getMixedStream = getMixedStream;
  4557. }
  4558. if (typeof RecordRTC === 'undefined') {
  4559. if (typeof module !== 'undefined' /* && !!module.exports*/ ) {
  4560. module.exports = MultiStreamsMixer;
  4561. }
  4562. if (typeof define === 'function' && define.amd) {
  4563. define('MultiStreamsMixer', [], function() {
  4564. return MultiStreamsMixer;
  4565. });
  4566. }
  4567. }
  4568. // ______________________
  4569. // MultiStreamRecorder.js
  4570. /*
  4571. * Video conference recording, using captureStream API along with WebAudio and Canvas2D API.
  4572. */
  4573. /**
  4574. * MultiStreamRecorder can record multiple videos in single container.
  4575. * @summary Multi-videos recorder.
  4576. * @license {@link https://github.com/muaz-khan/RecordRTC/blob/master/LICENSE|MIT}
  4577. * @author {@link https://MuazKhan.com|Muaz Khan}
  4578. * @typedef MultiStreamRecorder
  4579. * @class
  4580. * @example
  4581. * var options = {
  4582. * mimeType: 'video/webm'
  4583. * }
  4584. * var recorder = new MultiStreamRecorder(ArrayOfMediaStreams, options);
  4585. * recorder.record();
  4586. * recorder.stop(function(blob) {
  4587. * video.src = URL.createObjectURL(blob);
  4588. *
  4589. * // or
  4590. * var blob = recorder.blob;
  4591. * });
  4592. * @see {@link https://github.com/muaz-khan/RecordRTC|RecordRTC Source Code}
  4593. * @param {MediaStreams} mediaStreams - Array of MediaStreams.
  4594. * @param {object} config - {disableLogs:true, frameInterval: 1, mimeType: "video/webm"}
  4595. */
  4596. function MultiStreamRecorder(arrayOfMediaStreams, options) {
  4597. arrayOfMediaStreams = arrayOfMediaStreams || [];
  4598. var self = this;
  4599. var mixer;
  4600. var mediaRecorder;
  4601. options = options || {
  4602. elementClass: 'multi-streams-mixer',
  4603. mimeType: 'video/webm',
  4604. video: {
  4605. width: 360,
  4606. height: 240
  4607. }
  4608. };
  4609. if (!options.frameInterval) {
  4610. options.frameInterval = 10;
  4611. }
  4612. if (!options.video) {
  4613. options.video = {};
  4614. }
  4615. if (!options.video.width) {
  4616. options.video.width = 360;
  4617. }
  4618. if (!options.video.height) {
  4619. options.video.height = 240;
  4620. }
  4621. /**
  4622. * This method records all MediaStreams.
  4623. * @method
  4624. * @memberof MultiStreamRecorder
  4625. * @example
  4626. * recorder.record();
  4627. */
  4628. this.record = function() {
  4629. // github/muaz-khan/MultiStreamsMixer
  4630. mixer = new MultiStreamsMixer(arrayOfMediaStreams, options.elementClass || 'multi-streams-mixer');
  4631. if (getAllVideoTracks().length) {
  4632. mixer.frameInterval = options.frameInterval || 10;
  4633. mixer.width = options.video.width || 360;
  4634. mixer.height = options.video.height || 240;
  4635. mixer.startDrawingFrames();
  4636. }
  4637. if (options.previewStream && typeof options.previewStream === 'function') {
  4638. options.previewStream(mixer.getMixedStream());
  4639. }
  4640. // record using MediaRecorder API
  4641. mediaRecorder = new MediaStreamRecorder(mixer.getMixedStream(), options);
  4642. mediaRecorder.record();
  4643. };
  4644. function getAllVideoTracks() {
  4645. var tracks = [];
  4646. arrayOfMediaStreams.forEach(function(stream) {
  4647. getTracks(stream, 'video').forEach(function(track) {
  4648. tracks.push(track);
  4649. });
  4650. });
  4651. return tracks;
  4652. }
  4653. /**
  4654. * This method stops recording MediaStream.
  4655. * @param {function} callback - Callback function, that is used to pass recorded blob back to the callee.
  4656. * @method
  4657. * @memberof MultiStreamRecorder
  4658. * @example
  4659. * recorder.stop(function(blob) {
  4660. * video.src = URL.createObjectURL(blob);
  4661. * });
  4662. */
  4663. this.stop = function(callback) {
  4664. if (!mediaRecorder) {
  4665. return;
  4666. }
  4667. mediaRecorder.stop(function(blob) {
  4668. self.blob = blob;
  4669. callback(blob);
  4670. self.clearRecordedData();
  4671. });
  4672. };
  4673. /**
  4674. * This method pauses the recording process.
  4675. * @method
  4676. * @memberof MultiStreamRecorder
  4677. * @example
  4678. * recorder.pause();
  4679. */
  4680. this.pause = function() {
  4681. if (mediaRecorder) {
  4682. mediaRecorder.pause();
  4683. }
  4684. };
  4685. /**
  4686. * This method resumes the recording process.
  4687. * @method
  4688. * @memberof MultiStreamRecorder
  4689. * @example
  4690. * recorder.resume();
  4691. */
  4692. this.resume = function() {
  4693. if (mediaRecorder) {
  4694. mediaRecorder.resume();
  4695. }
  4696. };
  4697. /**
  4698. * This method resets currently recorded data.
  4699. * @method
  4700. * @memberof MultiStreamRecorder
  4701. * @example
  4702. * recorder.clearRecordedData();
  4703. */
  4704. this.clearRecordedData = function() {
  4705. if (mediaRecorder) {
  4706. mediaRecorder.clearRecordedData();
  4707. mediaRecorder = null;
  4708. }
  4709. if (mixer) {
  4710. mixer.releaseStreams();
  4711. mixer = null;
  4712. }
  4713. };
  4714. /**
  4715. * Add extra media-streams to existing recordings.
  4716. * @method
  4717. * @memberof MultiStreamRecorder
  4718. * @param {MediaStreams} mediaStreams - Array of MediaStreams
  4719. * @example
  4720. * recorder.addStreams([newAudioStream, newVideoStream]);
  4721. */
  4722. this.addStreams = function(streams) {
  4723. if (!streams) {
  4724. throw 'First parameter is required.';
  4725. }
  4726. if (!(streams instanceof Array)) {
  4727. streams = [streams];
  4728. }
  4729. arrayOfMediaStreams.concat(streams);
  4730. if (!mediaRecorder || !mixer) {
  4731. return;
  4732. }
  4733. mixer.appendStreams(streams);
  4734. if (options.previewStream && typeof options.previewStream === 'function') {
  4735. options.previewStream(mixer.getMixedStream());
  4736. }
  4737. };
  4738. /**
  4739. * Reset videos during live recording. Replace old videos e.g. replace cameras with full-screen.
  4740. * @method
  4741. * @memberof MultiStreamRecorder
  4742. * @param {MediaStreams} mediaStreams - Array of MediaStreams
  4743. * @example
  4744. * recorder.resetVideoStreams([newVideo1, newVideo2]);
  4745. */
  4746. this.resetVideoStreams = function(streams) {
  4747. if (!mixer) {
  4748. return;
  4749. }
  4750. if (streams && !(streams instanceof Array)) {
  4751. streams = [streams];
  4752. }
  4753. mixer.resetVideoStreams(streams);
  4754. };
  4755. /**
  4756. * Returns MultiStreamsMixer
  4757. * @method
  4758. * @memberof MultiStreamRecorder
  4759. * @example
  4760. * let mixer = recorder.getMixer();
  4761. * mixer.appendStreams([newStream]);
  4762. */
  4763. this.getMixer = function() {
  4764. return mixer;
  4765. };
  4766. // for debugging
  4767. this.name = 'MultiStreamRecorder';
  4768. this.toString = function() {
  4769. return this.name;
  4770. };
  4771. }
  4772. if (typeof RecordRTC !== 'undefined') {
  4773. RecordRTC.MultiStreamRecorder = MultiStreamRecorder;
  4774. }
  4775. // _____________________
  4776. // RecordRTC.promises.js
  4777. /**
  4778. * RecordRTCPromisesHandler adds promises support in {@link RecordRTC}. Try a {@link https://github.com/muaz-khan/RecordRTC/blob/master/simple-demos/RecordRTCPromisesHandler.html|demo here}
  4779. * @summary Promises for {@link RecordRTC}
  4780. * @license {@link https://github.com/muaz-khan/RecordRTC/blob/master/LICENSE|MIT}
  4781. * @author {@link https://MuazKhan.com|Muaz Khan}
  4782. * @typedef RecordRTCPromisesHandler
  4783. * @class
  4784. * @example
  4785. * var recorder = new RecordRTCPromisesHandler(mediaStream, options);
  4786. * recorder.startRecording()
  4787. * .then(successCB)
  4788. * .catch(errorCB);
  4789. * // Note: You can access all RecordRTC API using "recorder.recordRTC" e.g.
  4790. * recorder.recordRTC.onStateChanged = function(state) {};
  4791. * recorder.recordRTC.setRecordingDuration(5000);
  4792. * @see {@link https://github.com/muaz-khan/RecordRTC|RecordRTC Source Code}
  4793. * @param {MediaStream} mediaStream - Single media-stream object, array of media-streams, html-canvas-element, etc.
  4794. * @param {object} config - {type:"video", recorderType: MediaStreamRecorder, disableLogs: true, numberOfAudioChannels: 1, bufferSize: 0, sampleRate: 0, video: HTMLVideoElement, etc.}
  4795. * @throws Will throw an error if "new" keyword is not used to initiate "RecordRTCPromisesHandler". Also throws error if first argument "MediaStream" is missing.
  4796. * @requires {@link RecordRTC}
  4797. */
  4798. function RecordRTCPromisesHandler(mediaStream, options) {
  4799. if (!this) {
  4800. throw 'Use "new RecordRTCPromisesHandler()"';
  4801. }
  4802. if (typeof mediaStream === 'undefined') {
  4803. throw 'First argument "MediaStream" is required.';
  4804. }
  4805. var self = this;
  4806. /**
  4807. * @property {Blob} blob - Access/reach the native {@link RecordRTC} object.
  4808. * @memberof RecordRTCPromisesHandler
  4809. * @example
  4810. * let internal = recorder.recordRTC.getInternalRecorder();
  4811. * alert(internal instanceof MediaStreamRecorder);
  4812. * recorder.recordRTC.onStateChanged = function(state) {};
  4813. */
  4814. self.recordRTC = new RecordRTC(mediaStream, options);
  4815. /**
  4816. * This method records MediaStream.
  4817. * @method
  4818. * @memberof RecordRTCPromisesHandler
  4819. * @example
  4820. * recorder.startRecording()
  4821. * .then(successCB)
  4822. * .catch(errorCB);
  4823. */
  4824. this.startRecording = function() {
  4825. return new Promise(function(resolve, reject) {
  4826. try {
  4827. self.recordRTC.startRecording();
  4828. resolve();
  4829. } catch (e) {
  4830. reject(e);
  4831. }
  4832. });
  4833. };
  4834. /**
  4835. * This method stops the recording.
  4836. * @method
  4837. * @memberof RecordRTCPromisesHandler
  4838. * @example
  4839. * recorder.stopRecording().then(function() {
  4840. * var blob = recorder.getBlob();
  4841. * }).catch(errorCB);
  4842. */
  4843. this.stopRecording = function() {
  4844. return new Promise(function(resolve, reject) {
  4845. try {
  4846. self.recordRTC.stopRecording(function(url) {
  4847. self.blob = self.recordRTC.getBlob();
  4848. if (!self.blob || !self.blob.size) {
  4849. reject('Empty blob.', self.blob);
  4850. return;
  4851. }
  4852. resolve(url);
  4853. });
  4854. } catch (e) {
  4855. reject(e);
  4856. }
  4857. });
  4858. };
  4859. /**
  4860. * This method pauses the recording. You can resume recording using "resumeRecording" method.
  4861. * @method
  4862. * @memberof RecordRTCPromisesHandler
  4863. * @example
  4864. * recorder.pauseRecording()
  4865. * .then(successCB)
  4866. * .catch(errorCB);
  4867. */
  4868. this.pauseRecording = function() {
  4869. return new Promise(function(resolve, reject) {
  4870. try {
  4871. self.recordRTC.pauseRecording();
  4872. resolve();
  4873. } catch (e) {
  4874. reject(e);
  4875. }
  4876. });
  4877. };
  4878. /**
  4879. * This method resumes the recording.
  4880. * @method
  4881. * @memberof RecordRTCPromisesHandler
  4882. * @example
  4883. * recorder.resumeRecording()
  4884. * .then(successCB)
  4885. * .catch(errorCB);
  4886. */
  4887. this.resumeRecording = function() {
  4888. return new Promise(function(resolve, reject) {
  4889. try {
  4890. self.recordRTC.resumeRecording();
  4891. resolve();
  4892. } catch (e) {
  4893. reject(e);
  4894. }
  4895. });
  4896. };
  4897. /**
  4898. * This method returns data-url for the recorded blob.
  4899. * @method
  4900. * @memberof RecordRTCPromisesHandler
  4901. * @example
  4902. * recorder.stopRecording().then(function() {
  4903. * recorder.getDataURL().then(function(dataURL) {
  4904. * window.open(dataURL);
  4905. * }).catch(errorCB);;
  4906. * }).catch(errorCB);
  4907. */
  4908. this.getDataURL = function(callback) {
  4909. return new Promise(function(resolve, reject) {
  4910. try {
  4911. self.recordRTC.getDataURL(function(dataURL) {
  4912. resolve(dataURL);
  4913. });
  4914. } catch (e) {
  4915. reject(e);
  4916. }
  4917. });
  4918. };
  4919. /**
  4920. * This method returns the recorded blob.
  4921. * @method
  4922. * @memberof RecordRTCPromisesHandler
  4923. * @example
  4924. * recorder.stopRecording().then(function() {
  4925. * recorder.getBlob().then(function(blob) {})
  4926. * }).catch(errorCB);
  4927. */
  4928. this.getBlob = function() {
  4929. return new Promise(function(resolve, reject) {
  4930. try {
  4931. resolve(self.recordRTC.getBlob());
  4932. } catch (e) {
  4933. reject(e);
  4934. }
  4935. });
  4936. };
  4937. /**
  4938. * This method returns the internal recording object.
  4939. * @method
  4940. * @memberof RecordRTCPromisesHandler
  4941. * @example
  4942. * let internalRecorder = await recorder.getInternalRecorder();
  4943. * if(internalRecorder instanceof MultiStreamRecorder) {
  4944. * internalRecorder.addStreams([newAudioStream]);
  4945. * internalRecorder.resetVideoStreams([screenStream]);
  4946. * }
  4947. * @returns {Object}
  4948. */
  4949. this.getInternalRecorder = function() {
  4950. return new Promise(function(resolve, reject) {
  4951. try {
  4952. resolve(self.recordRTC.getInternalRecorder());
  4953. } catch (e) {
  4954. reject(e);
  4955. }
  4956. });
  4957. };
  4958. /**
  4959. * This method resets the recorder. So that you can reuse single recorder instance many times.
  4960. * @method
  4961. * @memberof RecordRTCPromisesHandler
  4962. * @example
  4963. * await recorder.reset();
  4964. * recorder.startRecording(); // record again
  4965. */
  4966. this.reset = function() {
  4967. return new Promise(function(resolve, reject) {
  4968. try {
  4969. resolve(self.recordRTC.reset());
  4970. } catch (e) {
  4971. reject(e);
  4972. }
  4973. });
  4974. };
  4975. /**
  4976. * Destroy RecordRTC instance. Clear all recorders and objects.
  4977. * @method
  4978. * @memberof RecordRTCPromisesHandler
  4979. * @example
  4980. * recorder.destroy().then(successCB).catch(errorCB);
  4981. */
  4982. this.destroy = function() {
  4983. return new Promise(function(resolve, reject) {
  4984. try {
  4985. resolve(self.recordRTC.destroy());
  4986. } catch (e) {
  4987. reject(e);
  4988. }
  4989. });
  4990. };
  4991. /**
  4992. * Get recorder's readonly state.
  4993. * @method
  4994. * @memberof RecordRTCPromisesHandler
  4995. * @example
  4996. * let state = await recorder.getState();
  4997. * // or
  4998. * recorder.getState().then(state => { console.log(state); })
  4999. * @returns {String} Returns recording state.
  5000. */
  5001. this.getState = function() {
  5002. return new Promise(function(resolve, reject) {
  5003. try {
  5004. resolve(self.recordRTC.getState());
  5005. } catch (e) {
  5006. reject(e);
  5007. }
  5008. });
  5009. };
  5010. /**
  5011. * @property {Blob} blob - Recorded data as "Blob" object.
  5012. * @memberof RecordRTCPromisesHandler
  5013. * @example
  5014. * await recorder.stopRecording();
  5015. * let blob = recorder.getBlob(); // or "recorder.recordRTC.blob"
  5016. * invokeSaveAsDialog(blob);
  5017. */
  5018. this.blob = null;
  5019. /**
  5020. * RecordRTC version number
  5021. * @property {String} version - Release version number.
  5022. * @memberof RecordRTCPromisesHandler
  5023. * @static
  5024. * @readonly
  5025. * @example
  5026. * alert(recorder.version);
  5027. */
  5028. this.version = '5.6.2';
  5029. }
  5030. if (typeof RecordRTC !== 'undefined') {
  5031. RecordRTC.RecordRTCPromisesHandler = RecordRTCPromisesHandler;
  5032. }
  5033. // ______________________
  5034. // WebAssemblyRecorder.js
  5035. /**
  5036. * WebAssemblyRecorder lets you create webm videos in JavaScript via WebAssembly. The library consumes raw RGBA32 buffers (4 bytes per pixel) and turns them into a webm video with the given framerate and quality. This makes it compatible out-of-the-box with ImageData from a CANVAS. With realtime mode you can also use webm-wasm for streaming webm videos.
  5037. * @summary Video recording feature in Chrome, Firefox and maybe Edge.
  5038. * @license {@link https://github.com/muaz-khan/RecordRTC/blob/master/LICENSE|MIT}
  5039. * @author {@link https://MuazKhan.com|Muaz Khan}
  5040. * @typedef WebAssemblyRecorder
  5041. * @class
  5042. * @example
  5043. * var recorder = new WebAssemblyRecorder(mediaStream);
  5044. * recorder.record();
  5045. * recorder.stop(function(blob) {
  5046. * video.src = URL.createObjectURL(blob);
  5047. * });
  5048. * @see {@link https://github.com/muaz-khan/RecordRTC|RecordRTC Source Code}
  5049. * @param {MediaStream} mediaStream - MediaStream object fetched using getUserMedia API or generated using captureStreamUntilEnded or WebAudio API.
  5050. * @param {object} config - {webAssemblyPath:'webm-wasm.wasm',workerPath: 'webm-worker.js', frameRate: 30, width: 1920, height: 1080, bitrate: 1024, realtime: true}
  5051. */
  5052. function WebAssemblyRecorder(stream, config) {
  5053. // based on: github.com/GoogleChromeLabs/webm-wasm
  5054. if (typeof ReadableStream === 'undefined' || typeof WritableStream === 'undefined') {
  5055. // because it fixes readable/writable streams issues
  5056. console.error('Following polyfill is strongly recommended: https://unpkg.com/@mattiasbuelens/web-streams-polyfill/dist/polyfill.min.js');
  5057. }
  5058. config = config || {};
  5059. config.width = config.width || 640;
  5060. config.height = config.height || 480;
  5061. config.frameRate = config.frameRate || 30;
  5062. config.bitrate = config.bitrate || 1200;
  5063. config.realtime = config.realtime || true;
  5064. function createBufferURL(buffer, type) {
  5065. return URL.createObjectURL(new Blob([buffer], {
  5066. type: type || ''
  5067. }));
  5068. }
  5069. var finished;
  5070. function cameraStream() {
  5071. return new ReadableStream({
  5072. start: function(controller) {
  5073. var cvs = document.createElement('canvas');
  5074. var video = document.createElement('video');
  5075. var first = true;
  5076. video.srcObject = stream;
  5077. video.muted = true;
  5078. video.height = config.height;
  5079. video.width = config.width;
  5080. video.volume = 0;
  5081. video.onplaying = function() {
  5082. cvs.width = config.width;
  5083. cvs.height = config.height;
  5084. var ctx = cvs.getContext('2d');
  5085. var frameTimeout = 1000 / config.frameRate;
  5086. var cameraTimer = setInterval(function f() {
  5087. if (finished) {
  5088. clearInterval(cameraTimer);
  5089. controller.close();
  5090. }
  5091. if (first) {
  5092. first = false;
  5093. if (config.onVideoProcessStarted) {
  5094. config.onVideoProcessStarted();
  5095. }
  5096. }
  5097. ctx.drawImage(video, 0, 0);
  5098. if (controller._controlledReadableStream.state !== 'closed') {
  5099. try {
  5100. controller.enqueue(
  5101. ctx.getImageData(0, 0, config.width, config.height)
  5102. );
  5103. } catch (e) {}
  5104. }
  5105. }, frameTimeout);
  5106. };
  5107. video.play();
  5108. }
  5109. });
  5110. }
  5111. var worker;
  5112. function startRecording(stream, buffer) {
  5113. if (!config.workerPath && !buffer) {
  5114. finished = false;
  5115. // is it safe to use @latest ?
  5116. fetch(
  5117. 'https://unpkg.com/webm-wasm@latest/dist/webm-worker.js'
  5118. ).then(function(r) {
  5119. r.arrayBuffer().then(function(buffer) {
  5120. startRecording(stream, buffer);
  5121. });
  5122. });
  5123. return;
  5124. }
  5125. if (!config.workerPath && buffer instanceof ArrayBuffer) {
  5126. var blob = new Blob([buffer], {
  5127. type: 'text/javascript'
  5128. });
  5129. config.workerPath = URL.createObjectURL(blob);
  5130. }
  5131. if (!config.workerPath) {
  5132. console.error('workerPath parameter is missing.');
  5133. }
  5134. worker = new Worker(config.workerPath);
  5135. worker.postMessage(config.webAssemblyPath || 'https://unpkg.com/webm-wasm@latest/dist/webm-wasm.wasm');
  5136. worker.addEventListener('message', function(event) {
  5137. if (event.data === 'READY') {
  5138. worker.postMessage({
  5139. width: config.width,
  5140. height: config.height,
  5141. bitrate: config.bitrate || 1200,
  5142. timebaseDen: config.frameRate || 30,
  5143. realtime: config.realtime
  5144. });
  5145. cameraStream().pipeTo(new WritableStream({
  5146. write: function(image) {
  5147. if (finished) {
  5148. console.error('Got image, but recorder is finished!');
  5149. return;
  5150. }
  5151. worker.postMessage(image.data.buffer, [image.data.buffer]);
  5152. }
  5153. }));
  5154. } else if (!!event.data) {
  5155. if (!isPaused) {
  5156. arrayOfBuffers.push(event.data);
  5157. }
  5158. }
  5159. });
  5160. }
  5161. /**
  5162. * This method records video.
  5163. * @method
  5164. * @memberof WebAssemblyRecorder
  5165. * @example
  5166. * recorder.record();
  5167. */
  5168. this.record = function() {
  5169. arrayOfBuffers = [];
  5170. isPaused = false;
  5171. this.blob = null;
  5172. startRecording(stream);
  5173. if (typeof config.initCallback === 'function') {
  5174. config.initCallback();
  5175. }
  5176. };
  5177. var isPaused;
  5178. /**
  5179. * This method pauses the recording process.
  5180. * @method
  5181. * @memberof WebAssemblyRecorder
  5182. * @example
  5183. * recorder.pause();
  5184. */
  5185. this.pause = function() {
  5186. isPaused = true;
  5187. };
  5188. /**
  5189. * This method resumes the recording process.
  5190. * @method
  5191. * @memberof WebAssemblyRecorder
  5192. * @example
  5193. * recorder.resume();
  5194. */
  5195. this.resume = function() {
  5196. isPaused = false;
  5197. };
  5198. function terminate(callback) {
  5199. if (!worker) {
  5200. if (callback) {
  5201. callback();
  5202. }
  5203. return;
  5204. }
  5205. // Wait for null event data to indicate that the encoding is complete
  5206. worker.addEventListener('message', function(event) {
  5207. if (event.data === null) {
  5208. worker.terminate();
  5209. worker = null;
  5210. if (callback) {
  5211. callback();
  5212. }
  5213. }
  5214. });
  5215. worker.postMessage(null);
  5216. }
  5217. var arrayOfBuffers = [];
  5218. /**
  5219. * This method stops recording video.
  5220. * @param {function} callback - Callback function, that is used to pass recorded blob back to the callee.
  5221. * @method
  5222. * @memberof WebAssemblyRecorder
  5223. * @example
  5224. * recorder.stop(function(blob) {
  5225. * video.src = URL.createObjectURL(blob);
  5226. * });
  5227. */
  5228. this.stop = function(callback) {
  5229. finished = true;
  5230. var recorder = this;
  5231. terminate(function() {
  5232. recorder.blob = new Blob(arrayOfBuffers, {
  5233. type: 'video/webm'
  5234. });
  5235. callback(recorder.blob);
  5236. });
  5237. };
  5238. // for debugging
  5239. this.name = 'WebAssemblyRecorder';
  5240. this.toString = function() {
  5241. return this.name;
  5242. };
  5243. /**
  5244. * This method resets currently recorded data.
  5245. * @method
  5246. * @memberof WebAssemblyRecorder
  5247. * @example
  5248. * recorder.clearRecordedData();
  5249. */
  5250. this.clearRecordedData = function() {
  5251. arrayOfBuffers = [];
  5252. isPaused = false;
  5253. this.blob = null;
  5254. // todo: if recording-ON then STOP it first
  5255. };
  5256. /**
  5257. * @property {Blob} blob - The recorded blob object.
  5258. * @memberof WebAssemblyRecorder
  5259. * @example
  5260. * recorder.stop(function(){
  5261. * var blob = recorder.blob;
  5262. * });
  5263. */
  5264. this.blob = null;
  5265. }
  5266. if (typeof RecordRTC !== 'undefined') {
  5267. RecordRTC.WebAssemblyRecorder = WebAssemblyRecorder;
  5268. }