1 | "use strict";
|
---|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
---|
3 | var tslib_1 = require("tslib");
|
---|
4 | var react_1 = require("react");
|
---|
5 | var Status;
|
---|
6 | (function (Status) {
|
---|
7 | Status[Status["init"] = 0] = "init";
|
---|
8 | Status[Status["play"] = 1] = "play";
|
---|
9 | Status[Status["pause"] = 2] = "pause";
|
---|
10 | Status[Status["end"] = 3] = "end";
|
---|
11 | })(Status || (Status = {}));
|
---|
12 | var useSpeech = function (text, options) {
|
---|
13 | var mounted = react_1.useRef(false);
|
---|
14 | var _a = react_1.useState(function () {
|
---|
15 | var _a = options.voice || {}, _b = _a.lang, lang = _b === void 0 ? 'default' : _b, _c = _a.name, name = _c === void 0 ? '' : _c;
|
---|
16 | return {
|
---|
17 | isPlaying: false,
|
---|
18 | status: Status[Status.init],
|
---|
19 | lang: options.lang || 'default',
|
---|
20 | voiceInfo: { lang: lang, name: name },
|
---|
21 | rate: options.rate || 1,
|
---|
22 | pitch: options.pitch || 1,
|
---|
23 | volume: options.volume || 1,
|
---|
24 | };
|
---|
25 | }), state = _a[0], setState = _a[1];
|
---|
26 | var handlePlay = react_1.useCallback(function () {
|
---|
27 | if (!mounted.current) {
|
---|
28 | return;
|
---|
29 | }
|
---|
30 | setState(function (preState) {
|
---|
31 | return tslib_1.__assign(tslib_1.__assign({}, preState), { isPlaying: true, status: Status[Status.play] });
|
---|
32 | });
|
---|
33 | }, []);
|
---|
34 | var handlePause = react_1.useCallback(function () {
|
---|
35 | if (!mounted.current) {
|
---|
36 | return;
|
---|
37 | }
|
---|
38 | setState(function (preState) {
|
---|
39 | return tslib_1.__assign(tslib_1.__assign({}, preState), { isPlaying: false, status: Status[Status.pause] });
|
---|
40 | });
|
---|
41 | }, []);
|
---|
42 | var handleEnd = react_1.useCallback(function () {
|
---|
43 | if (!mounted.current) {
|
---|
44 | return;
|
---|
45 | }
|
---|
46 | setState(function (preState) {
|
---|
47 | return tslib_1.__assign(tslib_1.__assign({}, preState), { isPlaying: false, status: Status[Status.end] });
|
---|
48 | });
|
---|
49 | }, []);
|
---|
50 | react_1.useEffect(function () {
|
---|
51 | mounted.current = true;
|
---|
52 | var utterance = new SpeechSynthesisUtterance(text);
|
---|
53 | options.lang && (utterance.lang = options.lang);
|
---|
54 | options.voice && (utterance.voice = options.voice);
|
---|
55 | utterance.rate = options.rate || 1;
|
---|
56 | utterance.pitch = options.pitch || 1;
|
---|
57 | utterance.volume = options.volume || 1;
|
---|
58 | utterance.onstart = handlePlay;
|
---|
59 | utterance.onpause = handlePause;
|
---|
60 | utterance.onresume = handlePlay;
|
---|
61 | utterance.onend = handleEnd;
|
---|
62 | window.speechSynthesis.speak(utterance);
|
---|
63 | return function () {
|
---|
64 | mounted.current = false;
|
---|
65 | };
|
---|
66 | }, []);
|
---|
67 | return state;
|
---|
68 | };
|
---|
69 | exports.default = useSpeech;
|
---|