Speech Synthesis
const msg = new SpeechSynthesisUtterance();// ๊ฐ์ฒด ์ ์ธ (๋ธ๋ผ์ฐ์ ์ ๋ด์ฅ ๋์ด์๋ ์ฃผ์ด์ง ํ
์คํธ๋ฅผ ์๋ฆฌ๋ก ๋ฐ๊ฟ์ฃผ๋ TTS API)
let voices = [];
const voicesDropdown = document.querySelector('[name="voice"]');
const options = document.querySelectorAll('[type="range"], [name="text"]');
const speakButton = document.querySelector('#speak');
const stopButton = document.querySelector('#stop');
msg.text = document.querySelector('[name="text"]').value;
function populateVoices() {
voices = this.getVoices();
voicesDropdown.innerHTML = voices
.filter(voice => voice.lang.includes('ko'))
.map(voice => `<option value="${voice.name}">${voice.name} (${voice.lang})</option>`)
.join(''); // ์ต์
์์ฑ
}
function setVoice() {
msg.voice - voices.find(voice => voice.name === this.valye);
toggle();
}
/*์๋ฆฌ๋ฅผ ์ค์ ์ด๋ฒคํธ๋ฅผ ๋ชฉ์๋ฆฌ๋ฅผ ์ค์ ํ๋ ํจ์
TTS ์ ๋ณด๋ฅผ ๊ด๋ฆฌํ๋ msg ๊ฐ์ฒด์ voice ๊ฐ์ ๋ฐ๊ฟ์ค ํ ์ง์ ์์ฑํ toggle() ํจ์๋ก ๋ชฉ์๋ฆฌ๋ฅผ ๋ค์ ์ฌ์ํ๋ค. */
function toggle(startOver = true) {
speechSynthesis.cancel();
if(startOver){
speechSynthesis.speak(msg);
}
}
/* ์์ฑ์ ์ฌ์ํ๋ toggle() ์์ฑ ์ธ์๋ก startOver๋ฅผ ๋๊ธฐ๊ณ , ๊ธฐ๋ณธ ์ค์ ์ธ์์ธ true์ธ ๊ฒฝ์ฐ
์ด์ ์์ฑ์ ์ทจ์ํ๊ณ ์๋ก์ด ์์ฑ์ ์ฌ์ํ๋ฉฐ, false๋ฅผ ์ธ์๋ก ์ฃผ๋ฉด ์์ฑ๋ง ์ทจ์ํ๋ค. */
function setOption(){
console.log(this.name, this.value);
msg[this.name] = this.value;
toggle();
}
/* ๋ค๋ฅธ ์ค์ ์ ๋ฐ๊ฟ ์ ์๋ setOption() ์์ฑํ๊ธฐ
input ๊ฐ์ฒด์ name์ ๋ณ๊ฒฝํ ์์ฑ์ ์ด๋ฆ๊ณผ ์ผ์น์ํค๋ฉด input ๊ฐ์ฒด์ value๋ก ๋ณ๋๋ก ์ต์
์ ๊ตฌ๋ณํ์ฌ ์์ฑํ ํ์์์ด ํ๋ฒ์ ์ฌ์ฉํ ์ ์๋ค.*/
// -> ํจ์๋ค์ ์ด๋ฒคํธ๋ก ๊ฑธ์ด์ค๋ค.
speechSynthesis.addEventListener('voiceschanged', populateVoices);
voicesDropdown.addEventListener('change', setVoice);
options.forEach(option => option.addEventListener('change', setOption)); // ์ต์
์ด ๋ณ๊ฒฝ๋ ๋ ๋ง๋ค ์คํ
speakButton.addEventListener('click', toggle);
stopButton.addEventListener('click', ()=> toggle(false));
Last updated
Was this helpful?