Skip to content

Commit 6dc2dd5

Browse files
committed
feat: add voice option in use speech
1 parent ba6d375 commit 6dc2dd5

File tree

3 files changed

+20
-5
lines changed

3 files changed

+20
-5
lines changed

Diff for: docs/useSpeech.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,10 @@ React UI hook that synthesizes human voice that speaks a given string.
88
```jsx
99
import {useSpeech} from 'react-use';
1010

11+
const voices = window.speechSynthesis.getVoices();
12+
1113
const Demo = () => {
12-
const state = useSpeech('Hello world!');
14+
const state = useSpeech('Hello world!', { rate: 0.8, pitch: 0.5, voice: voices[0] });
1315

1416
return (
1517
<pre>

Diff for: src/__stories__/useSpeech.story.tsx

+3-1
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@ import * as React from 'react';
33
import { useSpeech } from '..';
44
import ShowDocs from './util/ShowDocs';
55

6+
const voices = window.speechSynthesis.getVoices();
7+
68
const Demo = () => {
7-
const state = useSpeech('Hello world!');
9+
const state = useSpeech('Hello world!', { rate: 0.8, pitch: 0.5, voice: voices[0] });
810

911
return <pre>{JSON.stringify(state, null, 2)}</pre>;
1012
};

Diff for: src/useSpeech.ts

+14-3
Original file line numberDiff line numberDiff line change
@@ -4,30 +4,41 @@ import useSetState from './useSetState';
44

55
export interface SpeechState {
66
isPlaying: boolean;
7+
lang: string;
8+
voice: SpeechSynthesisVoice;
79
rate: number;
10+
pitch: number;
811
volume: number;
912
}
1013

1114
export interface SpeechOptions {
12-
lang?: any;
13-
pitch?: number;
15+
lang?: string;
16+
voice?: SpeechSynthesisVoice;
1417
rate?: number;
15-
voice?: any;
18+
pitch?: number;
1619
volume?: number;
1720
}
1821

22+
const voices = window.speechSynthesis.getVoices();
23+
1924
const useSpeech = (text: string, opts: SpeechOptions = {}): SpeechState => {
2025
const [state, setState] = useSetState<SpeechState>({
2126
isPlaying: false,
27+
lang: opts.lang || 'default',
28+
voice: opts.voice || voices[0],
2229
rate: opts.rate || 1,
30+
pitch: opts.pitch || 1,
2331
volume: opts.volume || 1,
2432
});
2533

2634
const uterranceRef = useRef<SpeechSynthesisUtterance | null>(null);
2735

2836
useMount(() => {
2937
const utterance = new SpeechSynthesisUtterance(text);
38+
opts.lang && (utterance.lang = opts.lang);
39+
opts.voice && (utterance.voice = opts.voice);
3040
utterance.rate = opts.rate || 1;
41+
utterance.pitch = opts.pitch || 1;
3142
utterance.volume = opts.volume || 1;
3243
utterance.onstart = () => setState({ isPlaying: true });
3344
utterance.onresume = () => setState({ isPlaying: true });

0 commit comments

Comments
 (0)