diff --git a/dist/talkify.js b/dist/talkify.js index 8f2ca7d..aa466ac 100644 --- a/dist/talkify.js +++ b/dist/talkify.js @@ -610,6 +610,10 @@ talkify.playbar = function (parent, correlationId) { return true; } + if (filter.byClass.indexOf("Neural") !== -1 && voice.isNeural) { + return true; + } + return false; } @@ -1214,7 +1218,7 @@ talkify.config = { active: true, host: 'https://talkify.net', apiKey: '', - speechBaseUrl: '/api/speech/v1', + speechBaseUrl: '/api/speech/v2', languageBaseUrl: '/api/language/v1' }, keyboardCommands: { diff --git a/dist/talkify.min.js b/dist/talkify.min.js index 646bbfb..9af6c89 100644 --- a/dist/talkify.min.js +++ b/dist/talkify.min.js @@ -1 +1 @@ -(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i '}},{}],3:[function(require,module,exports){talkify=talkify||{};talkify.playbar=function(parent,correlationId){var mainFlags=["de-DE","fr-FR","en-US","zh-CN","es-ES","it-IT","ja-JP","ko-KR","sv-SE","nb-NO","da-DK","ru-RU","nl-NL","pl-PL","tr-TR","is-IS","uk-UA","sk-SK","pt-PT","ro-RO","cy-GB","bg-BG","cs-CZ","el-GR","fi-FI","he-IL","hi-IN","hr-HR","hu-HU","id-ID","ms-MY","sl-SI","th-TH","vi-VN","ar-EG","ar-SA","ta-IN","te-IN","en-GB-WLS","ca-ES","gu-IN","ml-IN","bn-IN","kn-IN","fil-PH"];var settings={parentElement:parent||talkify.config.ui.audioControls.container||document.body};var playElement,pauseElement,rateElement,volumeElement,progressElement,voiceElement,currentTimeElement,textHighlightingElement,wrapper,voicePicker;var attachElement,detatchedElement,dragArea,loader,erroroccurredElement,textInteractionElement,pitchElement,wordBreakElement,wordBreakElementWrapper;var pitchElementWrapper,nextItemElement,previousItemElement,voiceNameElement;var flagElement,phonationNormalElement,phonationSoftElement,phonationWhisperElement,phonationDropDown;var voices=[];function hide(element){if(!element||element.classList.contains("talkify-hidden")){return}element.className+=" talkify-hidden"}function show(element){if(!element){return}element.className=element.className.replace("talkify-hidden","")}function play(){hide(loader);hide(playElement);hide(erroroccurredElement);show(pauseElement)}function pause(){hide(loader);hide(pauseElement);hide(erroroccurredElement);show(playElement)}function onError(){hide(loader);hide(pauseElement);hide(playElement);show(erroroccurredElement)}function addClass(element,c){if(element.classList.contains(c)){return}element.className+=" "+c}function removeClass(element,c){element.className=element.className.replace(c,"")}function createElement(type,classes){var element=document.createElement(type);element.className=classes;return element}var groupBy=function(xs,keyFn){return xs.reduce(function(rv,x){var key=keyFn(x);(rv[key]=rv[key]||[]).push(x);return rv},{})};function createVoicePicker(voices){var mainUl=createElement("ul","voice-selector");if(!voices.length){return mainUl}var byLanguage=groupBy(voices,function(v){return v.language});for(var prop in byLanguage){if(!byLanguage.hasOwnProperty(prop)){continue}var sortedVoices=byLanguage[prop].sort(function(a,b){return a.culture-b.culture});var defaultVoice=sortedVoices.filter(function(x){return x.isStandard})[0];var foo=sortedVoices.find(function(v){return mainFlags.indexOf(v.culture)!==-1});if(!foo){continue}var mainFlag="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/3.3.0/flags/4x3/"+foo.culture.split("-")[1].toLowerCase()+".svg";var li=createElement("li");var flagImg=createElement("img","talkify-flag");flagImg.src=mainFlag;var label=createElement("label","talkify-clickable");label.innerHTML=sortedVoices[0].language;label.htmlFor="chk_"+prop;var checkbox=createElement("input","");checkbox.id="chk_"+prop;checkbox.type="checkbox";checkbox.style="display: none";li.appendChild(flagImg);li.appendChild(label);li.appendChild(checkbox);var innerUl=createElement("ul","language");li.appendChild(innerUl);for(var j=0;j1){clickedValue=1}if(clickedValue<0){clickedValue=0}talkify.messageHub.publish(correlationId+".controlcenter.request.seek",clickedValue)});attachElement.addEventListener("click",function(){addClass(controlCenter,"attached");removeClass(controlCenter,"detached")});detatchedElement.addEventListener("click",function(){removeClass(controlCenter,"attached");addClass(controlCenter,"detached")});dragArea.addEventListener("mousedown",onMouseDown);document.addEventListener("mouseup",onMouseUp);function onMouseUp(e){document.removeEventListener("mousemove",onMouseMove)}function onMouseDown(e){document.addEventListener("mousemove",onMouseMove)}function onMouseMove(e){e.preventDefault();var dArea=dragArea.getBoundingClientRect();var leftOffset=dArea.width/2+dArea.x-controlCenter.getBoundingClientRect().x;controlCenter.style.top=e.clientY-controlCenter.offsetHeight/2+"px";controlCenter.style.left=e.clientX-leftOffset+"px"}}function initialize(){render();setupBindings();talkify.messageHub.subscribe("controlcenter",[correlationId+".player.*.pause",correlationId+".player.*.disposed"],pause);talkify.messageHub.subscribe("controlcenter",[correlationId+".player.*.play",correlationId+".player.*.resume"],play);talkify.messageHub.subscribe("controlcenter",correlationId+".player.*.disposed",dispose);talkify.messageHub.subscribe("controlcenter",correlationId+".player.*.loading",function(){hide(playElement);hide(pauseElement);hide(erroroccurredElement);show(loader)});talkify.messageHub.subscribe("controlcenter",correlationId+".player.*.loaded",function(){removeClass(pauseElement,"talkify-disabled");removeClass(playElement,"talkify-disabled");show(playElement);hide(loader)});talkify.messageHub.subscribe("controlcenter",correlationId+".player.*.texthighlight.enabled",function(){removeClass(textHighlightingElement,"talkify-disabled")});talkify.messageHub.subscribe("controlcenter",correlationId+".player.*.texthighlight.disabled",function(){addClass(textHighlightingElement,"talkify-disabled")});talkify.messageHub.subscribe("controlcenter",correlationId+".player.*.ratechanged",function(rate){rateElement.forEach(function(x){x.value=rate})});talkify.messageHub.subscribe("controlcenter",correlationId+".player.*.voiceset",function(voice){featureToggle(voice);setVoiceName(voice)});talkify.messageHub.subscribe("controlcenter",correlationId+".player.tts.error",onError);talkify.messageHub.subscribe("controlcenter",correlationId+".player.tts.timeupdated",updateClock);talkify.messageHub.subscribe("controlcenter",correlationId+".player.html5.timeupdated",function(value){progressElement.setAttribute("value",value)});talkify.messageHub.subscribe("controlcenter",correlationId+".playlist.loaded",function(){removeClass(playElement,"talkify-disabled")});talkify.messageHub.subscribe("controlcenter",correlationId+".playlist.textinteraction.enabled",function(){removeClass(textInteractionElement,"talkify-disabled")});talkify.messageHub.subscribe("controlcenter",correlationId+".playlist.textinteraction.disabled",function(){addClass(textInteractionElement,"talkify-disabled")});talkify.messageHub.subscribe("controlcenter",correlationId+".player.tts.wordbreakchanged",function(ms){wordBreakElement.value=ms});talkify.messageHub.subscribe("controlcenter",correlationId+".player.tts.pitchchanged",function(value){pitchElement.value=value});talkify.messageHub.subscribe("controlcenter",correlationId+".player.tts.phonationchanged",function(phonation){phonationDropDown.value=phonation==="soft"?"soft":"normal"});talkify.messageHub.subscribe("controlcenter",correlationId+".player.tts.whisperchanged",function(whisper){phonationDropDown.value=whisper?"whisper":"normal"});talkify.messageHub.subscribe("controlcenter",correlationId+".playlist.playing",function(msg){removeClass(nextItemElement,"talkify-disabled");removeClass(previousItemElement,"talkify-disabled");if(msg.isLast){addClass(nextItemElement,"talkify-disabled")}if(msg.isFirst){addClass(previousItemElement,"talkify-disabled")}});if(!talkify.config.ui.audioControls.voicepicker.enabled){return}talkify.http.get(talkify.config.remoteService.speechBaseUrl+"/voices").then(function(error,data){if(error!==false){return}voices=window.talkify.toLowerCaseKeys(data);voicePicker=createVoicePicker(filterVoicesByConfig(voices));wrapper.getElementsByClassName("talkify-voice-selector")[0].appendChild(voicePicker);voicePicker.querySelectorAll(".language > li").forEach(function(item){item.addEventListener("click",function(e){var voice=JSON.parse(e.currentTarget.dataset.voice);talkify.messageHub.publish(correlationId+".controlcenter.request.setvoice",window.talkify.toLowerCaseKeys(voice))})});if(voiceNameElement.textContent){var backendVoice=voices.find(function(v){return v.name===voiceNameElement.textContent});if(backendVoice){featureToggle(backendVoice);setVoiceName(backendVoice)}}})}function filterVoicesByConfig(voices){var filter=talkify.config.ui.audioControls.voicepicker.filter;if(!filter){return voices}return voices.filter(function(voice){var active=true;if(filter.byCulture.length){active=filter.byCulture.indexOf(voice.culture)!==-1}if(active&&filter.byLanguage.length){active=filter.byLanguage.indexOf(voice.language)!==-1}if(active&&filter.byClass.length){if(filter.byClass.indexOf("Standard")!==-1&&voice.isStandard){return true}if(filter.byClass.indexOf("Premium")!==-1&&voice.isPremium){return true}if(filter.byClass.indexOf("Exclusive")!==-1&&voice.isExclusive){return true}return false}return active})}function updateClock(timeInfo){var currentTime=timeInfo.currentTime;var duration=timeInfo.duration;progressElement.setAttribute("value",currentTime/duration);if(!currentTimeElement){return}var currentminutes=Math.floor(currentTime/60);var currentseconds=Math.round(currentTime)-currentminutes*60;var totalminutes=!!duration?Math.floor(duration/60):0;var totalseconds=!!duration?Math.round(duration)-totalminutes*60:0;currentTimeElement.textContent=currentminutes+":"+(currentseconds<10?"0"+currentseconds:currentseconds)+" / "+totalminutes+":"+(totalseconds<10?"0"+totalseconds:totalseconds)}function isTalkifyHostedVoice(voice){return voice&&voice.constructor.name!=="SpeechSynthesisVoice"}function featureToggle(voice){show(progressElement);show(textHighlightingElement);if(!voice){return}var backendVoice=voices.find(function(v){return v.name===voice.name});if(backendVoice){voice=backendVoice}voice.canUsePitch?show(pitchElementWrapper):hide(pitchElementWrapper);voice.canUseWordBreak?show(wordBreakElementWrapper):hide(wordBreakElementWrapper);voice.canWhisper?show(phonationWhisperElement):hide(phonationWhisperElement);voice.canSpeakSoftly?show(phonationSoftElement):hide(phonationSoftElement);if(voice.canSpeakSoftly){}if(isTalkifyHostedVoice(voice)){return}hide(currentTimeElement);if(!voice.localService){hide(progressElement);hide(textHighlightingElement)}}function setVoiceName(voice){if(!voice){voiceNameElement.textContent="Automatic voice detection";return}var backendVoice=voices.find(function(v){return v.name===voice.name});if(backendVoice){voice=backendVoice}var split=(voice.culture||"").split("-");if(split.length>1){flagElement.src="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/3.3.0/flags/4x3/"+split[1].toLowerCase()+".svg";show(flagElement)}else{hide(flagElement)}if(isTalkifyHostedVoice(voice)){voiceNameElement.textContent=voice.name;return}voiceNameElement.textContent=voice.name}function dispose(){var existingControl=document.getElementsByClassName("talkify-control-center")[0];if(existingControl){existingControl.parentNode.removeChild(existingControl)}talkify.messageHub.unsubscribe("controlcenter",[correlationId+".player.*.pause",correlationId+".player.*.disposed"]);talkify.messageHub.unsubscribe("controlcenter",[correlationId+".player.*.play",correlationId+".player.*.resume"]);talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.*.disposed");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.*.loaded");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.*.loading");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.*.texthighlight.enabled");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.*.texthighlight.disabled");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.*.ratechanged");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.*.voiceset");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.tts.timeupdated");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.html5.timeupdated");talkify.messageHub.unsubscribe("controlcenter",correlationId+".playlist.loaded");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.tts.error");talkify.messageHub.unsubscribe("controlcenter",correlationId+".playlist.textinteraction.enabled");talkify.messageHub.unsubscribe("controlcenter",correlationId+".playlist.textinteraction.disabled");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.tts.wordbreakchanged");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.tts.pitchchanged");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.tts.phonationchanged");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.tts.whisperchanged");talkify.messageHub.unsubscribe("controlcenter",correlationId+".playlist.playing")}initialize();return{setMaxRate:function(value){rateElement.forEach(function(x){x.setAttribute("max",value)});return this},setMinRate:function(value){rateElement.forEach(function(x){x.setAttribute("min",value)});return this},dispose:dispose}}},{}],4:[function(require,module,exports){talkify=talkify||{};talkify.controlcenters=talkify.controlcenters||{};talkify.controlcenters.local=function(){this.html='
T
'}},{}],5:[function(require,module,exports){talkify=talkify||{};talkify.controlcenters=talkify.controlcenters||{};talkify.controlcenters.modern=function(parent,correlationId){this.html='
    • Text highlighting
    • Text interaction
    • Dock player
'}},{}],6:[function(require,module,exports){(function(exports){function Promise(){this._callbacks=[]}Promise.prototype.then=function(func,context){var p;if(this._isdone){p=func.apply(context,this.result)}else{p=new Promise;this._callbacks.push(function(){var res=func.apply(context,arguments);if(res&&typeof res.then==="function")res.then(p.done,p)})}return p};Promise.prototype.done=function(){this.result=arguments;this._isdone=true;for(var i=0;i=300)&&xhr.status!==304;p.done(err,xhr.responseText,xhr)}};xhr.send(payload);return p}function _ajaxer(method){return function(url,data,headers){return ajax(method,url,data,headers)}}var promise={Promise:Promise,join:join,chain:chain,ajax:ajax,get:_ajaxer("GET"),post:_ajaxer("POST"),put:_ajaxer("PUT"),del:_ajaxer("DELETE"),ENOXHR:1,ETIMEOUT:2,ajaxTimeout:0};if(typeof define==="function"&&define.amd){define(function(){return promise})}else{exports.promise=promise}})(this)},{}],7:[function(require,module,exports){talkify=talkify||{};talkify.http=function ajax(){var get=function(url){var call=new promise.promise.Promise;var keypart=(url.indexOf("?")!==-1?"&key=":"?key=")+talkify.config.remoteService.apiKey;promise.promise.get(window.talkify.config.remoteService.host+url+keypart).then(function(error,data){try{var jsonObj=JSON.parse(data);call.done(error,jsonObj)}catch(e){call.done(e,data)}});return call};return{get:get}}()},{}],8:[function(require,module,exports){talkify=talkify||{};talkify.config={debug:false,useSsml:false,maximumTextLength:5e3,ui:{audioControls:{enabled:true,controlcenter:"native",container:document.body,voicepicker:{enabled:true,filter:{byClass:[],byCulture:[],byLanguage:[]}}}},formReader:{voice:null,rate:0,remoteService:true,requiredText:"This field is required",valueText:"You have entered {value} as: {label}.",selectedText:"You have selected {label}.",notSelectedText:"{label} is not selected."},remoteService:{active:true,host:"https://talkify.net",apiKey:"",speechBaseUrl:"/api/speech/v1",languageBaseUrl:"/api/language/v1"},keyboardCommands:{enabled:false,commands:{playPause:32,next:39,previous:37}},voiceCommands:{enabled:false,keyboardActivation:{enabled:true,key:77},commands:{playPause:["play","pause","stop","start"],next:["play next","next"],previous:["play previous","previous","back","go back"]}}}},{}],9:[function(require,module,exports){talkify=talkify||{};talkify.formReader=function(){var player;var timeout;function setupForm(formElement){var elements=formElement.elements;for(var i=0;i-1?70:language.indexOf("ko-")>-1?130:200;var chuncks=[];var sentences=text.split(/(\?|\.|。)+/g);var currentChunck="";sentences.forEach(function(sentence){if(sentence===""||sentence==="."||sentence==="。"||sentence==="?"){if(currentChunck){currentChunck+=sentence}return}if(currentChunck&¤tChunck.length+sentence.length>chunckSize){chuncks.push(currentChunck);currentChunck=""}if(sentence.length>chunckSize){var words=extractWords(sentence,language);words.forEach(function(word){if(currentChunck.length+word.length>chunckSize){chuncks.push(currentChunck);currentChunck=""}currentChunck+=word.trim()+" "});if(currentChunck.trim()){chuncks.push(currentChunck.trim()+".");currentChunck=""}return}currentChunck+=sentence});chuncks.push(currentChunck);return chuncks}function extractWords(text,language){var wordRegex=new RegExp(/[&\$\-|]|([("\-&])*(\b[^\s]+[.:,"-)!&?]*)/g);if(language){if(language.indexOf("zh-")>-1){return text.split(",")}if(language.indexOf("ko-")>-1){return text.split(".")}}var words=[];var m;while((m=wordRegex.exec(text))!==null){if(m.index===wordRegex.lastIndex){wordRegex.lastIndex++}words.push(m[0])}return words}function selectVoiceToPlay(voices){var matchingVoices=[];var voice=null;var language=me.settings.lockedLanguage||me.settings.referenceLanguage.Culture;for(var i=0;i-1}).forEach(function(subscriberKey){subscribers[subscriberKey]=subscribers[subscriberKey].filter(function(subscriber){return subscriber.key!==key})})}return{publish:publish,subscribe:subscribe,unsubscribe:unsubscribe}}()},{}],13:[function(require,module,exports){talkify=talkify||{};talkify.BasePlayer=function(_audiosource,_playbar){this.correlationId=talkify.generateGuid();this.audioSource=_audiosource;this.wordHighlighter=new talkify.wordHighlighter(this.correlationId);var me=this;this.settings={useTextHighlight:false,referenceLanguage:{Culture:"",Language:-1},lockedLanguage:null,rate:1,useControls:false};this.playbar=_playbar;this.forcedVoice=null;if(talkify.config.ui.audioControls.enabled&&talkify.config.ui.audioControls.controlcenter!=="native"){this.playbar.instance=talkify.playbar(null,this.correlationId)}talkify.messageHub.subscribe("core-player",this.correlationId+".player.*.loaded",function(item){item.isLoading=false});talkify.messageHub.subscribe("core-player",this.correlationId+".player.*.ended",function(item){item.isPlaying=false});talkify.messageHub.subscribe("core-player",this.correlationId+".controlcenter.texthighlightoggled",function(enabled){me.settings.useTextHighlight=enabled});talkify.messageHub.subscribe("core-player",this.correlationId+".controlcenter.request.setvoice",function(voice){me.forceVoice(voice)});talkify.messageHub.publish(this.correlationId+".player.*.ratechanged",me.settings.rate);this.withReferenceLanguage=function(refLang){this.settings.referenceLanguage=refLang;return this};this.enableTextHighlighting=function(){this.settings.useTextHighlight=true;talkify.messageHub.publish(this.correlationId+".player.*.texthighlight.enabled");return this};this.disableTextHighlighting=function(){this.settings.useTextHighlight=false;talkify.messageHub.publish(this.correlationId+".player.*.texthighlight.disabled");return this};this.setRate=function(r){this.settings.rate=r;talkify.messageHub.publish(this.correlationId+".player.*.ratechanged",r);return this};this.subscribeTo=function(subscriptions){talkify.messageHub.subscribe("core-player",this.correlationId+".player.*.pause",subscriptions.onPause||function(){});talkify.messageHub.subscribe("core-player",this.correlationId+".player.*.resume",subscriptions.onResume||function(){});talkify.messageHub.subscribe("core-player",this.correlationId+".player.*.play",subscriptions.onPlay||function(){});talkify.messageHub.subscribe("core-player",this.correlationId+".player.*.loaded",subscriptions.onItemLoaded||function(){});talkify.messageHub.subscribe("core-player",[this.correlationId+".wordhighlighter.complete",this.correlationId+".player.html5.utterancecomplete"],subscriptions.onItemFinished||function(){});talkify.messageHub.subscribe("core-player",this.correlationId+".player.*.prepareplay",subscriptions.onBeforeItemPlaying||function(){});talkify.messageHub.subscribe("core-player",this.correlationId+".controlcenter.texthighlightoggled",subscriptions.onTextHighligtChanged||function(){});return this};this.playItem=function(item){if(item&&item.isPlaying){if(this.audioSource.paused()){this.audioSource.play()}else{this.audioSource.pause()}}talkify.messageHub.publish(this.correlationId+".player.*.prepareplay",item);item.isLoading=true;item.isPlaying=true;item.element.classList.add("playing");this.playAudio(item)};this.createItems=function(text){var safeMaxQuerystringLength=window.talkify.config.maximumTextLength||1e3;var items=[];if(text.length>safeMaxQuerystringLength){var f=text.substr(0,safeMaxQuerystringLength);items.push(template(f));items=items.concat(this.createItems(text.substr(safeMaxQuerystringLength,text.length-1)));return items}items.push(template(text));return items;function template(t){var element=document.createElement("span");var clone=element.cloneNode(true);return{text:t,preview:t.substr(0,40),element:element,originalElement:clone,isPlaying:false,isLoading:false}}};this.playText=function(text){if(!text){return}var items=this.createItems(text);var currentItem=0;talkify.messageHub.subscribe("core-player.playText",this.correlationId+".player.*.ended",function(){currentItem++;if(currentItem>=items.length){talkify.messageHub.unsubscribe("core.playText",this.correlationId+".player.*.ended");return}this.playItem(items[currentItem])});this.playItem(items[currentItem])};this.paused=function(){return this.audioSource.paused()};this.isPlaying=function(){return this.audioSource.isPlaying()};this.play=function(){this.audioSource.play()};this.pause=function(){this.audioSource.pause();var me=this;if(!me.audioSource.paused()&&me.audioSource.cancel){me.audioSource.cancel(true)}};this.dispose=function(){talkify.messageHub.publish(this.correlationId+".player.tts.disposed");this.audioSource.stop();this.audioSource.dispose();this.wordHighlighter.dispose();talkify.messageHub.unsubscribe("core-player",this.correlationId+".player.*.loaded");talkify.messageHub.unsubscribe("core-player",this.correlationId+".player.*.ended");talkify.messageHub.unsubscribe("core-player",this.correlationId+".controlcenter.texthighlightoggled");talkify.messageHub.unsubscribe("core-player",this.correlationId+".player.*.pause");talkify.messageHub.unsubscribe("core-player",this.correlationId+".player.*.resume");talkify.messageHub.unsubscribe("core-player",this.correlationId+".player.*.play");talkify.messageHub.unsubscribe("core-player",[this.correlationId+".wordhighlighter.complete",this.correlationId+".player.html5.utterancecomplete"]);talkify.messageHub.unsubscribe("core-player",this.correlationId+".player.*.prepareplay");talkify.messageHub.unsubscribe("core-player",this.correlationId+".controlcenter.texthighlightoggled");talkify.messageHub.unsubscribe("core-player",this.correlationId+".controlcenter.request.setvoice")};this.forceLanguage=function(culture){this.settings.lockedLanguage=culture;return this};this.forceVoice=function(voice){this.forcedVoice=voice!==undefined?voice:null;this.settings.lockedLanguage=voice&&(voice.lang||voice.culture)||this.settings.lockedLanguage;talkify.messageHub.publish(this.correlationId+".player.*.voiceset",voice);return this}}},{}],14:[function(require,module,exports){talkify=talkify||{};talkify.TtsPlayer=function(){if(!talkify.config.remoteService.active){throw"This player needs to communicate to a remote service. To enable this player please set flag talkify.config.remoteService.active to true."}var me=this;var audioElement,timeupdater;var currentVoice,currentPitch,currentWordBreak,currentRate;this.currentContext={item:null,positions:[]};this.playbar={instance:null};this.audioSource={play:function(){audioElement.play()},pause:function(){audioElement.pause()},isPlaying:function(){return audioElement.duration>0&&!audioElement.paused},paused:function(){return audioElement.paused},currentTime:function(){return audioElement.currentTime},stop:function(){audioElement.pause();audioElement.currentTime=0},dispose:function(){if(timeupdater){clearInterval(timeupdater)}var existingElement=document.getElementById("talkify-audio");if(existingElement){existingElement.outerHTML=""}talkify.messageHub.unsubscribe("tts-player",me.correlationId+".controlcenter.request.play");talkify.messageHub.unsubscribe("tts-player",me.correlationId+".controlcenter.request.pause");talkify.messageHub.unsubscribe("tts-player",me.correlationId+".controlcenter.request.seek");talkify.messageHub.unsubscribe("tts-player",me.correlationId+".controlcenter.request.volume");talkify.messageHub.unsubscribe("tts-player",me.correlationId+".controlcenter.request.rate");talkify.messageHub.unsubscribe("tts-player",me.correlationId+".controlcenter.request.wordbreak");talkify.messageHub.unsubscribe("tts-player",me.correlationId+".controlcenter.request.pitch");talkify.messageHub.unsubscribe("tts-player",me.correlationId+".controlcenter.request.phonation.normal");talkify.messageHub.unsubscribe("tts-player",me.correlationId+".controlcenter.request.phonation.soft");talkify.messageHub.unsubscribe("tts-player",me.correlationId+".controlcenter.request.phonation.whisper")}};talkify.BasePlayer.call(this,this.audioSource,this.playbar);this.settings.whisper=false;this.settings.soft=false;this.settings.wordbreakms=0;this.settings.volumeDb=0;this.settings.pitch=0;function setupBindings(){audioElement.addEventListener("pause",onPause);audioElement.addEventListener("play",onPlay);audioElement.addEventListener("seeked",onSeek)}function onSeek(){talkify.messageHub.publish(me.correlationId+".player.tts.seeked",{time:this.currentTime,item:me.currentContext.item,positions:me.currentContext.positions});if(me.audioSource.paused()&&me.audioSource.currentTime()>.1){me.audioSource.play()}}function onPause(){if(timeupdater){clearInterval(timeupdater)}talkify.messageHub.publish(me.correlationId+".player.tts.pause")}function onPlay(){if(timeupdater){clearInterval(timeupdater)}timeupdater=setInterval(function(){talkify.messageHub.publish(me.correlationId+".player.tts.timeupdated",{currentTime:audioElement.currentTime,duration:audioElement.duration})},50);if(!me.currentContext.item){talkify.messageHub.publish(me.correlationId+".player.tts.unplayable");me.audioSource.pause()}if(!me.currentContext.positions.length){talkify.messageHub.publish(me.correlationId+".player.tts.play",{item:me.currentContext.item,positions:[],currentTime:me.audioSource.currentTime()});return}if(me.audioSource.currentTime()>.1){talkify.messageHub.publish(me.correlationId+".player.tts.resume",{currentTime:me.audioSource.currentTime()})}else{var interval=setInterval(function(){if(me.audioSource.currentTime()>0){clearInterval(interval);talkify.messageHub.publish(me.correlationId+".player.tts.play",{item:me.currentContext.item,positions:me.currentContext.positions,currentTime:me.audioSource.currentTime()})}},20)}}function initialize(){if(timeupdater){clearInterval(timeupdater)}audioElement=null;var existingElement=document.getElementById("talkify-audio");if(existingElement){existingElement.outerHTML=""}var mp3Source=document.createElement("source");var wavSource=document.createElement("source");audioElement=document.createElement("audio");audioElement.appendChild(mp3Source);audioElement.appendChild(wavSource);mp3Source.type="audio/mpeg";wavSource.type="audio/wav";audioElement.id="talkify-audio";audioElement.controls=talkify.config.ui.audioControls.enabled&&talkify.config.ui.audioControls.controlcenter==="native";audioElement.autoplay=false;(talkify.config.ui.audioControls.container||document.body).appendChild(audioElement);var clonedAudio=audioElement.cloneNode(true);audioElement.parentNode.replaceChild(clonedAudio,audioElement);audioElement=clonedAudio;talkify.messageHub.subscribe("tts-player",me.correlationId+".controlcenter.request.play",function(){me.play()});talkify.messageHub.subscribe("tts-player",me.correlationId+".controlcenter.request.pause",function(){audioElement.pause()});talkify.messageHub.subscribe("tts-player",me.correlationId+".controlcenter.request.seek",function(position){var pos=audioElement.duration*position;if(isNaN(audioElement.duration)){return}audioElement.currentTime=pos});talkify.messageHub.subscribe("tts-player",me.correlationId+".controlcenter.request.volume",function(volume){audioElement.volume=volume/10});talkify.messageHub.subscribe("tts-player",me.correlationId+".controlcenter.request.rate",function(rate){me.settings.rate=rate;talkify.messageHub.publish(me.correlationId+".player.tts.ratechanged",me.settings.rate)});talkify.messageHub.subscribe("tts-player",me.correlationId+".controlcenter.request.wordbreak",function(ms){me.useWordBreak(ms)});talkify.messageHub.subscribe("tts-player",me.correlationId+".controlcenter.request.pitch",function(value){me.usePitch(value)});talkify.messageHub.subscribe("tts-player",me.correlationId+".controlcenter.request.phonation.soft",function(){me.normalTone();me.usePhonation("soft")});talkify.messageHub.subscribe("tts-player",me.correlationId+".controlcenter.request.phonation.normal",function(){me.normalTone();me.usePhonation("normal")});talkify.messageHub.subscribe("tts-player",me.correlationId+".controlcenter.request.phonation.whisper",function(){me.usePhonation("normal");me.whisper()});if(me.playbar.instance){me.playbar.instance.setMinRate(-5).setMaxRate(5)}}function getPositions(requestId){var p=new promise.promise.Promise;talkify.http.get(talkify.config.remoteService.speechBaseUrl+"/marks?id="+requestId).then(function(error,positions){p.done(null,positions)});return p}initialize.apply(this);this.playAudio=function(item){talkify.messageHub.publish(me.correlationId+".player.tts.loading",item);me.currentContext.item=item;me.currentContext.positions=[];audioElement.onloadeddata=null;audioElement.onended=null;var sources=audioElement.getElementsByTagName("source");var textType=talkify.config.useSsml&&item.ssml?"ssml":"text";var textToPlay=textType==="ssml"?encodeURIComponent(item.ssml.replace(/\n/g," ")):encodeURIComponent(item.text.replace(/\n/g," "));var voice=item.voice||(this.forcedVoice?this.forcedVoice.name:"");if(voice!==currentVoice){talkify.messageHub.publish(this.correlationId+".player.tts.voiceset",{name:voice});currentVoice=voice}var pitch=item.pitch||this.settings.pitch;if(pitch!==currentPitch){talkify.messageHub.publish(me.correlationId+".player.tts.pitchchanged",pitch);currentPitch=pitch}var wordbreak=item.wordbreakms||this.settings.wordbreakms;if(wordbreak!==currentWordBreak){talkify.messageHub.publish(me.correlationId+".player.tts.wordbreakchanged",wordbreak);currentWordBreak=wordbreak}var rate=item.rate||this.settings.rate;if(rate!==currentRate){talkify.messageHub.publish(me.correlationId+".player.tts.ratechanged",rate);currentRate=rate}var requestId=talkify.generateGuid();var audioUrl=talkify.config.remoteService.host+talkify.config.remoteService.speechBaseUrl+"?texttype="+textType+"&text="+textToPlay+"&fallbackLanguage="+this.settings.referenceLanguage.Language+"&voice="+voice+"&rate="+rate+"&key="+talkify.config.remoteService.apiKey+"&whisper="+(item.whisper||this.settings.whisper)+"&soft="+(item.soft||this.settings.soft)+"&wordbreakms="+wordbreak+"&volume="+this.settings.volumeDb+"&pitch="+pitch;if(me.settings.useTextHighlight){audioUrl+="&marksid="+requestId}sources[0].src=audioUrl+"&format=mp3";sources[1].src=audioUrl+"&format=wav";sources[1].onerror=function(e){talkify.messageHub.publish(me.correlationId+".player.tts.error",null)};audioElement.load();audioElement.onloadeddata=function(){me.audioSource.pause();if(!me.settings.useTextHighlight){talkify.messageHub.publish(me.correlationId+".player.tts.loaded",me.currentContext.item);me.audioSource.play();return}getPositions(requestId).then(function(error,positions){me.currentContext.positions=positions||[];talkify.messageHub.publish(me.correlationId+".player.tts.loaded",me.currentContext.item);me.audioSource.play()})};audioElement.onended=function(){talkify.messageHub.publish(me.correlationId+".player.tts.ended",item)}};this.usePhonation=function(phonation){this.settings.soft=phonation==="soft";talkify.messageHub.publish(me.correlationId+".player.tts.phonationchanged",phonation);return this};this.whisper=function(){this.settings.whisper=true;talkify.messageHub.publish(me.correlationId+".player.tts.whisperchanged",true);return this};this.normalTone=function(){this.settings.whisper=false;talkify.messageHub.publish(me.correlationId+".player.tts.whisperchanged",false);return this};this.useWordBreak=function(ms){this.settings.wordbreakms=Math.max(0,ms);talkify.messageHub.publish(me.correlationId+".player.tts.wordbreakchanged",this.settings.wordbreakms);return this};this.useVolumeBaseline=function(volumeDb){this.settings.volumeDb=volumeDb;talkify.messageHub.publish(me.correlationId+".player.tts.volumechanged",volumeDb);return this};this.usePitch=function(pitch){this.settings.pitch=pitch;talkify.messageHub.publish(me.correlationId+".player.tts.pitchchanged",pitch);return this};setupBindings()};talkify.TtsPlayer.prototype.constructor=talkify.TtsPlayer},{}],15:[function(require,module,exports){talkify=talkify||{};talkify.playlist=function(){var defaults={useGui:false,useTextInteraction:false,domElements:[],exclusions:[],rootSelector:"body",events:{onEnded:null,onVoiceCommandListeningStarted:null,onVoiceCommandListeningEnded:null}};var s=JSON.parse(JSON.stringify(defaults));var p=null;function isSupported(){var a=document.createElement("audio");return typeof a.canPlayType==="function"&&(a.canPlayType("audio/mpeg")!==""||a.canPlayType("audio/wav")!=="")}function implementation(_settings,player){var textextractor=new talkify.textextractor;var playlist={queue:[],currentlyPlaying:null,refrenceText:"",referenceLanguage:{Culture:"",Language:-1}};var settings=_settings;var playerHasBeenReplaced=false;var commands=[new talkify.KeyboardCommands(talkify.config.keyboardCommands),new talkify.SpeechCommands(talkify.config.voiceCommands)];var voiceCommands=commands[1];for(var k=0;ksafeMaxQuerystringLength){var chuncks=getSafeTextChunks(text,safeMaxQuerystringLength);element.innerHTML="";for(var i=0;i-1?breakAt:text.substr(0,safeMaxQuerystringLength).lastIndexOf("。");breakAt=breakAt>-1?breakAt:safeMaxQuerystringLength;return text.substr(0,breakAt+1)}function play(item){if(!item){if(playlist.queue.length===0){return}playFromBeginning();return}playItem(item)}function pause(){player.pause()}function setupItemForUserInteraction(item){item.element.style.cursor="pointer";item.element.classList.add("talkify-highlight");removeEventListeners("click",item.element);addEventListener("click",item.element,textInteractionEventListener);function textInteractionEventListener(){play(item)}}function removeUserInteractionForItem(item){item.element.style.cursor="inherit";item.element.classList.remove("talkify-highlight");removeEventListeners("click",item.element)}function initialize(){reset();if(!settings.domElements||settings.domElements.length===0){settings.domElements=textextractor.extract(settings.rootSelector,settings.exclusions)}for(var i=0;iplaylist.refrenceText.length){playlist.refrenceText=text}}if(settings.useTextInteraction){for(var j=0;j0){var isSameAsPrevious=item.element===playlist.queue[j-1].element;if(isSameAsPrevious){continue}}setupItemForUserInteraction(item)}}talkify.messageHub.publish(player.correlationId+".playlist.loaded");if(settings.useTextInteraction){talkify.messageHub.publish(player.correlationId+".playlist.textinteraction.enabled")}else{talkify.messageHub.publish(player.correlationId+".playlist.textinteraction.disabled")}}function convertToSsml(element){if(!talkify.config.useSsml){return null}var ssmlMappings={h1:{start:'###emphasis level="strong">',end:"###/emphasis>",trim:false},h2:{start:'###emphasis level="strong">',end:"###/emphasis>",trim:false},h3:{start:'###emphasis level="strong">',end:"###/emphasis>",trim:false},b:{start:'###emphasis level="strong">',end:"###/emphasis>",trim:false},strong:{start:'###emphasis level="strong">',end:"###/emphasis>",trim:false},em:{start:'###emphasis level="strong">',end:"###/emphasis>",trim:false},i:{start:'###emphasis level="reduced">',end:"###/emphasis>",trim:false},br:{start:'###break strength="x-strong">###/break>',end:"",trim:true}};var htmlEntities={};htmlEntities[" "]=" ";htmlEntities["<"]="<";htmlEntities[">"]=">";htmlEntities["&qout;"]='"';htmlEntities["'"]="'";htmlEntities["&"]="&";var ssml=element.innerHTML.replace(/ +/g," ").replace(/(\r\n|\n|\r)/gm,"").trim();for(var key in htmlEntities){ssml=ssml.replace(new RegExp(key,"g"),htmlEntities[key])}for(var key in ssmlMappings){var mapping=ssmlMappings[key];var startTagMatches=ssml.match(new RegExp("<"+key+"+(>|.*?[^?]>)","gi"))||[];for(var j=0;j"&&startTagMatches[j].indexOf("<"+key+" ")!==0){continue}ssml=ssml.replace(startTagMatches[j],mapping.start);if(mapping.trim){ssml=ssml.split(mapping.start).map(function(x){return x.trim()}).join(mapping.start)}}ssml=ssml.split("").map(function(x,i){return mapping.trim?x.trim():x}).join(mapping.end)}ssml=ssml.replace(/<[^>]*>?/gm,"");ssml=ssml.replace(/\s+/g," ");ssml=ssml.split("###").join("<");return ssml}function getNextItem(){var currentQueuePosition=playlist.queue.indexOf(playlist.currentlyPlaying);if(currentQueuePosition===playlist.queue.length-1){return null}return playlist.queue[currentQueuePosition+1]}function getPreviousItem(){var currentQueuePosition=playlist.queue.indexOf(playlist.currentlyPlaying);if(currentQueuePosition===0){return null}return playlist.queue[currentQueuePosition-1]}function playFromBeginning(){if(!talkify.config.remoteService.active){onComplete({Cultures:[],Language:-1});return}var text=playlist.refrenceText.length<=1e3?playlist.refrenceText:playlist.refrenceText.substr(0,1e3);talkify.http.get(talkify.config.remoteService.languageBaseUrl+"/detect?text="+text).then(function(error,data){if(error){onComplete({Cultures:[],Language:-1});return}onComplete(data)});function onComplete(refLang){playlist.referenceLanguage={Culture:refLang.Cultures[0],Language:refLang.Language};player.withReferenceLanguage(playlist.referenceLanguage);playItem(playlist.queue[0])}}function insertElement(element){var items=[];var text=element.innerText;if(text.trim()===""){return items}if(domElementExistsInQueue(element)){return items}var documentPositionFollowing=4;for(var j=0;j-1})[0];if(match){possibleMatches.push(key);break}}}if(possibleMatches.length>0){var bestValue=0;var bestCommand=null;for(var j=0;jbestValue){bestValue=temp;bestCommand=possibleMatches[j]}}return bestCommand}return null}function levenshtein(s1,s2){var longer=s1;var shorter=s2;if(s1.length0){var newValue=costs[j-1];if(s1.charAt(i-1)!=s2.charAt(j-1))newValue=Math.min(Math.min(newValue,lastValue),costs[j])+1;costs[j-1]=lastValue;lastValue=newValue}}}if(i>0)costs[s2.length]=lastValue}return costs[s2.length]}if(speechCommandConfig.keyboardActivation.enabled){document.addEventListener("keyup",function(e){if(!e.ctrlKey){return}if(isListening){return}var key=e.keyCode?e.keyCode:e.which;if(key===speechCommandConfig.keyboardActivation.key){recognition.start()}})}return{onPrevious:function(callback){onPreviousCallback=callback},onNext:function(callback){onNextCallback=callback},onPlayPause:function(callback){onPlayPauseCallback=callback},start:function(){if(isListening){return}recognition.start()},onListeningStarted:function(callback){onListeningStartedCallback=callback},onListeningEnded:function(callback){onListeningEndedCallback=callback},dispose:function(){}}}},{}],17:[function(require,module,exports){talkify=talkify||{};talkify.textextractor=function(){var validElements=[];var inlineElements=["a","span","b","big","i","small","tt","abbr","acronym","cite","code","dfn","em","kbd","strong","samp","var","a","bdo","q","sub","sup","label"];var forbiddenElementsString=["img","map","object","script","button","input","select","textarea","style","code","nav","#nav","#navigation",".nav",".navigation","footer","rp","rt"];var userExcludedElements=[];function getVisible(elements){var result=[];for(var j=0;j=10}return false}function isValidAnchor(node){var nrOfSiblings=getSiblings(node);if(nrOfSiblings.length>=1){return true}var previous=node.previousSibling;if(isValidTextNode(previous)){return true}if(isValidTextNode(node.nextSibling)){return true}return false}function isValidForGrouping(node){if(node.nodeName==="BR"){return true}var isTextNode=node.nodeType===3;var textLength=getStrippedText(node.textContent).length;return isTextNode&&textLength>=2||!isForbidden(node)&&elementIsInlineElement(node)}function getConnectedElements(nodes,firstIndex){var connectedElements=[];for(var l=firstIndex;l1){var wrapping=group(connectedElements);var isAboveThreshold=getStrippedText(wrapping.innerText).length>=20;if(isAboveThreshold){nodes[i].parentNode.replaceChild(wrapping,nodes[i]);for(var j=0;j "+generateExcludesFromForbiddenElements());for(var i=0;i=position&&time<=currentPositions[i+1].Position){currentPos=i;break}}if(currentPosition===currentPos){return}currentPosition=currentPos;highlight(currentItem,currentPositions[currentPos].Word,currentPositions[currentPos].CharPosition)});function adjustPositionsToSsml(text,positions){var internalPos=JSON.parse(JSON.stringify(positions));var lastFound=0;for(var i=0;i'+text.substring(sentence.start,charPosition)+''+text.substring(charPosition,charPosition+word.length)+""+text.substring(charPosition+word.length,sentence.end)+""+text.substring(sentence.end)}function cancel(){resetCurrentItem();currentPositions=[]}function setupWordHightlighting(item,positions,startFrom){cancel();if(!positions.length){return}if(item.ssml||item.wordbreakms||currentWordbreakMs){currentPositions=adjustPositionsToSsml(item.text,positions)}else{currentPositions=positions}var i=startFrom||0;var internalCallback=function(){currentItem=item;i++;if(i>=positions.length){window.setTimeout(function(){item.element.innerHTML=item.originalElement.innerHTML;talkify.messageHub.publish(correlationId+".wordhighlighter.complete",item)},1e3);return}};internalCallback()}function resetCurrentItem(){if(currentItem){currentItem.element.innerHTML=currentItem.originalElement.innerHTML}}function setPosition(message){var diff=0;var timeInMs=message.time*1e3;var nextPosition=0;for(var i=0;i=charactersTraversed&&charPosition<=charactersTraversed+result[i].length){if(charactersTraversed>0){sentenceStart=charactersTraversed+1}sentenceEnd=charactersTraversed+result[i].length;break}charactersTraversed+=result[i].length}return{start:sentenceStart,end:sentenceEnd}}function dispose(){talkify.messageHub.unsubscribe("word-highlighter",correlationId+".player.tts.seeked");talkify.messageHub.unsubscribe("word-highlighter",[correlationId+".player.tts.loading",correlationId+".player.tts.disposed"]);talkify.messageHub.unsubscribe("word-highlighter",correlationId+".player.tts.play");talkify.messageHub.unsubscribe("word-highlighter",correlationId+".player.tts.timeupdated")}return{start:setupWordHightlighting,highlight:highlight,dispose:dispose}}},{}],20:[function(require,module,exports){talkify={}},{}]},{},[1]); +(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i
  • 00:00 / 00:00
  • ;
'}},{}],3:[function(require,module,exports){talkify=talkify||{};talkify.playbar=function(parent,correlationId){var mainFlags=["de-DE","fr-FR","en-US","zh-CN","es-ES","it-IT","ja-JP","ko-KR","sv-SE","nb-NO","da-DK","ru-RU","nl-NL","pl-PL","tr-TR","is-IS","uk-UA","sk-SK","pt-PT","ro-RO","cy-GB","bg-BG","cs-CZ","el-GR","fi-FI","he-IL","hi-IN","hr-HR","hu-HU","id-ID","ms-MY","sl-SI","th-TH","vi-VN","ar-EG","ar-SA","ta-IN","te-IN","en-GB-WLS","ca-ES","gu-IN","ml-IN","bn-IN","kn-IN","fil-PH"];var settings={parentElement:parent||talkify.config.ui.audioControls.container||document.body};var playElement,pauseElement,rateElement,volumeElement,progressElement,voiceElement,currentTimeElement,textHighlightingElement,wrapper,voicePicker;var attachElement,detatchedElement,dragArea,loader,erroroccurredElement,textInteractionElement,pitchElement,wordBreakElement,wordBreakElementWrapper;var pitchElementWrapper,nextItemElement,previousItemElement,voiceNameElement;var flagElement,phonationNormalElement,phonationSoftElement,phonationWhisperElement,phonationDropDown;var voices=[];function hide(element){if(!element||element.classList.contains("talkify-hidden")){return}element.className+=" talkify-hidden"}function show(element){if(!element){return}element.className=element.className.replace("talkify-hidden","")}function play(){hide(loader);hide(playElement);hide(erroroccurredElement);show(pauseElement)}function pause(){hide(loader);hide(pauseElement);hide(erroroccurredElement);show(playElement)}function onError(){hide(loader);hide(pauseElement);hide(playElement);show(erroroccurredElement)}function addClass(element,c){if(element.classList.contains(c)){return}element.className+=" "+c}function removeClass(element,c){element.className=element.className.replace(c,"")}function createElement(type,classes){var element=document.createElement(type);element.className=classes;return element}var groupBy=function(xs,keyFn){return xs.reduce(function(rv,x){var key=keyFn(x);(rv[key]=rv[key]||[]).push(x);return rv},{})};function createVoicePicker(voices){var mainUl=createElement("ul","voice-selector");if(!voices.length){return mainUl}var byLanguage=groupBy(voices,function(v){return v.language});for(var prop in byLanguage){if(!byLanguage.hasOwnProperty(prop)){continue}var sortedVoices=byLanguage[prop].sort(function(a,b){return a.culture-b.culture});var defaultVoice=sortedVoices.filter(function(x){return x.isStandard})[0];var foo=sortedVoices.find(function(v){return mainFlags.indexOf(v.culture)!==-1});if(!foo){continue}var mainFlag="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/3.3.0/flags/4x3/"+foo.culture.split("-")[1].toLowerCase()+".svg";var li=createElement("li");var flagImg=createElement("img","talkify-flag");flagImg.src=mainFlag;var label=createElement("label","talkify-clickable");label.innerHTML=sortedVoices[0].language;label.htmlFor="chk_"+prop;var checkbox=createElement("input","");checkbox.id="chk_"+prop;checkbox.type="checkbox";checkbox.style="display: none";li.appendChild(flagImg);li.appendChild(label);li.appendChild(checkbox);var innerUl=createElement("ul","language");li.appendChild(innerUl);for(var j=0;j1){clickedValue=1}if(clickedValue<0){clickedValue=0}talkify.messageHub.publish(correlationId+".controlcenter.request.seek",clickedValue)});attachElement.addEventListener("click",function(){addClass(controlCenter,"attached");removeClass(controlCenter,"detached")});detatchedElement.addEventListener("click",function(){removeClass(controlCenter,"attached");addClass(controlCenter,"detached")});dragArea.addEventListener("mousedown",onMouseDown);document.addEventListener("mouseup",onMouseUp);function onMouseUp(e){document.removeEventListener("mousemove",onMouseMove)}function onMouseDown(e){document.addEventListener("mousemove",onMouseMove)}function onMouseMove(e){e.preventDefault();var dArea=dragArea.getBoundingClientRect();var leftOffset=dArea.width/2+dArea.x-controlCenter.getBoundingClientRect().x;controlCenter.style.top=e.clientY-controlCenter.offsetHeight/2+"px";controlCenter.style.left=e.clientX-leftOffset+"px"}}function initialize(){render();setupBindings();talkify.messageHub.subscribe("controlcenter",[correlationId+".player.*.pause",correlationId+".player.*.disposed"],pause);talkify.messageHub.subscribe("controlcenter",[correlationId+".player.*.play",correlationId+".player.*.resume"],play);talkify.messageHub.subscribe("controlcenter",correlationId+".player.*.disposed",dispose);talkify.messageHub.subscribe("controlcenter",correlationId+".player.*.loading",function(){hide(playElement);hide(pauseElement);hide(erroroccurredElement);show(loader)});talkify.messageHub.subscribe("controlcenter",correlationId+".player.*.loaded",function(){removeClass(pauseElement,"talkify-disabled");removeClass(playElement,"talkify-disabled");show(playElement);hide(loader)});talkify.messageHub.subscribe("controlcenter",correlationId+".player.*.texthighlight.enabled",function(){removeClass(textHighlightingElement,"talkify-disabled")});talkify.messageHub.subscribe("controlcenter",correlationId+".player.*.texthighlight.disabled",function(){addClass(textHighlightingElement,"talkify-disabled")});talkify.messageHub.subscribe("controlcenter",correlationId+".player.*.ratechanged",function(rate){rateElement.forEach(function(x){x.value=rate})});talkify.messageHub.subscribe("controlcenter",correlationId+".player.*.voiceset",function(voice){featureToggle(voice);setVoiceName(voice)});talkify.messageHub.subscribe("controlcenter",correlationId+".player.tts.error",onError);talkify.messageHub.subscribe("controlcenter",correlationId+".player.tts.timeupdated",updateClock);talkify.messageHub.subscribe("controlcenter",correlationId+".player.html5.timeupdated",function(value){progressElement.setAttribute("value",value)});talkify.messageHub.subscribe("controlcenter",correlationId+".playlist.loaded",function(){removeClass(playElement,"talkify-disabled")});talkify.messageHub.subscribe("controlcenter",correlationId+".playlist.textinteraction.enabled",function(){removeClass(textInteractionElement,"talkify-disabled")});talkify.messageHub.subscribe("controlcenter",correlationId+".playlist.textinteraction.disabled",function(){addClass(textInteractionElement,"talkify-disabled")});talkify.messageHub.subscribe("controlcenter",correlationId+".player.tts.wordbreakchanged",function(ms){wordBreakElement.value=ms});talkify.messageHub.subscribe("controlcenter",correlationId+".player.tts.pitchchanged",function(value){pitchElement.value=value});talkify.messageHub.subscribe("controlcenter",correlationId+".player.tts.phonationchanged",function(phonation){phonationDropDown.value=phonation==="soft"?"soft":"normal"});talkify.messageHub.subscribe("controlcenter",correlationId+".player.tts.whisperchanged",function(whisper){phonationDropDown.value=whisper?"whisper":"normal"});talkify.messageHub.subscribe("controlcenter",correlationId+".playlist.playing",function(msg){removeClass(nextItemElement,"talkify-disabled");removeClass(previousItemElement,"talkify-disabled");if(msg.isLast){addClass(nextItemElement,"talkify-disabled")}if(msg.isFirst){addClass(previousItemElement,"talkify-disabled")}});if(!talkify.config.ui.audioControls.voicepicker.enabled){return}talkify.http.get(talkify.config.remoteService.speechBaseUrl+"/voices").then(function(error,data){if(error!==false){return}voices=window.talkify.toLowerCaseKeys(data);voicePicker=createVoicePicker(filterVoicesByConfig(voices));wrapper.getElementsByClassName("talkify-voice-selector")[0].appendChild(voicePicker);voicePicker.querySelectorAll(".language > li").forEach(function(item){item.addEventListener("click",function(e){var voice=JSON.parse(e.currentTarget.dataset.voice);talkify.messageHub.publish(correlationId+".controlcenter.request.setvoice",window.talkify.toLowerCaseKeys(voice))})});if(voiceNameElement.textContent){var backendVoice=voices.find(function(v){return v.name===voiceNameElement.textContent});if(backendVoice){featureToggle(backendVoice);setVoiceName(backendVoice)}}})}function filterVoicesByConfig(voices){var filter=talkify.config.ui.audioControls.voicepicker.filter;if(!filter){return voices}return voices.filter(function(voice){var active=true;if(filter.byCulture.length){active=filter.byCulture.indexOf(voice.culture)!==-1}if(active&&filter.byLanguage.length){active=filter.byLanguage.indexOf(voice.language)!==-1}if(active&&filter.byClass.length){if(filter.byClass.indexOf("Standard")!==-1&&voice.isStandard){return true}if(filter.byClass.indexOf("Premium")!==-1&&voice.isPremium){return true}if(filter.byClass.indexOf("Exclusive")!==-1&&voice.isExclusive){return true}if(filter.byClass.indexOf("Neural")!==-1&&voice.isNeural){return true}return false}return active})}function updateClock(timeInfo){var currentTime=timeInfo.currentTime;var duration=timeInfo.duration;progressElement.setAttribute("value",currentTime/duration);if(!currentTimeElement){return}var currentminutes=Math.floor(currentTime/60);var currentseconds=Math.round(currentTime)-currentminutes*60;var totalminutes=!!duration?Math.floor(duration/60):0;var totalseconds=!!duration?Math.round(duration)-totalminutes*60:0;currentTimeElement.textContent=currentminutes+":"+(currentseconds<10?"0"+currentseconds:currentseconds)+" / "+totalminutes+":"+(totalseconds<10?"0"+totalseconds:totalseconds)}function isTalkifyHostedVoice(voice){return voice&&voice.constructor.name!=="SpeechSynthesisVoice"}function featureToggle(voice){show(progressElement);show(textHighlightingElement);if(!voice){return}var backendVoice=voices.find(function(v){return v.name===voice.name});if(backendVoice){voice=backendVoice}voice.canUsePitch?show(pitchElementWrapper):hide(pitchElementWrapper);voice.canUseWordBreak?show(wordBreakElementWrapper):hide(wordBreakElementWrapper);voice.canWhisper?show(phonationWhisperElement):hide(phonationWhisperElement);voice.canSpeakSoftly?show(phonationSoftElement):hide(phonationSoftElement);if(voice.canSpeakSoftly){}if(isTalkifyHostedVoice(voice)){return}hide(currentTimeElement);if(!voice.localService){hide(progressElement);hide(textHighlightingElement)}}function setVoiceName(voice){if(!voice){voiceNameElement.textContent="Automatic voice detection";return}var backendVoice=voices.find(function(v){return v.name===voice.name});if(backendVoice){voice=backendVoice}var split=(voice.culture||"").split("-");if(split.length>1){flagElement.src="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/3.3.0/flags/4x3/"+split[1].toLowerCase()+".svg";show(flagElement)}else{hide(flagElement)}if(isTalkifyHostedVoice(voice)){voiceNameElement.textContent=voice.name;return}voiceNameElement.textContent=voice.name}function dispose(){var existingControl=document.getElementsByClassName("talkify-control-center")[0];if(existingControl){existingControl.parentNode.removeChild(existingControl)}talkify.messageHub.unsubscribe("controlcenter",[correlationId+".player.*.pause",correlationId+".player.*.disposed"]);talkify.messageHub.unsubscribe("controlcenter",[correlationId+".player.*.play",correlationId+".player.*.resume"]);talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.*.disposed");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.*.loaded");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.*.loading");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.*.texthighlight.enabled");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.*.texthighlight.disabled");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.*.ratechanged");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.*.voiceset");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.tts.timeupdated");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.html5.timeupdated");talkify.messageHub.unsubscribe("controlcenter",correlationId+".playlist.loaded");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.tts.error");talkify.messageHub.unsubscribe("controlcenter",correlationId+".playlist.textinteraction.enabled");talkify.messageHub.unsubscribe("controlcenter",correlationId+".playlist.textinteraction.disabled");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.tts.wordbreakchanged");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.tts.pitchchanged");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.tts.phonationchanged");talkify.messageHub.unsubscribe("controlcenter",correlationId+".player.tts.whisperchanged");talkify.messageHub.unsubscribe("controlcenter",correlationId+".playlist.playing")}initialize();return{setMaxRate:function(value){rateElement.forEach(function(x){x.setAttribute("max",value)});return this},setMinRate:function(value){rateElement.forEach(function(x){x.setAttribute("min",value)});return this},dispose:dispose}}},{}],4:[function(require,module,exports){talkify=talkify||{};talkify.controlcenters=talkify.controlcenters||{};talkify.controlcenters.local=function(){this.html='
T
'}},{}],5:[function(require,module,exports){talkify=talkify||{};talkify.controlcenters=talkify.controlcenters||{};talkify.controlcenters.modern=function(parent,correlationId){this.html='
    • Text highlighting
    • Text interaction
    • Dock player
'}},{}],6:[function(require,module,exports){(function(exports){function Promise(){this._callbacks=[]}Promise.prototype.then=function(func,context){var p;if(this._isdone){p=func.apply(context,this.result)}else{p=new Promise;this._callbacks.push(function(){var res=func.apply(context,arguments);if(res&&typeof res.then==="function")res.then(p.done,p)})}return p};Promise.prototype.done=function(){this.result=arguments;this._isdone=true;for(var i=0;i=300)&&xhr.status!==304;p.done(err,xhr.responseText,xhr)}};xhr.send(payload);return p}function _ajaxer(method){return function(url,data,headers){return ajax(method,url,data,headers)}}var promise={Promise:Promise,join:join,chain:chain,ajax:ajax,get:_ajaxer("GET"),post:_ajaxer("POST"),put:_ajaxer("PUT"),del:_ajaxer("DELETE"),ENOXHR:1,ETIMEOUT:2,ajaxTimeout:0};if(typeof define==="function"&&define.amd){define(function(){return promise})}else{exports.promise=promise}})(this)},{}],7:[function(require,module,exports){talkify=talkify||{};talkify.http=function ajax(){var get=function(url){var call=new promise.promise.Promise;var keypart=(url.indexOf("?")!==-1?"&key=":"?key=")+talkify.config.remoteService.apiKey;promise.promise.get(window.talkify.config.remoteService.host+url+keypart).then(function(error,data){try{var jsonObj=JSON.parse(data);call.done(error,jsonObj)}catch(e){call.done(e,data)}});return call};return{get:get}}()},{}],8:[function(require,module,exports){talkify=talkify||{};talkify.config={debug:false,useSsml:false,maximumTextLength:5e3,ui:{audioControls:{enabled:true,controlcenter:"native",container:document.body,voicepicker:{enabled:true,filter:{byClass:[],byCulture:[],byLanguage:[]}}}},formReader:{voice:null,rate:0,remoteService:true,requiredText:"This field is required",valueText:"You have entered {value} as: {label}.",selectedText:"You have selected {label}.",notSelectedText:"{label} is not selected."},remoteService:{active:true,host:"https://talkify.net",apiKey:"",speechBaseUrl:"/api/speech/v2",languageBaseUrl:"/api/language/v1"},keyboardCommands:{enabled:false,commands:{playPause:32,next:39,previous:37}},voiceCommands:{enabled:false,keyboardActivation:{enabled:true,key:77},commands:{playPause:["play","pause","stop","start"],next:["play next","next"],previous:["play previous","previous","back","go back"]}}}},{}],9:[function(require,module,exports){talkify=talkify||{};talkify.formReader=function(){var player;var timeout;function setupForm(formElement){var elements=formElement.elements;for(var i=0;i-1?70:language.indexOf("ko-")>-1?130:200;var chuncks=[];var sentences=text.split(/(\?|\.|。)+/g);var currentChunck="";sentences.forEach(function(sentence){if(sentence===""||sentence==="."||sentence==="。"||sentence==="?"){if(currentChunck){currentChunck+=sentence}return}if(currentChunck&¤tChunck.length+sentence.length>chunckSize){chuncks.push(currentChunck);currentChunck=""}if(sentence.length>chunckSize){var words=extractWords(sentence,language);words.forEach(function(word){if(currentChunck.length+word.length>chunckSize){chuncks.push(currentChunck);currentChunck=""}currentChunck+=word.trim()+" "});if(currentChunck.trim()){chuncks.push(currentChunck.trim()+".");currentChunck=""}return}currentChunck+=sentence});chuncks.push(currentChunck);return chuncks}function extractWords(text,language){var wordRegex=new RegExp(/[&\$\-|]|([("\-&])*(\b[^\s]+[.:,"-)!&?]*)/g);if(language){if(language.indexOf("zh-")>-1){return text.split(",")}if(language.indexOf("ko-")>-1){return text.split(".")}}var words=[];var m;while((m=wordRegex.exec(text))!==null){if(m.index===wordRegex.lastIndex){wordRegex.lastIndex++}words.push(m[0])}return words}function selectVoiceToPlay(voices){var matchingVoices=[];var voice=null;var language=me.settings.lockedLanguage||me.settings.referenceLanguage.Culture;for(var i=0;i-1}).forEach(function(subscriberKey){subscribers[subscriberKey]=subscribers[subscriberKey].filter(function(subscriber){return subscriber.key!==key})})}return{publish:publish,subscribe:subscribe,unsubscribe:unsubscribe}}()},{}],13:[function(require,module,exports){talkify=talkify||{};talkify.BasePlayer=function(_audiosource,_playbar){this.correlationId=talkify.generateGuid();this.audioSource=_audiosource;this.wordHighlighter=new talkify.wordHighlighter(this.correlationId);var me=this;this.settings={useTextHighlight:false,referenceLanguage:{Culture:"",Language:-1},lockedLanguage:null,rate:1,useControls:false};this.playbar=_playbar;this.forcedVoice=null;if(talkify.config.ui.audioControls.enabled&&talkify.config.ui.audioControls.controlcenter!=="native"){this.playbar.instance=talkify.playbar(null,this.correlationId)}talkify.messageHub.subscribe("core-player",this.correlationId+".player.*.loaded",function(item){item.isLoading=false});talkify.messageHub.subscribe("core-player",this.correlationId+".player.*.ended",function(item){item.isPlaying=false});talkify.messageHub.subscribe("core-player",this.correlationId+".controlcenter.texthighlightoggled",function(enabled){me.settings.useTextHighlight=enabled});talkify.messageHub.subscribe("core-player",this.correlationId+".controlcenter.request.setvoice",function(voice){me.forceVoice(voice)});talkify.messageHub.publish(this.correlationId+".player.*.ratechanged",me.settings.rate);this.withReferenceLanguage=function(refLang){this.settings.referenceLanguage=refLang;return this};this.enableTextHighlighting=function(){this.settings.useTextHighlight=true;talkify.messageHub.publish(this.correlationId+".player.*.texthighlight.enabled");return this};this.disableTextHighlighting=function(){this.settings.useTextHighlight=false;talkify.messageHub.publish(this.correlationId+".player.*.texthighlight.disabled");return this};this.setRate=function(r){this.settings.rate=r;talkify.messageHub.publish(this.correlationId+".player.*.ratechanged",r);return this};this.subscribeTo=function(subscriptions){talkify.messageHub.subscribe("core-player",this.correlationId+".player.*.pause",subscriptions.onPause||function(){});talkify.messageHub.subscribe("core-player",this.correlationId+".player.*.resume",subscriptions.onResume||function(){});talkify.messageHub.subscribe("core-player",this.correlationId+".player.*.play",subscriptions.onPlay||function(){});talkify.messageHub.subscribe("core-player",this.correlationId+".player.*.loaded",subscriptions.onItemLoaded||function(){});talkify.messageHub.subscribe("core-player",[this.correlationId+".wordhighlighter.complete",this.correlationId+".player.html5.utterancecomplete"],subscriptions.onItemFinished||function(){});talkify.messageHub.subscribe("core-player",this.correlationId+".player.*.prepareplay",subscriptions.onBeforeItemPlaying||function(){});talkify.messageHub.subscribe("core-player",this.correlationId+".controlcenter.texthighlightoggled",subscriptions.onTextHighligtChanged||function(){});return this};this.playItem=function(item){if(item&&item.isPlaying){if(this.audioSource.paused()){this.audioSource.play()}else{this.audioSource.pause()}}talkify.messageHub.publish(this.correlationId+".player.*.prepareplay",item);item.isLoading=true;item.isPlaying=true;item.element.classList.add("playing");this.playAudio(item)};this.createItems=function(text){var safeMaxQuerystringLength=window.talkify.config.maximumTextLength||1e3;var items=[];if(text.length>safeMaxQuerystringLength){var f=text.substr(0,safeMaxQuerystringLength);items.push(template(f));items=items.concat(this.createItems(text.substr(safeMaxQuerystringLength,text.length-1)));return items}items.push(template(text));return items;function template(t){var element=document.createElement("span");var clone=element.cloneNode(true);return{text:t,preview:t.substr(0,40),element:element,originalElement:clone,isPlaying:false,isLoading:false}}};this.playText=function(text){if(!text){return}var items=this.createItems(text);var currentItem=0;talkify.messageHub.subscribe("core-player.playText",this.correlationId+".player.*.ended",function(){currentItem++;if(currentItem>=items.length){talkify.messageHub.unsubscribe("core.playText",this.correlationId+".player.*.ended");return}this.playItem(items[currentItem])});this.playItem(items[currentItem])};this.paused=function(){return this.audioSource.paused()};this.isPlaying=function(){return this.audioSource.isPlaying()};this.play=function(){this.audioSource.play()};this.pause=function(){this.audioSource.pause();var me=this;if(!me.audioSource.paused()&&me.audioSource.cancel){me.audioSource.cancel(true)}};this.dispose=function(){talkify.messageHub.publish(this.correlationId+".player.tts.disposed");this.audioSource.stop();this.audioSource.dispose();this.wordHighlighter.dispose();talkify.messageHub.unsubscribe("core-player",this.correlationId+".player.*.loaded");talkify.messageHub.unsubscribe("core-player",this.correlationId+".player.*.ended");talkify.messageHub.unsubscribe("core-player",this.correlationId+".controlcenter.texthighlightoggled");talkify.messageHub.unsubscribe("core-player",this.correlationId+".player.*.pause");talkify.messageHub.unsubscribe("core-player",this.correlationId+".player.*.resume");talkify.messageHub.unsubscribe("core-player",this.correlationId+".player.*.play");talkify.messageHub.unsubscribe("core-player",[this.correlationId+".wordhighlighter.complete",this.correlationId+".player.html5.utterancecomplete"]);talkify.messageHub.unsubscribe("core-player",this.correlationId+".player.*.prepareplay");talkify.messageHub.unsubscribe("core-player",this.correlationId+".controlcenter.texthighlightoggled");talkify.messageHub.unsubscribe("core-player",this.correlationId+".controlcenter.request.setvoice")};this.forceLanguage=function(culture){this.settings.lockedLanguage=culture;return this};this.forceVoice=function(voice){this.forcedVoice=voice!==undefined?voice:null;this.settings.lockedLanguage=voice&&(voice.lang||voice.culture)||this.settings.lockedLanguage;talkify.messageHub.publish(this.correlationId+".player.*.voiceset",voice);return this}}},{}],14:[function(require,module,exports){talkify=talkify||{};talkify.TtsPlayer=function(){if(!talkify.config.remoteService.active){throw"This player needs to communicate to a remote service. To enable this player please set flag talkify.config.remoteService.active to true."}var me=this;var audioElement,timeupdater;var currentVoice,currentPitch,currentWordBreak,currentRate;this.currentContext={item:null,positions:[]};this.playbar={instance:null};this.audioSource={play:function(){audioElement.play()},pause:function(){audioElement.pause()},isPlaying:function(){return audioElement.duration>0&&!audioElement.paused},paused:function(){return audioElement.paused},currentTime:function(){return audioElement.currentTime},stop:function(){audioElement.pause();audioElement.currentTime=0},dispose:function(){if(timeupdater){clearInterval(timeupdater)}var existingElement=document.getElementById("talkify-audio");if(existingElement){existingElement.outerHTML=""}talkify.messageHub.unsubscribe("tts-player",me.correlationId+".controlcenter.request.play");talkify.messageHub.unsubscribe("tts-player",me.correlationId+".controlcenter.request.pause");talkify.messageHub.unsubscribe("tts-player",me.correlationId+".controlcenter.request.seek");talkify.messageHub.unsubscribe("tts-player",me.correlationId+".controlcenter.request.volume");talkify.messageHub.unsubscribe("tts-player",me.correlationId+".controlcenter.request.rate");talkify.messageHub.unsubscribe("tts-player",me.correlationId+".controlcenter.request.wordbreak");talkify.messageHub.unsubscribe("tts-player",me.correlationId+".controlcenter.request.pitch");talkify.messageHub.unsubscribe("tts-player",me.correlationId+".controlcenter.request.phonation.normal");talkify.messageHub.unsubscribe("tts-player",me.correlationId+".controlcenter.request.phonation.soft");talkify.messageHub.unsubscribe("tts-player",me.correlationId+".controlcenter.request.phonation.whisper")}};talkify.BasePlayer.call(this,this.audioSource,this.playbar);this.settings.whisper=false;this.settings.soft=false;this.settings.wordbreakms=0;this.settings.volumeDb=0;this.settings.pitch=0;function setupBindings(){audioElement.addEventListener("pause",onPause);audioElement.addEventListener("play",onPlay);audioElement.addEventListener("seeked",onSeek)}function onSeek(){talkify.messageHub.publish(me.correlationId+".player.tts.seeked",{time:this.currentTime,item:me.currentContext.item,positions:me.currentContext.positions});if(me.audioSource.paused()&&me.audioSource.currentTime()>.1){me.audioSource.play()}}function onPause(){if(timeupdater){clearInterval(timeupdater)}talkify.messageHub.publish(me.correlationId+".player.tts.pause")}function onPlay(){if(timeupdater){clearInterval(timeupdater)}timeupdater=setInterval(function(){talkify.messageHub.publish(me.correlationId+".player.tts.timeupdated",{currentTime:audioElement.currentTime,duration:audioElement.duration})},50);if(!me.currentContext.item){talkify.messageHub.publish(me.correlationId+".player.tts.unplayable");me.audioSource.pause()}if(!me.currentContext.positions.length){talkify.messageHub.publish(me.correlationId+".player.tts.play",{item:me.currentContext.item,positions:[],currentTime:me.audioSource.currentTime()});return}if(me.audioSource.currentTime()>.1){talkify.messageHub.publish(me.correlationId+".player.tts.resume",{currentTime:me.audioSource.currentTime()})}else{var interval=setInterval(function(){if(me.audioSource.currentTime()>0){clearInterval(interval);talkify.messageHub.publish(me.correlationId+".player.tts.play",{item:me.currentContext.item,positions:me.currentContext.positions,currentTime:me.audioSource.currentTime()})}},20)}}function initialize(){if(timeupdater){clearInterval(timeupdater)}audioElement=null;var existingElement=document.getElementById("talkify-audio");if(existingElement){existingElement.outerHTML=""}var mp3Source=document.createElement("source");var wavSource=document.createElement("source");audioElement=document.createElement("audio");audioElement.appendChild(mp3Source);audioElement.appendChild(wavSource);mp3Source.type="audio/mpeg";wavSource.type="audio/wav";audioElement.id="talkify-audio";audioElement.controls=talkify.config.ui.audioControls.enabled&&talkify.config.ui.audioControls.controlcenter==="native";audioElement.autoplay=false;(talkify.config.ui.audioControls.container||document.body).appendChild(audioElement);var clonedAudio=audioElement.cloneNode(true);audioElement.parentNode.replaceChild(clonedAudio,audioElement);audioElement=clonedAudio;talkify.messageHub.subscribe("tts-player",me.correlationId+".controlcenter.request.play",function(){me.play()});talkify.messageHub.subscribe("tts-player",me.correlationId+".controlcenter.request.pause",function(){audioElement.pause()});talkify.messageHub.subscribe("tts-player",me.correlationId+".controlcenter.request.seek",function(position){var pos=audioElement.duration*position;if(isNaN(audioElement.duration)){return}audioElement.currentTime=pos});talkify.messageHub.subscribe("tts-player",me.correlationId+".controlcenter.request.volume",function(volume){audioElement.volume=volume/10});talkify.messageHub.subscribe("tts-player",me.correlationId+".controlcenter.request.rate",function(rate){me.settings.rate=rate;talkify.messageHub.publish(me.correlationId+".player.tts.ratechanged",me.settings.rate)});talkify.messageHub.subscribe("tts-player",me.correlationId+".controlcenter.request.wordbreak",function(ms){me.useWordBreak(ms)});talkify.messageHub.subscribe("tts-player",me.correlationId+".controlcenter.request.pitch",function(value){me.usePitch(value)});talkify.messageHub.subscribe("tts-player",me.correlationId+".controlcenter.request.phonation.soft",function(){me.normalTone();me.usePhonation("soft")});talkify.messageHub.subscribe("tts-player",me.correlationId+".controlcenter.request.phonation.normal",function(){me.normalTone();me.usePhonation("normal")});talkify.messageHub.subscribe("tts-player",me.correlationId+".controlcenter.request.phonation.whisper",function(){me.usePhonation("normal");me.whisper()});if(me.playbar.instance){me.playbar.instance.setMinRate(-5).setMaxRate(5)}}function getPositions(requestId){var p=new promise.promise.Promise;talkify.http.get(talkify.config.remoteService.speechBaseUrl+"/marks?id="+requestId).then(function(error,positions){p.done(null,positions)});return p}initialize.apply(this);this.playAudio=function(item){talkify.messageHub.publish(me.correlationId+".player.tts.loading",item);me.currentContext.item=item;me.currentContext.positions=[];audioElement.onloadeddata=null;audioElement.onended=null;var sources=audioElement.getElementsByTagName("source");var textType=talkify.config.useSsml&&item.ssml?"ssml":"text";var textToPlay=textType==="ssml"?encodeURIComponent(item.ssml.replace(/\n/g," ")):encodeURIComponent(item.text.replace(/\n/g," "));var voice=item.voice||(this.forcedVoice?this.forcedVoice.name:"");if(voice!==currentVoice){talkify.messageHub.publish(this.correlationId+".player.tts.voiceset",{name:voice});currentVoice=voice}var pitch=item.pitch||this.settings.pitch;if(pitch!==currentPitch){talkify.messageHub.publish(me.correlationId+".player.tts.pitchchanged",pitch);currentPitch=pitch}var wordbreak=item.wordbreakms||this.settings.wordbreakms;if(wordbreak!==currentWordBreak){talkify.messageHub.publish(me.correlationId+".player.tts.wordbreakchanged",wordbreak);currentWordBreak=wordbreak}var rate=item.rate||this.settings.rate;if(rate!==currentRate){talkify.messageHub.publish(me.correlationId+".player.tts.ratechanged",rate);currentRate=rate}var requestId=talkify.generateGuid();var audioUrl=talkify.config.remoteService.host+talkify.config.remoteService.speechBaseUrl+"?texttype="+textType+"&text="+textToPlay+"&fallbackLanguage="+this.settings.referenceLanguage.Language+"&voice="+voice+"&rate="+rate+"&key="+talkify.config.remoteService.apiKey+"&whisper="+(item.whisper||this.settings.whisper)+"&soft="+(item.soft||this.settings.soft)+"&wordbreakms="+wordbreak+"&volume="+this.settings.volumeDb+"&pitch="+pitch;if(me.settings.useTextHighlight){audioUrl+="&marksid="+requestId}sources[0].src=audioUrl+"&format=mp3";sources[1].src=audioUrl+"&format=wav";sources[1].onerror=function(e){talkify.messageHub.publish(me.correlationId+".player.tts.error",null)};audioElement.load();audioElement.onloadeddata=function(){me.audioSource.pause();if(!me.settings.useTextHighlight){talkify.messageHub.publish(me.correlationId+".player.tts.loaded",me.currentContext.item);me.audioSource.play();return}getPositions(requestId).then(function(error,positions){me.currentContext.positions=positions||[];talkify.messageHub.publish(me.correlationId+".player.tts.loaded",me.currentContext.item);me.audioSource.play()})};audioElement.onended=function(){talkify.messageHub.publish(me.correlationId+".player.tts.ended",item)}};this.usePhonation=function(phonation){this.settings.soft=phonation==="soft";talkify.messageHub.publish(me.correlationId+".player.tts.phonationchanged",phonation);return this};this.whisper=function(){this.settings.whisper=true;talkify.messageHub.publish(me.correlationId+".player.tts.whisperchanged",true);return this};this.normalTone=function(){this.settings.whisper=false;talkify.messageHub.publish(me.correlationId+".player.tts.whisperchanged",false);return this};this.useWordBreak=function(ms){this.settings.wordbreakms=Math.max(0,ms);talkify.messageHub.publish(me.correlationId+".player.tts.wordbreakchanged",this.settings.wordbreakms);return this};this.useVolumeBaseline=function(volumeDb){this.settings.volumeDb=volumeDb;talkify.messageHub.publish(me.correlationId+".player.tts.volumechanged",volumeDb);return this};this.usePitch=function(pitch){this.settings.pitch=pitch;talkify.messageHub.publish(me.correlationId+".player.tts.pitchchanged",pitch);return this};setupBindings()};talkify.TtsPlayer.prototype.constructor=talkify.TtsPlayer},{}],15:[function(require,module,exports){talkify=talkify||{};talkify.playlist=function(){var defaults={useGui:false,useTextInteraction:false,domElements:[],exclusions:[],rootSelector:"body",events:{onEnded:null,onVoiceCommandListeningStarted:null,onVoiceCommandListeningEnded:null}};var s=JSON.parse(JSON.stringify(defaults));var p=null;function isSupported(){var a=document.createElement("audio");return typeof a.canPlayType==="function"&&(a.canPlayType("audio/mpeg")!==""||a.canPlayType("audio/wav")!=="")}function implementation(_settings,player){var textextractor=new talkify.textextractor;var playlist={queue:[],currentlyPlaying:null,refrenceText:"",referenceLanguage:{Culture:"",Language:-1}};var settings=_settings;var playerHasBeenReplaced=false;var commands=[new talkify.KeyboardCommands(talkify.config.keyboardCommands),new talkify.SpeechCommands(talkify.config.voiceCommands)];var voiceCommands=commands[1];for(var k=0;ksafeMaxQuerystringLength){var chuncks=getSafeTextChunks(text,safeMaxQuerystringLength);element.innerHTML="";for(var i=0;i-1?breakAt:text.substr(0,safeMaxQuerystringLength).lastIndexOf("。");breakAt=breakAt>-1?breakAt:safeMaxQuerystringLength;return text.substr(0,breakAt+1)}function play(item){if(!item){if(playlist.queue.length===0){return}playFromBeginning();return}playItem(item)}function pause(){player.pause()}function setupItemForUserInteraction(item){item.element.style.cursor="pointer";item.element.classList.add("talkify-highlight");removeEventListeners("click",item.element);addEventListener("click",item.element,textInteractionEventListener);function textInteractionEventListener(){play(item)}}function removeUserInteractionForItem(item){item.element.style.cursor="inherit";item.element.classList.remove("talkify-highlight");removeEventListeners("click",item.element)}function initialize(){reset();if(!settings.domElements||settings.domElements.length===0){settings.domElements=textextractor.extract(settings.rootSelector,settings.exclusions)}for(var i=0;iplaylist.refrenceText.length){playlist.refrenceText=text}}if(settings.useTextInteraction){for(var j=0;j0){var isSameAsPrevious=item.element===playlist.queue[j-1].element;if(isSameAsPrevious){continue}}setupItemForUserInteraction(item)}}talkify.messageHub.publish(player.correlationId+".playlist.loaded");if(settings.useTextInteraction){talkify.messageHub.publish(player.correlationId+".playlist.textinteraction.enabled")}else{talkify.messageHub.publish(player.correlationId+".playlist.textinteraction.disabled")}}function convertToSsml(element){if(!talkify.config.useSsml){return null}var ssmlMappings={h1:{start:'###emphasis level="strong">',end:"###/emphasis>",trim:false},h2:{start:'###emphasis level="strong">',end:"###/emphasis>",trim:false},h3:{start:'###emphasis level="strong">',end:"###/emphasis>",trim:false},b:{start:'###emphasis level="strong">',end:"###/emphasis>",trim:false},strong:{start:'###emphasis level="strong">',end:"###/emphasis>",trim:false},em:{start:'###emphasis level="strong">',end:"###/emphasis>",trim:false},i:{start:'###emphasis level="reduced">',end:"###/emphasis>",trim:false},br:{start:'###break strength="x-strong">###/break>',end:"",trim:true}};var htmlEntities={};htmlEntities[" "]=" ";htmlEntities["<"]="<";htmlEntities[">"]=">";htmlEntities["&qout;"]='"';htmlEntities["'"]="'";htmlEntities["&"]="&";var ssml=element.innerHTML.replace(/ +/g," ").replace(/(\r\n|\n|\r)/gm,"").trim();for(var key in htmlEntities){ssml=ssml.replace(new RegExp(key,"g"),htmlEntities[key])}for(var key in ssmlMappings){var mapping=ssmlMappings[key];var startTagMatches=ssml.match(new RegExp("<"+key+"+(>|.*?[^?]>)","gi"))||[];for(var j=0;j"&&startTagMatches[j].indexOf("<"+key+" ")!==0){continue}ssml=ssml.replace(startTagMatches[j],mapping.start);if(mapping.trim){ssml=ssml.split(mapping.start).map(function(x){return x.trim()}).join(mapping.start)}}ssml=ssml.split("").map(function(x,i){return mapping.trim?x.trim():x}).join(mapping.end)}ssml=ssml.replace(/<[^>]*>?/gm,"");ssml=ssml.replace(/\s+/g," ");ssml=ssml.split("###").join("<");return ssml}function getNextItem(){var currentQueuePosition=playlist.queue.indexOf(playlist.currentlyPlaying);if(currentQueuePosition===playlist.queue.length-1){return null}return playlist.queue[currentQueuePosition+1]}function getPreviousItem(){var currentQueuePosition=playlist.queue.indexOf(playlist.currentlyPlaying);if(currentQueuePosition===0){return null}return playlist.queue[currentQueuePosition-1]}function playFromBeginning(){if(!talkify.config.remoteService.active){onComplete({Cultures:[],Language:-1});return}var text=playlist.refrenceText.length<=1e3?playlist.refrenceText:playlist.refrenceText.substr(0,1e3);talkify.http.get(talkify.config.remoteService.languageBaseUrl+"/detect?text="+text).then(function(error,data){if(error){onComplete({Cultures:[],Language:-1});return}onComplete(data)});function onComplete(refLang){playlist.referenceLanguage={Culture:refLang.Cultures[0],Language:refLang.Language};player.withReferenceLanguage(playlist.referenceLanguage);playItem(playlist.queue[0])}}function insertElement(element){var items=[];var text=element.innerText;if(text.trim()===""){return items}if(domElementExistsInQueue(element)){return items}var documentPositionFollowing=4;for(var j=0;j-1})[0];if(match){possibleMatches.push(key);break}}}if(possibleMatches.length>0){var bestValue=0;var bestCommand=null;for(var j=0;jbestValue){bestValue=temp;bestCommand=possibleMatches[j]}}return bestCommand}return null}function levenshtein(s1,s2){var longer=s1;var shorter=s2;if(s1.length0){var newValue=costs[j-1];if(s1.charAt(i-1)!=s2.charAt(j-1))newValue=Math.min(Math.min(newValue,lastValue),costs[j])+1;costs[j-1]=lastValue;lastValue=newValue}}}if(i>0)costs[s2.length]=lastValue}return costs[s2.length]}if(speechCommandConfig.keyboardActivation.enabled){document.addEventListener("keyup",function(e){if(!e.ctrlKey){return}if(isListening){return}var key=e.keyCode?e.keyCode:e.which;if(key===speechCommandConfig.keyboardActivation.key){recognition.start()}})}return{onPrevious:function(callback){onPreviousCallback=callback},onNext:function(callback){onNextCallback=callback},onPlayPause:function(callback){onPlayPauseCallback=callback},start:function(){if(isListening){return}recognition.start()},onListeningStarted:function(callback){onListeningStartedCallback=callback},onListeningEnded:function(callback){onListeningEndedCallback=callback},dispose:function(){}}}},{}],17:[function(require,module,exports){talkify=talkify||{};talkify.textextractor=function(){var validElements=[];var inlineElements=["a","span","b","big","i","small","tt","abbr","acronym","cite","code","dfn","em","kbd","strong","samp","var","a","bdo","q","sub","sup","label"];var forbiddenElementsString=["img","map","object","script","button","input","select","textarea","style","code","nav","#nav","#navigation",".nav",".navigation","footer","rp","rt"];var userExcludedElements=[];function getVisible(elements){var result=[];for(var j=0;j=10}return false}function isValidAnchor(node){var nrOfSiblings=getSiblings(node);if(nrOfSiblings.length>=1){return true}var previous=node.previousSibling;if(isValidTextNode(previous)){return true}if(isValidTextNode(node.nextSibling)){return true}return false}function isValidForGrouping(node){if(node.nodeName==="BR"){return true}var isTextNode=node.nodeType===3;var textLength=getStrippedText(node.textContent).length;return isTextNode&&textLength>=2||!isForbidden(node)&&elementIsInlineElement(node)}function getConnectedElements(nodes,firstIndex){var connectedElements=[];for(var l=firstIndex;l1){var wrapping=group(connectedElements);var isAboveThreshold=getStrippedText(wrapping.innerText).length>=20;if(isAboveThreshold){nodes[i].parentNode.replaceChild(wrapping,nodes[i]);for(var j=0;j "+generateExcludesFromForbiddenElements());for(var i=0;i=position&&time<=currentPositions[i+1].Position){currentPos=i;break}}if(currentPosition===currentPos){return}currentPosition=currentPos;highlight(currentItem,currentPositions[currentPos].Word,currentPositions[currentPos].CharPosition)});function adjustPositionsToSsml(text,positions){var internalPos=JSON.parse(JSON.stringify(positions));var lastFound=0;for(var i=0;i'+text.substring(sentence.start,charPosition)+''+text.substring(charPosition,charPosition+word.length)+""+text.substring(charPosition+word.length,sentence.end)+""+text.substring(sentence.end)}function cancel(){resetCurrentItem();currentPositions=[]}function setupWordHightlighting(item,positions,startFrom){cancel();if(!positions.length){return}if(item.ssml||item.wordbreakms||currentWordbreakMs){currentPositions=adjustPositionsToSsml(item.text,positions)}else{currentPositions=positions}var i=startFrom||0;var internalCallback=function(){currentItem=item;i++;if(i>=positions.length){window.setTimeout(function(){item.element.innerHTML=item.originalElement.innerHTML;talkify.messageHub.publish(correlationId+".wordhighlighter.complete",item)},1e3);return}};internalCallback()}function resetCurrentItem(){if(currentItem){currentItem.element.innerHTML=currentItem.originalElement.innerHTML}}function setPosition(message){var diff=0;var timeInMs=message.time*1e3;var nextPosition=0;for(var i=0;i=charactersTraversed&&charPosition<=charactersTraversed+result[i].length){if(charactersTraversed>0){sentenceStart=charactersTraversed+1}sentenceEnd=charactersTraversed+result[i].length;break}charactersTraversed+=result[i].length}return{start:sentenceStart,end:sentenceEnd}}function dispose(){talkify.messageHub.unsubscribe("word-highlighter",correlationId+".player.tts.seeked");talkify.messageHub.unsubscribe("word-highlighter",[correlationId+".player.tts.loading",correlationId+".player.tts.disposed"]);talkify.messageHub.unsubscribe("word-highlighter",correlationId+".player.tts.play");talkify.messageHub.unsubscribe("word-highlighter",correlationId+".player.tts.timeupdated")}return{start:setupWordHightlighting,highlight:highlight,dispose:dispose}}},{}],20:[function(require,module,exports){talkify={}},{}]},{},[1]); diff --git a/examples/control-center.html b/examples/control-center.html index 9cedc29..7c3445b 100644 --- a/examples/control-center.html +++ b/examples/control-center.html @@ -35,7 +35,7 @@ talkify.config.keyboardCommands.enabled = true; talkify.config.voiceCommands.enabled = true; - talkify.config.remoteService.speechBaseUrl = '/api/speech/v1'; + talkify.config.remoteService.speechBaseUrl = '/api/speech/v2'; talkify.config.remoteService.languageBaseUrl = '/api/language/v1'; talkify.config.remoteService.apiKey = ''; diff --git a/package.json b/package.json index ad430d4..84fe9fe 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "talkify-tts", - "version": "3.2.2", + "version": "3.3.0", "description": "A JavaScript text to speech (TTS) library. Provides you with high quality TTS voices in many languages and a high quality language. These voices and engines runs on a Talkify hosted server. This lib also supports browser built in voices via the SpeechSynthesis API if you rather not rely on Talkify servers.", "browser": "dist/talkify.min.js", "files": ["dist/styles/**/*.css"], diff --git a/src/control-centers/talkify-controlcenter-core.js b/src/control-centers/talkify-controlcenter-core.js index 79fa20b..738810b 100644 --- a/src/control-centers/talkify-controlcenter-core.js +++ b/src/control-centers/talkify-controlcenter-core.js @@ -529,6 +529,10 @@ talkify.playbar = function (parent, correlationId) { return true; } + if (filter.byClass.indexOf("Neural") !== -1 && voice.isNeural) { + return true; + } + return false; } diff --git a/src/talkify-config.js b/src/talkify-config.js index 53054f4..9b1f255 100644 --- a/src/talkify-config.js +++ b/src/talkify-config.js @@ -32,7 +32,7 @@ talkify.config = { active: true, host: 'https://talkify.net', apiKey: '', - speechBaseUrl: '/api/speech/v1', + speechBaseUrl: '/api/speech/v2', languageBaseUrl: '/api/language/v1' }, keyboardCommands: {