feat: add voice option in use speech

This commit is contained in:
allen 2019-06-27 01:19:02 +08:00
parent ba6d375e07
commit 6dc2dd572b
3 changed files with 20 additions and 5 deletions

View File

@ -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 (
<pre>

View File

@ -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 <pre>{JSON.stringify(state, null, 2)}</pre>;
};

View File

@ -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<SpeechState>({
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 });