UNPKG

@freddydrodev/artyom

Version:

Artyom is a Robust Wrapper of the Google Chrome SpeechSynthesis and SpeechRecognition that allows you to create a virtual assistent

23 lines 13.4 kB
'use strict';/** * Artyom.js is a voice control, speech recognition and speech synthesis JavaScript library. * * @requires {webkitSpeechRecognition && speechSynthesis} * @license MIT * @version 1.0.6 * @copyright 2017 Our Code World (www.ourcodeworld.com) All Rights Reserved. * @author Carlos Delgado (https://github.com/sdkcarlos) and Sema García (https://github.com/semagarcia) * @see https://sdkcarlos.github.io/sites/artyom.html * @see http://docs.ourcodeworld.com/projects/artyom-js */ var y=Object.defineProperty;var h=Object.getOwnPropertySymbols;var g=Object.prototype.hasOwnProperty,A=Object.prototype.propertyIsEnumerable;var u=(l,e,t)=>e in l?y(l,e,{enumerable:true,configurable:true,writable:true,value:t}):l[e]=t,c=(l,e)=>{for(var t in e||(e={}))g.call(e,t)&&u(l,t,e[t]);if(h)for(var t of h(e))A.call(e,t)&&u(l,t,e[t]);return l};var m=(l,e,t)=>new Promise((r,o)=>{var i=a=>{try{s(t.next(a));}catch(d){o(d);}},n=a=>{try{s(t.throw(a));}catch(d){o(d);}},s=a=>a.done?r(a.value):Promise.resolve(a.value).then(i,n);s((t=t.apply(l,e)).next());});var p=class{constructor(){if(this.ArtyomCommands=[],this.ArtyomVoicesIdentifiers={"de-DE":["Google Deutsch","de-DE","de_DE"],"es-ES":["Google espa\xF1ol","es-ES","es_ES","es-MX","es_MX"],"it-IT":["Google italiano","it-IT","it_IT"],"ja-JP":["Google \u65E5\u672C\u4EBA","ja-JP","ja_JP"],"en-US":["Google US English","en-US","en_US"],"en-GB":["Google UK English Male","Google UK English Female","en-GB","en_GB"],"pt-BR":["Google portugu\xEAs do Brasil","pt-PT","pt-BR","pt_PT","pt_BR"],"pt-PT":["Google portugu\xEAs do Brasil","pt-PT","pt_PT"],"ru-RU":["Google \u0440\u0443\u0441\u0441\u043A\u0438\u0439","ru-RU","ru_RU"],"nl-NL":["Google Nederlands","nl-NL","nl_NL"],"fr-FR":["Google fran\xE7ais","fr-FR","fr_FR"],"pl-PL":["Google polski","pl-PL","pl_PL"],"id-ID":["Google Bahasa Indonesia","id-ID","id_ID"],"hi-IN":["Google \u0939\u093F\u0928\u094D\u0926\u0940","hi-IN","hi_IN"],"zh-CN":["Google \u666E\u901A\u8BDD\uFF08\u4E2D\u56FD\u5927\u9646\uFF09","zh-CN","zh_CN"],"zh-HK":["Google \u7CA4\u8A9E\uFF08\u9999\u6E2F\uFF09","zh-HK","zh_HK"],native:["native"]},"speechSynthesis"in window?window.speechSynthesis.getVoices():console.error("Artyom.js can't speak without the Speech Synthesis API."),"webkitSpeechRecognition"in window)this.artyomWebkitSpeechRecognition=new window.webkitSpeechRecognition;else throw new Error("Artyom.js can't recognize voice without the Speech Recognition API.");this.ArtyomProperties={lang:"en-GB",recognizing:false,continuous:false,speed:1,volume:1,listen:false,mode:"normal",debug:false,helpers:{redirectRecognizedTextOutput:void 0,remoteProcessorHandler:void 0,lastSay:void 0,fatalityPromiseCallback:void 0},executionKeyword:void 0,obeyKeyword:void 0,speaking:false,obeying:true,soundex:false,name:void 0},this.ArtyomGarbageCollection=[],this.ArtyomFlags={restartRecognition:false},this.ArtyomGlobalEvents={ERROR:"ERROR",SPEECH_SYNTHESIS_START:"SPEECH_SYNTHESIS_START",SPEECH_SYNTHESIS_END:"SPEECH_SYNTHESIS_END",TEXT_RECOGNIZED:"TEXT_RECOGNIZED",COMMAND_RECOGNITION_START:"COMMAND_RECOGNITION_START",COMMAND_RECOGNITION_END:"COMMAND_RECOGNITION_END",COMMAND_MATCHED:"COMMAND_MATCHED",NOT_COMMAND_MATCHED:"NOT_COMMAND_MATCHED"},this.Device={isMobile:/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),isChrome:/Chrome/.test(navigator.userAgent)},this.ArtyomVoice={default:false,lang:"en-GB",localService:false,name:"Google UK English Male",voiceURI:"Google UK English Male"},this.initializeDevice(),this.initializeSpeechRecognition();}initializeDevice(){this.Device.isChrome=/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor),this.Device.isMobile=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);}initializeSpeechRecognition(){if(!window.webkitSpeechRecognition)throw new Error("Speech Recognition API not supported in this browser");this.artyomWebkitSpeechRecognition=new window.webkitSpeechRecognition,this.setupSpeechRecognitionEvents();}setupSpeechRecognitionEvents(){this.artyomWebkitSpeechRecognition.onresult=e=>{let t=e.results[e.results.length-1],r=t[0].transcript;this.handleSpeechResult(r,t.isFinal);},this.artyomWebkitSpeechRecognition.onerror=e=>{console.error("Speech recognition error:",e.error);},this.artyomWebkitSpeechRecognition.onend=()=>{this.ArtyomProperties.continuous&&this.artyomWebkitSpeechRecognition.start();};}handleSpeechResult(e,t){this.ArtyomProperties.helpers.redirectRecognizedTextOutput&&this.ArtyomProperties.helpers.redirectRecognizedTextOutput(e,t);}addCommands(e){let t=r=>{"indexes"in r?this.ArtyomCommands.push(r):console.error("The given command doesn't provide any index to execute.");};return Array.isArray(e)?e.forEach(t):t(e),true}clearGarbageCollection(){return this.ArtyomGarbageCollection=[]}debug(e,t){if(!this.ArtyomProperties.debug)return;let r=`[v${this.getVersion()}] Artyom.js`,o={error:"background: #C12127; color: black;",info:"background: #4285F4; color: #FFFFFF",default:"background: #005454; color: #BFF8F8"};switch(t){case "error":console.log(`%c${r}:%c ${e}`,o.error,"color:black;");break;case "warn":console.warn(e);break;case "info":console.log(`%c${r}:%c ${e}`,o.info,"color:black;");break;default:console.log(`%c${r}:%c ${e}`,o.default,"color:black;");}}detectErrors(){if(window.location.protocol==="file:"){let e="Error: running Artyom directly from a file. The APIs require a different communication protocol like HTTP or HTTPS";return console.error(e),{code:"artyom_error_localfile",message:e}}if(!this.Device.isChrome){let e="Error: the Speech Recognition and Speech Synthesis APIs require the Google Chrome Browser to work.";return console.error(e),{code:"artyom_error_browser_unsupported",message:e}}return window.location.protocol!=="https:"&&console.warn(`Warning: artyom is being executed using the '${window.location.protocol}' protocol. The continuous mode requires a secure protocol (HTTPS)`),false}emptyCommands(){return this.ArtyomCommands=[]}fatality(){return m(this,null,function*(){return new Promise(e=>{this.ArtyomProperties.helpers.fatalityPromiseCallback=e;try{this.ArtyomFlags.restartRecognition=!1,this.artyomWebkitSpeechRecognition.stop();}catch(t){console.error(t);}})})}getAvailableCommands(){return this.ArtyomCommands}getVoices(){return window.speechSynthesis.getVoices()}speechSupported(){return "speechSynthesis"in window}recognizingSupported(){return "webkitSpeechRecognition"in window}shutUp(){if("speechSynthesis"in window)for(;window.speechSynthesis.pending;)window.speechSynthesis.cancel();this.ArtyomProperties.speaking=false,this.clearGarbageCollection();}getProperties(){return this.ArtyomProperties}getLanguage(){return this.ArtyomProperties.lang}getVersion(){return "1.0.6"}on(e,t){return {then:r=>{let o=c({indexes:e,action:r},t&&{smart:true});this.addCommands(o);}}}triggerEvent(e,t){let r=new CustomEvent(e,{detail:t});return document.dispatchEvent(r),r}repeatLastSay(e){let t=this.ArtyomProperties.helpers.lastSay;if(e)return t;t&&this.say(t.text);}when(e,t){document.addEventListener(e,r=>{r instanceof CustomEvent&&t(r.detail);});}remoteProcessorService(e){return this.ArtyomProperties.helpers.remoteProcessorHandler=e,true}voiceAvailable(e){return typeof this.getVoice(e)!="undefined"}isObeying(){return this.ArtyomProperties.obeying}obey(){return this.ArtyomProperties.obeying=true}dontObey(){return this.ArtyomProperties.obeying=false}isSpeaking(){return this.ArtyomProperties.speaking}isRecognizing(){return this.ArtyomProperties.recognizing}getNativeApi(){return this.artyomWebkitSpeechRecognition}getGarbageCollection(){return this.ArtyomGarbageCollection}getVoice(e){let t=this.ArtyomVoicesIdentifiers[e]||this.ArtyomVoicesIdentifiers["en-GB"];return window.speechSynthesis.getVoices().find(o=>t.some(i=>o.name===i||o.lang===i))}newDictation(e){if(!this.recognizingSupported())return console.error("SpeechRecognition is not supported in this browser"),{start:()=>{},stop:()=>{},onError:null};let t=new window.webkitSpeechRecognition;return t.continuous=true,t.interimResults=true,t.lang=this.ArtyomProperties.lang,t.onresult=r=>{var n;let{interimTranscript:o,finalTranscript:i}=Array.from(r.results).reduce((s,a)=>({interimTranscript:s.interimTranscript+(a.isFinal?"":a[0].transcript),finalTranscript:s.finalTranscript+(a.isFinal?a[0].transcript:"")}),{interimTranscript:"",finalTranscript:""});(n=e.onResult)==null||n.call(e,o,i);},{start:()=>{var i;let r=true,o=(i=e.continuous)!=null?i:false;t.onstart=()=>{var n;r&&((n=e.onStart)==null||n.call(e));},t.onend=()=>{var n;o?(r=false,t.start()):(r=true,(n=e.onEnd)==null||n.call(e));},t.start();},stop:()=>{t.stop();},onError:e.onError||null}}newPrompt(e){var o;if(typeof e!="object"){console.error("Expected the prompt configuration.");return}let t=[...this.ArtyomCommands];this.emptyCommands();let r=c({description:"Setting the artyom commands only for the prompt. The commands will be restored after the prompt finishes",indexes:e.options,action:(i,n)=>{var a;this.ArtyomCommands=t;let s=(a=e.onMatch)==null?void 0:a.call(e,i,n);if(typeof s!="function"){console.error("onMatch function expects a returning function to be executed");return}s();}},e.smart&&{smart:true});this.addCommands(r),(o=e.beforePrompt)==null||o.call(e),this.say(e.question,{onStart:()=>{var i;return (i=e.onStartPrompt)==null?void 0:i.call(e)},onEnd:()=>{var i;return (i=e.onEndPrompt)==null?void 0:i.call(e)}});}sayRandom(e){if(!Array.isArray(e))return console.error("Random quotes must be in an array!"),null;let t=Math.floor(Math.random()*e.length);return this.say(e[t]),{text:e[t],index:t}}setDebug(e){return this.ArtyomProperties.debug=e}simulateInstruction(e){var r,o;if(!e||typeof e!="string")return console.warn("Cannot execute a non string command"),false;let t=this.execute(e);return t!=null&&t.instruction?(this.debug(`Command matches with simulation, executing${t.instruction.smart?" (smart)":""}`,"info"),t.instruction.smart?t.instruction.action(t.index,(r=t.wildcard)==null?void 0:r.item,(o=t.wildcard)==null?void 0:o.full):t.instruction.action(t.index),true):(console.warn(`No command found trying with ${e}`),false)}soundex(e){let t=e.toLowerCase().split(""),r=t.shift()||"",o={a:"",e:"",i:"",o:"",u:"",b:1,f:1,p:1,v:1,c:2,g:2,j:2,k:2,q:2,s:2,x:2,z:2,d:3,t:3,l:4,m:5,n:5,r:6};return (r+t.map(n=>{var s;return (s=o[n])!=null?s:""}).filter((n,s,a)=>s===0?n!==o[r]:n!==a[s-1]).join("")+"000").slice(0,4).toUpperCase()}splitStringByChunks(e="",t=100){let r=[],o=t,i=0;for(;e[o];)e[o++]===" "&&(r.push(e.substring(i,o)),i=o,o+=t);return r.push(e.substr(i)),r}redirectRecognizedTextOutput(e){return typeof e!="function"?(console.warn("Expected function to handle the recognized text ..."),false):(this.ArtyomProperties.helpers.redirectRecognizedTextOutput=e,true)}restart(){return m(this,null,function*(){let e=c({},this.ArtyomProperties);return yield this.fatality(),this.initialize(e)})}talk(e,t,r,o){let i=new SpeechSynthesisUtterance(e);i.volume=this.ArtyomProperties.volume,i.rate=this.ArtyomProperties.speed;let n=o!=null&&o.lang?this.getVoice(o.lang):this.getVoice(this.ArtyomProperties.lang);this.Device.isMobile?n&&(i.lang=n.lang):n&&(i.voice=n),t===1&&i.addEventListener("start",()=>{var s;this.ArtyomProperties.speaking=true,this.debug(`Event reached: ${this.ArtyomGlobalEvents.SPEECH_SYNTHESIS_START}`),this.triggerEvent(this.ArtyomGlobalEvents.SPEECH_SYNTHESIS_START),(s=o==null?void 0:o.onStart)==null||s.call(o);}),t>=r&&i.addEventListener("end",()=>{var s;this.ArtyomProperties.speaking=false,this.debug(`Event reached: ${this.ArtyomGlobalEvents.SPEECH_SYNTHESIS_END}`),this.triggerEvent(this.ArtyomGlobalEvents.SPEECH_SYNTHESIS_END),(s=o==null?void 0:o.onEnd)==null||s.call(o);}),this.debug(`${t} text chunk processed successfully out of ${r}`),this.ArtyomGarbageCollection.push(i),window.speechSynthesis.speak(i);}say(e,t){if(!this.speechSupported())return;if(typeof e!="string"){console.warn(`Artyom expects a string to speak ${typeof e} given`);return}if(!e.length){console.warn("Cannot speak empty string");return}let r=115,o=[];if(e.length>r){let i=e.split(/,|:|\. |;/);o=this.flatMap(i,n=>n.length>r?this.splitStringByChunks(n,r):[n]);}else o=[e];o.forEach((i,n)=>{i&&this.talk(i,n+1,o.length,t);}),this.ArtyomProperties.helpers.lastSay={text:e,date:new Date};}execute(e){if(typeof e=="string")return this.findCommand(e);e.action&&e.action(0);}findCommand(e){let t=this.ArtyomCommands.find(r=>r.indexes.some(o=>e.toLowerCase().includes(o.toLowerCase())));if(t)return {index:0,instruction:t,wildcard:void 0}}initialize(e){Object.assign(this.ArtyomProperties,e);}setVoice(e){e&&(this.ArtyomProperties.voice=e);}flatMap(e,t){return e.reduce((r,o)=>[...r,...t(o)],[])}addEventListener(e,t){document.addEventListener(e,t);}};/** * Artyom.js is a voice control, speech recognition and speech synthesis JavaScript library. * * @requires {webkitSpeechRecognition && speechSynthesis} * @license MIT * @version 1.0.6 * @copyright 2017 Our Code World (www.ourcodeworld.com) All Rights Reserved. * @author Carlos Delgado (https://github.com/sdkcarlos) and Sema García (https://github.com/semagarcia) * @see https://sdkcarlos.github.io/sites/artyom.html * @see http://docs.ourcodeworld.com/projects/artyom-js */module.exports=p;//# sourceMappingURL=artyom.js.map //# sourceMappingURL=artyom.js.map