공유/JavaScript, TypeScript
[JS/TS] TTS, Text to Speech 구현하기
구하천포
2024. 8. 2. 12:30
JavaScript(TypeScript)를 이용하여 Text를 Voice로 변환하는 방법을 알아보도록 하겠습니다.
다른 라이브러리를 사용하지 않고 구현이 가능합니다.
코드는 TypeScript로 구현하겠습니다.
TTS 구현
const onSpeakToText = (text: string) => {
const utterance = new SpeechSynthesisUtterance(text);
utterance.lang = 'ko-KR';
window.speechSynthesis.speak(utterance);
}
text를 한국어로 읽어주는 함수를 구현하였습니다.
TTS 속도 조절하기
읽는 속도를 빠르게 또는 느리게 조절도 가능합니다.
const onSpeakToText = (text: string, rate: number) => {
const utterance = new SpeechSynthesisUtterance(text);
utterance.lang = 'ko-KR';
utterance.rate = rate;
window.speechSynthesis.speak(utterance);
}
위 rate 값을 1미만으로 주면 느리게, 1초과로 주면 빠르게 읽어줍니다.
TTS 다른 언어 사용하기
한국어 외 다른 언어로 텍스트를 읽도록 할 수 있습니다.
현재 함수에는 lang 값이 'ko-KR'로 고정이 되어 있는데 이 값을 변경해주면 됩니다.
어떠한 값을 넣을 수 있는 지 확인하는 방법은 간단합니다.
const synth = window.speechSynthesis;
console.log(synth.getVoices())
위 코드를 실행하면 실행 가능한 voices를 얻을 수 있습니다.
여기에 있는 lang 값을 확인하여 넣으시면 됩니다.
const onSpeakToText = (text: string, rate: number, lang: string) => {
const utterance = new SpeechSynthesisUtterance(text);
utterance.lang = lang;
utterance.rate = rate;
window.speechSynthesis.speak(utterance);
}
결론
간단하게 text를 읽어주는 onSpeakToText 함수를 구현해보았습니다.
라이브러리를 사용하지 않고 쉽게 구현이 가능합니다.
위에서 최종적으로 구현한 함수는 확장성이 없습니다. 실제로 사용하실 때는 함수 오버로딩을 이용하여 여러 args를 받을 수 있도록 수정하면 좋을 것 같습니다.
반응형