mirror of
https://github.com/streamich/react-use.git
synced 2025-12-08 18:02:14 +00:00
feat: add voice option in use speech
This commit is contained in:
parent
ba6d375e07
commit
6dc2dd572b
@ -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>
|
||||
|
||||
@ -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>;
|
||||
};
|
||||
|
||||
@ -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 });
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user