beautiful-react-hooks
Version:
A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development
43 lines (42 loc) • 1.69 kB
JavaScript
;
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = require("react");
var defaultOptions = { rate: 1, pitch: 1, volume: 1 };
/**
* Enables the possibility to perform a text-to-speech (with different voices) operation in your
* React component by using the Web_Speech_API
*/
var useSpeechSynthesis = function (text, options) {
if (options === void 0) { options = defaultOptions; }
var utter = (0, react_1.useMemo)(function () { return new SpeechSynthesisUtterance(text); }, [text]);
var voiceOptions = __assign(__assign({}, defaultOptions), options);
utter.voice = voiceOptions.voice;
(0, react_1.useEffect)(function () {
utter.pitch = voiceOptions.pitch;
}, [voiceOptions.pitch]);
(0, react_1.useEffect)(function () {
utter.rate = voiceOptions.rate;
}, [voiceOptions.rate]);
(0, react_1.useEffect)(function () {
utter.volume = voiceOptions.volume;
}, [voiceOptions.volume]);
var speak = (0, react_1.useCallback)(function () {
speechSynthesis.speak(utter);
}, [text, voiceOptions.pitch, voiceOptions.rate, voiceOptions.voice, voiceOptions.volume]);
return Object.freeze({
speak: speak,
speechSynthUtterance: utter
});
};
exports.default = useSpeechSynthesis;