diff --git a/docs/useSpeech.md b/docs/useSpeech.md index f94628fe09..fa77e6995a 100644 --- a/docs/useSpeech.md +++ b/docs/useSpeech.md @@ -8,8 +8,10 @@ React UI hook that synthesizes human voice that speaks a given string. ```jsx import {useSpeech} from 'react-use'; +const voices = window.speechSynthesis.getVoices(); + const Demo = () => { - const state = useSpeech('Hello world!'); + const state = useSpeech('Hello world!', { rate: 0.8, pitch: 0.5, voice: voices[0] }); return (
diff --git a/src/__stories__/useSpeech.story.tsx b/src/__stories__/useSpeech.story.tsx index 2d2f1e80dd..6dd02e0584 100644 --- a/src/__stories__/useSpeech.story.tsx +++ b/src/__stories__/useSpeech.story.tsx @@ -3,8 +3,10 @@ import * as React from 'react'; import { useSpeech } from '..'; import ShowDocs from './util/ShowDocs'; +const voices = window.speechSynthesis.getVoices(); + const Demo = () => { - const state = useSpeech('Hello world!'); + const state = useSpeech('Hello world!', { rate: 0.8, pitch: 0.5, voice: voices[0] }); return{JSON.stringify(state, null, 2)}; }; diff --git a/src/useSpeech.ts b/src/useSpeech.ts index c04c5d4325..05b980afba 100644 --- a/src/useSpeech.ts +++ b/src/useSpeech.ts @@ -4,22 +4,30 @@ import useSetState from './useSetState'; export interface SpeechState { isPlaying: boolean; + lang: string; + voice: SpeechSynthesisVoice; rate: number; + pitch: number; volume: number; } export interface SpeechOptions { - lang?: any; - pitch?: number; + lang?: string; + voice?: SpeechSynthesisVoice; rate?: number; - voice?: any; + pitch?: number; volume?: number; } +const voices = window.speechSynthesis.getVoices(); + const useSpeech = (text: string, opts: SpeechOptions = {}): SpeechState => { const [state, setState] = useSetState({ isPlaying: false, + lang: opts.lang || 'default', + voice: opts.voice || voices[0], rate: opts.rate || 1, + pitch: opts.pitch || 1, volume: opts.volume || 1, }); @@ -27,7 +35,10 @@ const useSpeech = (text: string, opts: SpeechOptions = {}): SpeechState => { useMount(() => { const utterance = new SpeechSynthesisUtterance(text); + opts.lang && (utterance.lang = opts.lang); + opts.voice && (utterance.voice = opts.voice); utterance.rate = opts.rate || 1; + utterance.pitch = opts.pitch || 1; utterance.volume = opts.volume || 1; utterance.onstart = () => setState({ isPlaying: true }); utterance.onresume = () => setState({ isPlaying: true });