-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathuseSpeech.ts
92 lines (79 loc) Β· 2.21 KB
/
useSpeech.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import { useCallback, useEffect, useRef, useState } from 'react';
type SpeechOptions = {
lang: string;
voice?: SpeechSynthesisVoice;
rate: number;
pitch: number;
volume: number;
};
export type ISpeechOptions = Partial<SpeechOptions>;
export type VoiceInfo = Pick<SpeechSynthesisVoice, 'lang' | 'name'>;
export type ISpeechState = SpeechOptions & {
isPlaying: boolean;
status: string;
voiceInfo: VoiceInfo;
};
enum Status {
init,
play,
pause,
end,
}
const useSpeech = (text: string, options: ISpeechOptions): ISpeechState => {
let mounted = useRef<boolean>(false);
const [state, setState] = useState<ISpeechState>(() => {
const { lang = 'default', name = '' } = options.voice || {};
return {
isPlaying: false,
status: Status[Status.init],
lang: options.lang || 'default',
voiceInfo: { lang, name },
rate: options.rate || 1,
pitch: options.pitch || 1,
volume: options.volume || 1,
};
});
const handlePlay = useCallback(() => {
if (!mounted.current) {
return;
}
setState((preState) => {
return { ...preState, isPlaying: true, status: Status[Status.play] };
});
}, []);
const handlePause = useCallback(() => {
if (!mounted.current) {
return;
}
setState((preState) => {
return { ...preState, isPlaying: false, status: Status[Status.pause] };
});
}, []);
const handleEnd = useCallback(() => {
if (!mounted.current) {
return;
}
setState((preState) => {
return { ...preState, isPlaying: false, status: Status[Status.end] };
});
}, []);
useEffect(() => {
mounted.current = true;
const utterance = new SpeechSynthesisUtterance(text);
options.lang && (utterance.lang = options.lang);
options.voice && (utterance.voice = options.voice);
utterance.rate = options.rate || 1;
utterance.pitch = options.pitch || 1;
utterance.volume = options.volume || 1;
utterance.onstart = handlePlay;
utterance.onpause = handlePause;
utterance.onresume = handlePlay;
utterance.onend = handleEnd;
window.speechSynthesis.speak(utterance);
return () => {
mounted.current = false;
};
}, []);
return state;
};
export default useSpeech;