forked from webbro-software/voice-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
106 lines (93 loc) · 2.64 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
const isBrowser = typeof window !== "undefined";
const speechToText = (continuous = false) => {
if (
!isBrowser ||
(!window.SpeechRecognition && !window.webkitSpeechRecognition)
) {
throw new Error("Speech Recognition is not supported in this environment.");
}
const recognition = new (window.SpeechRecognition ||
window.webkitSpeechRecognition)();
recognition.continuous = continuous;
recognition.start();
return {
getTranscript() {
return new Promise((resolve, reject) => {
recognition.addEventListener("result", (e) => {
const transcript = Array.from(e.results)
.map((result) => result[0].transcript)
.join("");
resolve(transcript);
});
recognition.addEventListener("error", (e) => {
reject(new Error("Speech recognition error: " + e.error));
});
recognition.addEventListener("end", () => {
if (!continuous) {
reject(
new Error("Speech recognition ended without capturing results.")
);
} else {
recognition.start();
}
});
});
},
stopSpeech() {
recognition.stop();
},
};
};
const textToSpeech = (
text,
lang = "en-US",
volume = 1,
rate = 1,
pitch = 1,
voiceIndex = 5
) => {
if (!isBrowser)
return Promise.reject(
"Text-to-Speech is not supported in this environment."
);
return new Promise((resolve, reject) => {
try {
const speech = new SpeechSynthesisUtterance();
const voices = window.speechSynthesis.getVoices();
if (voiceIndex < voices.length) {
speech.voice = voices[voiceIndex];
} else {
console.warn("Voice index out of range, using default voice.");
}
speech.text = text;
speech.lang = lang;
speech.volume = volume;
speech.rate = rate;
speech.pitch = pitch;
speech.onend = resolve;
speech.onerror = (e) =>
reject(new Error("Text-to-Speech error: " + e.error));
window.speechSynthesis.speak(speech);
} catch (error) {
reject(new Error(error.message));
}
});
};
const getVoices = () => {
if (!isBrowser) return [];
return new Promise((resolve, reject) => {
try {
const voices = window.speechSynthesis.getVoices();
if (voices.length) {
resolve(voices);
} else {
window.speechSynthesis.onvoiceschanged = () => {
resolve(window.speechSynthesis.getVoices());
};
}
} catch (error) {
reject(new Error("Failed to get voices: " + error.message));
}
});
};
export { speechToText, textToSpeech, getVoices };