본문 바로가기
FRONT-END/JAVASCRIPT

[JS] SpeechSynthesisUtterance API

by 썬키 2023. 4. 2.
 

SpeechSynthesisUtterance - Web APIs | MDN

The SpeechSynthesisUtterance interface of the Web Speech API represents a speech request. It contains the content the speech service should read and information about how to read it (e.g. language, pitch and volume.)

developer.mozilla.org

API에 대한 자세한 설명은 위의 링크에서 확인할 수 있습니다.

 

 

SpeechSynthesisUtterance API 란?

 

해당 API는 웹 브라우저가 기본적으로 제공하는 API인데,

이 API를 사용하면 input 태그에 입력된 텍스트를 컴퓨터가 음성으로 출력하는 기능을 제공할 수 있다.

 

GOAL

 

SpeechSynthesisUtterance API 의 사용법에 대해 이해할 수 있다.

 

웹 브라우저에 위와 같이 텍스트를 입력하고, 음성 듣기 버튼을 누르면 음성이 출력되는 UI가 있다고 가정하자.

 

 

1. SpeechSynthesisUtterance API의 사용법

 

필자는 React 라이브러리를 이용하여 해당 API를 활용했다.

 

const [text, setText] = useState();

const pitch = 10;
const rate = 1;

 

입력된 텍스트의 값을 저장하기 위한 text라는 state변수를 생성한다.

상수값인 pitch와 rate는 음성 합성에 필요한 속성을 설정한 부분이다.

그 외에도 lang, text, voice, volume에 대한 값을 설정할 수 있다.

 

출처 : MDN

 

async function populateVoiceList(synth) {
	try {
        const voices = await synth.getVoices().sort(function (a, b) {
            const aname = a.name.toUpperCase();
            const bname = b.name.toUpperCase();
            if (aname < bname) return -1;
            else if (aname === bname) return 0;
            else return +1;
        });
		return voices;
	} catch (error) {
		throw new Error("Failure retrieving voices");
	}
}

 

populateVoiceList 함수는 speechSynthesis 객체의 getVoices 메소드를 사용하여

사용 가능한 음성 목록을 가져오고, 이름을 기준으로 정렬하여 반환하는 함수이다.

 

async function speak(textToRead, synth) {
	if (speechSynthesis.onvoiceschanged !== undefined) {
		speechSynthesis.onvoiceschanged = () => populateVoiceList
	}

	if (synth.speaking) {
		console.error("speechSynthesis.speaking")
		return
	}
    
	if (textToRead !== "") {
		const utterThis = new SpeechSynthesisUtterance(textToRead)
		utterThis.onend = function (event) {
		}
		utterThis.onerror = function (event) {
			console.error("SpeechSynthesisUtterance.onerror")
		}
        // utterThis.voice = voices[0]
        utterThis.pitch = pitch
        utterThis.rate = rate
        synth.speak(utterThis)
	}
}

 

speak 함수는 extToRead 매개변수에 전달된 텍스트를 음성으로 변환하여 출력하는 함수이다.

 

첫번째 if문은 브라우저에서 음성 합성 기능을 사용할 수 있는지 확인하는 조건문이다.

이벤트 리스너를 설정하여 음성 합성기가 음성 데이터를 제공할 때마다 호출되는

onvoicesChange 이벤트가 정의되어 있는 경우에만, populateVoiceList 함수를 호출한다.

 

두번째 if문은 현재 음성 합성기가 음성 출력 중인지를 확인하는 조건문이다.

이미 출력 중이면 함수를 빠져 나간다.

 

세번째 if문은 음성으로 출력할 텍스트가 있는지를 확인하는 조건문이다.

텍스트가 존재한다면 새로운 speechSynthesisUtterance 객체를 생성하여 매개변수로 전달된 텍스트를 출력한다.

 

function btnClick(){
	speechSynthesis.cancel();
	speak(text, window.speechSynthesis);
}

return (
	<div align="center">
		<br />
		<input size="50" value={text} onChange={(e)=>setText(e.target.value)} placeholder="음성으로 변환할 텍스트를 입력해주세요" />&nbsp;
		<button onClick={btnClick}>음성듣기</button>
	</div>
);

 

버튼을 클릭하면 입력된 텍스트를 음성으로 변환하고 출력하게 된다.

 

마치며

 

학원에서는 그냥 이런게 있다 라는 정도로만 알려줬었는데

함수 하나하나를 살펴보며 정리해보니 어느정도 이해가 되는 코드였다.

텍스트를 입력하면 파일로 저장되는 것보다 바로 출력되는 이 API가 훨씬 효율적인듯 하다.

댓글