react-blabla
Version:
A React text-to-speech component
75 lines • 3.21 kB
JavaScript
import { useEffect, useState, useMemo, useCallback } from 'react';
var synthesis = (window === null || window === void 0 ? void 0 : window.speechSynthesis) || {};
var Utterance = (window === null || window === void 0 ? void 0 : window.SpeechSynthesisUtterance) || {};
var utterance = new Utterance();
export function useBlabla(params) {
var _a = useState(0), currentWordIndex = _a[0], setCurrentWordIndex = _a[1];
var _b = useState(false), isStart = _b[0], setIsStart = _b[1];
var _c = useState(false), isPaused = _c[0], setIsPaused = _c[1];
var allWords = useMemo(function () { var _a; return ((_a = params === null || params === void 0 ? void 0 : params.text) === null || _a === void 0 ? void 0 : _a.split(' ').filter(function (str) { return str; })) || []; }, []);
var sayNext = useCallback(function () {
if (currentWordIndex === allWords.length + 1) {
synthesis.cancel();
setIsStart(false);
setCurrentWordIndex(0);
return;
}
utterance.text = allWords[currentWordIndex];
synthesis.speak(utterance);
}, [currentWordIndex, utterance]);
useEffect(function () {
var _a, _b, _c, _d, _e, _f, _g, _h;
if (params === null || params === void 0 ? void 0 : params.options) {
utterance.pitch = ((_a = params.options) === null || _a === void 0 ? void 0 : _a.pitch) || 1;
utterance.rate = ((_b = params.options) === null || _b === void 0 ? void 0 : _b.rate) || 1;
utterance.volume = ((_c = params.options) === null || _c === void 0 ? void 0 : _c.volume) || 0.25;
utterance.lang = ((_d = params.options) === null || _d === void 0 ? void 0 : _d.lang) || 'en-US';
if ((_f = (_e = params.options) === null || _e === void 0 ? void 0 : _e.voice) === null || _f === void 0 ? void 0 : _f.name) {
utterance.voice =
((_g = params.options) === null || _g === void 0 ? void 0 : _g.voice) || ((_h = window === null || window === void 0 ? void 0 : window.speechSynthesis) === null || _h === void 0 ? void 0 : _h.getVoices()[0]);
}
}
}, [params]);
utterance.onstart = function () {
setCurrentWordIndex(currentWordIndex + 1);
};
useEffect(function () {
if (isStart) {
sayNext();
}
}, [isStart, currentWordIndex]);
useEffect(function () {
synthesis.cancel();
}, []);
var stop = useCallback(function () {
synthesis.cancel();
setIsStart(false);
setCurrentWordIndex(0);
}, []);
var start = function () {
if (isPaused) {
sayNext();
setIsPaused(!isPaused);
return;
}
setIsStart(true);
};
var pause = function () {
if (isPaused) {
sayNext();
}
else {
synthesis.cancel();
}
setIsPaused(!isPaused);
};
return {
start: start,
pause: pause,
stop: stop,
allWords: allWords,
currentWord: allWords[currentWordIndex - 1],
currentWordIndex: Math.max(currentWordIndex - 1, 0),
};
}
//# sourceMappingURL=useBlabla.js.map