This repository has been archived by the owner on Feb 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
224 lines (203 loc) · 7.43 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
// ELEVENLABS PARAMETERS https://beta.elevenlabs.io/
var apiKey = "XXXXXXXXX"; // your elevenlabs api key
// TWITCH PARAMETERS
var channelId = "12345678"; // your twitch channel id
// rewards
var rewards = {
"Radd (AI TTS)": {
// reward name (must be the same as the reward name in twitch !! case sensitive)
ttsCharacterLimit: 300, // max characters to send
type: "elevenlabs", // elevenlabs or streamelements
voiceId: "XXXXXXXXXXX", // elevenlabs voice id
volume: 1, // volume 0.0 - 1.0
stability: 0.3, // elevenlabs stability 0.0 - 1.0
style: 0.5, // elevenlabs values
useSpeakerBoost: false, // elevenlabs values
modelId: "eleven_monolingual_v1", // elevenlabs values. Use eleven_monolingual_v1 for english only and eleven_multilingual_v1 for other languages
similarityBoost: 0.8, // elevenlabs similarityBoost 0.0 - 1.0
},
"Brian (Normal TTS)": {
// reward name (must be the same as the reward name in twitch !! case sensitive)
ttsCharacterLimit: 500, // max characters to send
type: "streamelements", // streamelements or elevenlabs
voiceId: "Brian", // streamelements voice id
volume: 0.35, // volume 0.0 - 1.0
},
};
// -----------------
// DEBUG PARAMETERS
// -----------------
var testTTSOnLoad = false; // debug mode to test. true = F5 to play text false = nothing. Leave this on false if you dont plan to change the code.
var testTTS = "Brian (Normal TTS)"; // reward name to test
var testText = "Hello world"; // text to test
function sleep(miliseconds) {
return new Promise((res) => setTimeout(res, miliseconds));
}
async function textToSpeech(reward, text) {
const ctx = new AudioContext();
// Limit text length
text = text.substring(0, reward["ttsCharacterLimit"]);
console.log("TTS text:", text);
let url;
let requestOptions;
if (reward["type"] == "elevenlabs") {
requestOptions = {
method: "POST",
headers: {
"xi-api-key": apiKey,
"Content-Type": "application/json",
},
body: JSON.stringify({
text: text,
model_id: reward["modelId"],
voice_settings: {
stability: reward["stability"],
similarity_boost: reward["similarityBoost"],
style: reward["style"],
use_speaker_boost: reward["useSpeakerBoost"],
},
}),
};
url = `https://api.elevenlabs.io/v1/text-to-speech/${reward["voiceId"]}`;
} else if (reward["type"] == "streamelements") {
url = `https://api.streamelements.com/kappa/v2/speech?voice=${reward["voiceId"]}&text=${text}`;
} else {
throw "TTS type not found";
}
// fetch() returns a promise that
// resolves once headers have been received
var response = await fetch(url, requestOptions);
var arrayBuffer = await response.arrayBuffer();
var decodedAudio = await ctx.decodeAudioData(arrayBuffer);
var gainNode = ctx.createGain();
gainNode.connect(ctx.destination);
gainNode.gain.value = reward["volume"];
const audio = decodedAudio;
const source = ctx.createBufferSource();
source.buffer = audio;
source.connect(gainNode);
source.start();
return new Promise((resolve, reject) => {
source.onended = resolve;
});
}
window.onload = () => {
let ws = undefined;
let pong = false;
let interval = false;
let notifications = [];
(async () => {
while (true) {
if (notifications.length > 0) {
let notif = notifications.pop();
console.log("Notification started", notif);
let reward = rewards[notif.title];
if (reward && notif.text != "") {
console.log("Playing TTS");
try {
await textToSpeech(reward, notif.text);
console.log("TTS ended");
} catch (e) {
console.log("TTS error:", e);
}
}
console.log("Notification ended");
}
await sleep(1000);
}
})();
function connect() {
ws = new WebSocket("wss://pubsub-edge.twitch.tv");
listen();
}
function disconnect() {
if (interval) {
clearInterval(interval);
interval = false;
}
ws.close();
}
function listen() {
ws.onmessage = (a) => {
let o = JSON.parse(a.data);
switch (o.type) {
case "PING":
ws.send(
JSON.stringify({
type: "PONG",
})
);
break;
case "PONG":
pong = true;
break;
case "RECONNECT":
disconnect();
connect();
break;
case "RESPONCE":
console.log("PubSub responce ", o.error);
break;
case "MESSAGE":
switch (o.data.topic) {
case `community-points-channel-v1.${channelId}`:
let msg = JSON.parse(o.data.message);
console.log(msg);
switch (msg.type) {
case "reward-redeemed":
let reward = msg.data.redemption.reward;
let notif = {
title: reward.title,
price: reward.cost,
user: msg.data.redemption.user.display_name,
text: msg.data.redemption.user_input,
};
console.log("Notification queued", notif);
notifications.push(notif);
break;
}
break;
}
break;
}
};
ws.onopen = () => {
if (testTTSOnLoad) {
let notif = {
title: testTTS,
price: 5000,
user: "test_user",
text: testText,
};
console.log("Notification queued", notif);
notifications.push(notif);
}
ws.send(
JSON.stringify({
type: "LISTEN",
nonce: "pepega",
data: {
topics: ["community-points-channel-v1." + channelId],
auth_token: "",
},
})
);
interval = setInterval(async () => {
ws.send(
JSON.stringify({
type: "PING",
})
);
await sleep(5000);
if (pong) {
pong = false;
} else {
pong = false;
disconnect();
connect();
}
}, 5 * 60 * 1000);
};
}
connect();
};