컴포넌트가 언마운트 되었을 때 = useEffect 내 return 정리 함수이므로, useEffect훅을 사용해야 한다. 이는 커스텀 훅에서만 사용할 수 있다.
startSpeech, pauseSpeech함수를 리턴한다.
window.speechSynthesis를 사용한다.
<aside> 💡 window.speechSynthesis
: SpeechSynthesis 객체를 리턴하는 window 객체
const synthRef = React.useRef<SpeechSynthesis>(window.speechSynthesis);
const utteranceRef = React.useRef<SpeechSynthesisUtterance | null>(null);
utterranceRef도 synthRef처럼, useRef 인자에 값을 넘겨서 생성할 수 있다. 이러한 경우 props로 오디오 재생에 필요한 데이터를 넘겨주면 된다. 하지만, 우리는 startSpeech함수를 실행할 때 content같은 데이터를 보내줄 것이기에, 여기서는 null로 선언한다.
<aside> 💡 SpeechSynthesis, SpeechSynthesisUtterance 객체
SpeechSynthesis는 위에서 설명한, Web Speech API를 사용할 수 있게 해주는 객체이다. 이 객체를 이용해서 오디오를 실행, 중단 등 오디오에 대한 제어를 할 것이다.
SpeechSynthesisUtterance객체는 언어, 속도, 내용, 목소리, 볼륨 등 스피치 요청에 대한 정보를 담은 객체이다.
</aside>
startSpeech
const startSpeech = (text: string) => {
utteranceRef.current = new SpeechSynthesisUtterance(text);
synthRef.current.speak(utteranceRef.current);
};
text를 인자로 전달받아, 스피치 요청에 대한 정보를 담는 SpeechSynthesisUtterance객체를 만든다. 이 SpeechSynthesisUtterance객체를 SpeechSynthesis.speak() 메서드에 전달한다.
pauseSpeech
const pauseSpeech = () => {
synthRef.current.pause();
};