Skip to content

Instantly share code, notes, and snippets.

@Ser-Gen
Created February 14, 2016 12:02
Show Gist options
  • Save Ser-Gen/cd4fc1fc825090016077 to your computer and use it in GitHub Desktop.
Save Ser-Gen/cd4fc1fc825090016077 to your computer and use it in GitHub Desktop.
Генератор речи
speaker.say('Как у вас дела?').then(speaker.say('У меня норм, например.'));
var speaker = (function () {
var speechUtteranceChunker = function (utt, settings, callback) {
settings = settings || {};
var chunkLength = settings.chunkLength || 160;
var pattRegex = new RegExp('^.{' + Math.floor(chunkLength / 2) + ',' + chunkLength + '}[\.\!\?\,]{1}|^.{1,' + chunkLength + '}$|^.{1,' + chunkLength + '} ');
var txt = (settings.offset !== undefined ? utt.text.substring(settings.offset) : utt.text);
var chunkArr = txt.match(pattRegex);
if (chunkArr[0] !== undefined && chunkArr[0].length > 2) {
var chunk = chunkArr[0];
var newUtt = new SpeechSynthesisUtterance(chunk);
for (x in utt) {
if (utt.hasOwnProperty(x) && x !== 'text') {
newUtt[x] = utt[x];
};
};
newUtt.onend = function () {
settings.offset = settings.offset || 0;
settings.offset += chunk.length - 1;
speechUtteranceChunker(utt, settings, callback);
};
setTimeout(function () {
speechSynthesis.speak(newUtt);
}, 0);
}
else {
if (callback !== undefined) {
callback();
};
};
};
function say (text) {
return new Promise(function(resolve, reject) {
var utterance = new SpeechSynthesisUtterance(text);
var voiceArr = speechSynthesis.getVoices();
utterance.voice = voiceArr[2];
speechUtteranceChunker(utterance, {
chunkLength: 120
}, resolve);
});
};
return {
say: say
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment