Skip to content

Commit

Permalink
feat: add voice option in useSpeech (#422)
Browse files Browse the repository at this point in the history
feat: add voice option in useSpeech
  • Loading branch information
streamich authored Jun 30, 2019
2 parents 1df0677 + 6dc2dd5 commit c32d02b
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 5 deletions.
4 changes: 3 additions & 1 deletion docs/useSpeech.md
Original file line number Diff line number Diff line change
Expand Up @@ -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>
Expand Down
4 changes: 3 additions & 1 deletion src/__stories__/useSpeech.story.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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>;
};
Expand Down
17 changes: 14 additions & 3 deletions src/useSpeech.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,41 @@ 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,
});

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

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 });
Expand Down

0 comments on commit c32d02b

Please sign in to comment.