Last active
July 19, 2023 12:52
-
-
Save luislobo9b/8e9be6e93302b60b39d80d7bf841e78c to your computer and use it in GitHub Desktop.
speak.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// speak.js v1 | |
function speak(speakObj) { | |
const utterance = new window.SpeechSynthesisUtterance() | |
utterance.volume = 1 | |
utterance.rate = 1 | |
utterance.pitch = 1 | |
if (speakObj.voice && voice.lang) { | |
utterance.lang = voice.lang | |
} | |
for (prop in speakObj) { | |
utterance[prop] = speakObj[prop] | |
} | |
window.speechSynthesis.speak(utterance) | |
} | |
function selectVoices(voices, filterList, preferredList = []) { | |
if (filterList) { | |
voices = voices.filter(voice => { | |
for (const word of filterList) { | |
if (voice.name.includes(word)) { | |
return true | |
} | |
} | |
return false | |
}) | |
} | |
if (preferredList) { | |
voices = voices.sort((a, b) => { | |
return _sort(a) > _sort(b) ? 1 : -1 | |
}) | |
} | |
return voices | |
function _sort({ | |
name: voiceName | |
}) { | |
for (let i = 0; i < preferredList.length; i++) { | |
const wantedVoiceName = preferredList[i] | |
if (voiceName.includes(wantedVoiceName)) { | |
return i | |
} | |
} | |
return preferredList.length | |
} | |
} | |
async function getVoices(delay = 1000) { | |
return new Promise(resolve => { | |
const interval = setInterval(() => { | |
if (window.speechSynthesis && typeof(window.speechSynthesis.getVoices) === 'function') { | |
const voices = window.speechSynthesis.getVoices() | |
if (voices && voices.length) { | |
const lastVoice = voices[voices.length - 1] | |
if (typeof(lastVoice.name) === 'string' && lastVoice.name.length > 0) { | |
clearInterval(interval) | |
setTimeout(() => { | |
resolve(voices) | |
}, delay) | |
} | |
} | |
} | |
}, 10) | |
}) | |
} | |
// example of use: | |
const allVoices = await getVoices() | |
let voices = selectVoices(allVoices, ['Brazil', 'Brasil'], [ | |
'Francisca', // edge | |
'Antonio', // edge | |
'Daniel', | |
'Maria' | |
]) | |
let voice = voices[0] | |
speak({ | |
text: `Olá mundo, o nome da minha voz é: ${voice.name}`, | |
voice, | |
rate: 1, | |
volume: 1, | |
pitch: 1 | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment