-
Notifications
You must be signed in to change notification settings - Fork 0
/
speech-recorder.html
569 lines (486 loc) · 16.5 KB
/
speech-recorder.html
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Generatore dataset audio</title>
<script src="http://unpkg.com/tone"></script>
</head>
<body>
<script>
window.textSamples = [
{
lang: "it",
text: "La storia dell'umanità è ricca di eventi significativi e personaggi straordinari come Einstein che, con la teoria della relatività, ha rivoluzionato il nostro modo di comprendere l'universo.\nCome Einstein, ci sono molti altri pensatori e innovatori il cui contributo ha plasmato il corso della storia e ha ispirato generazioni future a esplorare le frontiere della conoscenza e della scoperta."
},
{
lang: "it",
text: "Adoro i profumi di Guerlain, Burberry e Paco Rabanne. Per caso avete uno di questi in offerta?"
},
{
lang: "it",
text: "La crema anti-età Shiseido che mi avete consigliato l'ultima volta mi ha fatto uscire uno sfogo terribile, quindi esigo un risarcimento!"
},
{
lang: "it",
text: "Posso ottenere lo sconto sui gloss di Sisley anche se non acquisto nessun rossetto MAC?"
},
{
lang: "en",
text: "Sorry, could you repeat that? I didn't catch what you said."
},
]
</script>
<script>
function blobToBase64(blob) {
return new Promise((resolve, _) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.readAsDataURL(blob)
})
}
function downloadRecordedSample(sample) {
const a = document.createElement('a')
a.href = URL.createObjectURL(new Blob([JSON.stringify(sample, undefined, 2)], {type: 'application/json'}))
a.download = `${sample.id}.json`
a.style.display = 'none'
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
(() => {
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
const temp = array[i]
array[i] = array[j]
array[j] = temp
}
}
class AudioChunkedRecorder {
voiceTrackers = new Map()
constructor(stream, mimeType, bitsPerSecond, minDecibels = -55) {
this.mimeType = mimeType
this.bitsPerSecond = bitsPerSecond
const audioContext = new AudioContext()
const source = audioContext.createMediaStreamSource(stream)
this.analyser = audioContext.createAnalyser()
this.analyser.minDecibels = minDecibels
source.connect(this.analyser)
const destination = audioContext.createMediaStreamDestination()
source.connect(destination)
this.stream = destination.stream
}
start(seconds, onAudio) {
const recordDuration = seconds * 1000
const overlappingDuration = Math.floor(recordDuration * 2 / 3)
this.intervalId = setInterval(() => { this.runRecorder(recordDuration, onAudio) }, overlappingDuration)
this.runAnalyzer(recordDuration)
this.runRecorder(recordDuration, onAudio)
}
stop() {
clearInterval(this.intervalId)
this.intervalId = undefined
}
runRecorder(milliseconds, onAudioBlob) {
const chunkStartTime = Date.now()
this.voiceTrackers.set(chunkStartTime, false)
const mediaRecorder = new MediaRecorder(this.stream, {
mimeType: this.mimeType,
audioBitsPerSecond: this.bitsPerSecond,
})
const chunks = []
mediaRecorder.ondataavailable = (event) => {
chunks.push(event.data)
}
mediaRecorder.onstop = () => {
const audioBlob = new Blob(chunks, { type: this.mimeType })
const hasVoice = this.voiceTrackers.get(chunkStartTime) ?? true
this.voiceTrackers.delete(chunkStartTime)
onAudioBlob(audioBlob, hasVoice, this.voiceTrackers.size === 0)
}
mediaRecorder.start()
setTimeout(() => { mediaRecorder.stop() }, milliseconds)
}
runAnalyzer(milliseconds) {
const runAnalyzerInternal = () => {
if (!this.intervalId) {
return
}
const domainData = new Uint8Array(this.analyser.frequencyBinCount)
const analysisTime = Date.now()
this.analyser.getByteFrequencyData(domainData)
let soundDetected = false
for (let i = 0; i < this.analyser.frequencyBinCount; i++) {
if (domainData[i] > 0) {
soundDetected = true
break
}
}
if (soundDetected) {
const trackersToChange = [...this.voiceTrackers.keys()].filter((key) => key <= analysisTime && analysisTime < key + milliseconds)
trackersToChange.forEach((key) => this.voiceTrackers.set(key, true))
}
window.requestAnimationFrame(runAnalyzerInternal)
}
window.requestAnimationFrame(runAnalyzerInternal)
}
}
class AudioRecorderService {
activeRecorders = new Map()
audioType = 'audio/webm'
bitsPerSecond = 32000
recordersCounter = 0
start(seconds, onAudio) {
const recorderId = ++this.recordersCounter
navigator.mediaDevices.getUserMedia({audio: true})
.then((stream) => {
const recorder = new AudioChunkedRecorder(stream, this.audioType, this.bitsPerSecond)
recorder.start(seconds, (blob, hasVoice, isLast) => onAudio(blob, hasVoice, isLast))
this.activeRecorders.set(recorderId, recorder)
})
.catch((error) => {
console.error(error)
})
return recorderId
}
stop(id) {
const recorder = this.activeRecorders.get(id)
if (recorder) {
recorder.stop()
}
this.activeRecorders.delete(id)
}
}
const ars = new AudioRecorderService()
const textRecorder = (chunkSeconds) => {
let resolve, reject
const recPromise = new Promise((res, rej) => {resolve = res; rej = reject})
const chunks = []
const recId = ars.start(chunkSeconds, (blob, hasVoice, isLast) => {
blobToBase64(blob).then((data) => {
chunks.push({
hasVoice: hasVoice,
audio: data
})
if (isLast) {
resolve(chunks)
}
})
})
return async () => {
ars.stop(recId)
return await recPromise
}
}
document.addEventListener("DOMContentLoaded", (event) => {
const sessionId = Date.now().toString(36) + Math.random().toString(36).substring(2)
const chunkDuration = 3
const samplesSettings = []
window.textSamples.forEach((sample, index) => {
;['normal', 'slow', 'fast'].forEach((speed) => {
samplesSettings.push({
text: sample.text,
lang: sample.lang,
speed: speed,
chunkDuration: chunkDuration,
id: `sample_${index}_${speed}_${sample.lang}_##VOICE##_${chunkDuration}s-${sessionId}`
})
})
})
shuffleArray(samplesSettings)
const showPage = (mainElement, index, createRecordedSample) => {
const paginationElement = mainElement.querySelector('.pagination')
const prevButton = paginationElement.querySelector('button.prev')
const nextButton = paginationElement.querySelector('button.next')
prevButton.style.visibility = index === 0 ? 'hidden' : 'visible'
prevButton.onclick = () => showPage(mainElement, index - 1, createRecordedSample)
nextButton.style.visibility = index === samplesSettings.length - 1 ? 'hidden' : 'visible'
nextButton.onclick = () => showPage(mainElement, index + 1, createRecordedSample)
paginationElement.querySelector('span.progress').innerText = `${index + 1} / ${samplesSettings.length}`
const currentSample = samplesSettings[index]
const sampleElement = mainElement.querySelector('.sample')
sampleElement.querySelector('.hint').innerText = {
'normal': 'Leggi il seguente testo ad una velocità normale',
'slow': 'Leggi il seguente testo lentamente',
'fast': 'Leggi il seguente testo velocemente',
}[currentSample.speed]
sampleElement.querySelector('.text').innerHTML = currentSample.text.replace(/\n/gum, '<br>')
const toggleButton = sampleElement.querySelector('button.toggle-recording')
toggleButton.innerText = '▶ Start'
toggleButton.onclick = () => {
toggleButton.innerText = '◼ Stop'
toggleButton.classList.add('recording')
prevButton.disabled = true
nextButton.disabled = true
const stop = textRecorder(currentSample.chunkDuration)
toggleButton.onclick = async () => {
toggleButton.disabled = true
const chunks = await stop()
const recordedSample = createRecordedSample(currentSample, chunks)
prevButton.disabled = false
nextButton.disabled = false
toggleButton.classList.remove('recording')
toggleButton.innerText = '▶ Start'
downloadRecordedSample(recordedSample)
toggleButton.disabled = false
}
}
}
const startForm = document.getElementById('start')
startForm.addEventListener('submit', (event) => {
event.preventDefault()
const data = new FormData(startForm)
const voice = data.get('voice').trim()
const voiceId = voice.replace(/\s+/, '').toLowerCase()
const mainElement = document.querySelector('.main')
showPage(mainElement, 0, (settings, chunks) => {
const recordedSample = structuredClone(settings)
recordedSample.chunks = chunks
recordedSample.voice = voice
recordedSample.id = recordedSample.id.replace('##VOICE##', voiceId)
return recordedSample
})
mainElement.style.display = 'block'
startForm.style.display = 'none'
})
})
})()
</script>
<style>
* {
font-family: sans-serif;
}
body {
margin: auto;
padding: 1em;
max-width: 800px;
}
button {
padding: 0.5em 1em;
background: white;
border: 1px solid black;
cursor: pointer;
}
button:hover {
background: silver;
}
button:disabled {
opacity: 0.2;
background: white;
}
input {
padding: 0.5em 1em;
border: 1px solid black;
}
.intro form {
margin: 1em 0;
}
.intro form button[type="submit"] {
display: block;
}
.main {
display: none;
}
.main .sample {
border: 1px solid black;
padding: 1em;
margin: 2em 0;
}
.main .sample .hint {
font-weight: bold;
font-style: italic;
}
.main .sample .text {
font-family: serif;
font-size: 1.2em;
line-height: 1.4;
}
.main .sample .toggle-recording {
display: block;
margin: 0 auto;
min-width: 150px;
background: palegreen;
}
.main .sample .toggle-recording.recording {
background: orangered;
}
.main .pagination {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
gap: 1em;
}
details.debug {
margin-top: 50px;
}
</style>
<h1>Strumento di generazione dataset audio</h1>
<div class="intro">
<p>Dovrai leggere le frasi proposte, seguendo le eventuali richieste relative all'impostazione vocale. Le frasi si ripetono in ordine casuale con richieste diverse.</p>
<p>Sarà presente un tasto Start/Stop da cliccare per avviare e fermare la registrazione. Al termine di ciascuna registrazione verrà scaricato un file.<p>
<p>Alla prima registrazione dovrai concedere al browser il permesso per utilizzare il microfono.</p>
<form id="start">
<label for="voice">Inserisci il tuo nome o uno pseudonimo:</label>
<input type="text" required name="voice">
<button type="submit">Inizia</button>
</form>
</div>
<div class="main">
<div class="sample">
<p class="hint"></p>
<p class="text"></p>
<button class="toggle-recording"></button>
</div>
<div class="pagination">
<button class="prev">← Precedente</button>
<span class="progress"></span>
<button class="next">Successivo →</button>
</div>
</div>
<script>
(() => {
document.addEventListener("DOMContentLoaded", (event) => {
const sectionWrapper = document.querySelector('.debug')
const playerElement = sectionWrapper.querySelector('.player')
const initPlayer = (data) => {
playerElement.innerHTML = `<div class="info"><ul><li>Lang: ${data.lang}</li><li>Voice: ${data.voice}</li><li>Speed: ${data.speed}</li><li>Text: <span>${data.text}</span></li></ul></div>`
const playButton = document.createElement('button')
playButton.innerText = 'Riproduci'
playerElement.appendChild(playButton)
const progressElement = document.createElement('span')
playerElement.appendChild(progressElement)
const playChunk = (index = 0) => {
progressElement.innerText = `Chunk ${index+1}/${data.chunks.length} (hasVoice: ${data.chunks[index].hasVoice})`
const sound = new Audio(data.chunks[index].audio)
sound.addEventListener('ended', () => {
if (index + 1 < data.chunks.length) {
playChunk(index + 1)
} else {
progressElement.innerText = ''
}
})
sound.play()
}
playButton.addEventListener('click', () => {
playChunk()
})
}
const editorElement = sectionWrapper.querySelector('.editor')
const initEditor = (data) => {
data = structuredClone(data)
editorElement.innerHTML = ''
const progressElement = document.createElement('span')
editorElement.appendChild(progressElement)
const playButton = document.createElement('button')
playButton.innerText = 'Genera versione con rumore'
editorElement.appendChild(playButton)
const addEffects = async (output, volume) => {
const autoFilter1 = new Tone.AutoFilter({
frequency: "5n",
baseFrequency: 300,
octaves: 6
}).connect(output).start()
const autoFilter2 = new Tone.AutoFilter({
frequency: "3n",
baseFrequency: 500,
octaves: 7
}).connect(autoFilter1).start()
const noise1 = new Tone.Noise({
volume: volume - 45,
type: 'pink',
}).start().connect(autoFilter2)
const noise2 = new Tone.Noise({
volume: volume - 40,
type: 'brown',
}).start().connect(output)
// Announcement bell
const synth = new Tone.PolySynth({
volume: volume - 20,
}).connect(output)
const announcementVoice = await new Promise((resolve) => {
const x = new Tone.Player({
url: 'https://cdn.freesound.org/previews/324/324230_8238-lq.mp3',
volume: volume - 18,
playbackRate: 1.5,
onload: () => resolve(x)
}).connect(output)
})
const loop = new Tone.Loop((time) => {
const startTime = time + Math.random()
synth.triggerAttack("D4", startTime)
synth.triggerAttack("F4", startTime + 0.4)
synth.triggerAttack("A4", startTime + 0.8)
synth.triggerAttack("E5", startTime + 1.2)
synth.triggerRelease(["D4", "F4", "A4", "E5"], startTime + 2)
announcementVoice.start(startTime + 2, 8.6, 2)
}, 7).start()
// Persons around
const crowdVoices = new Tone.Player({
url: 'https://cdn.freesound.org/previews/57/57776_717853-lq.mp3',
autostart: true,
loop: true,
volume: volume - 14,
}).connect(output)
}
const runAudio = async () => {
await Tone.Transport.start()
const recorder = new Tone.Recorder()
const noiseVolume = 10
const gain = new Tone.Gain(0.5).connect(recorder)
await addEffects(gain, noiseVolume)
for (let i = 0; i < data.chunks.length; i++) {
progressElement.innerText = `Chunk ${i+1}/${data.chunks.length}`
const player = await new Promise((resolve) => {
const x = new Tone.Player({
url: data.chunks[i].audio,
onload: () => resolve(x)
}).connect(gain)
})
await recorder.start()
player.start()
const blob = await new Promise((resolve) => {
player.onstop = async () => {
const blob = await recorder.stop()
player.dispose()
resolve(blob)
}
})
const blobData = await blobToBase64(blob)
data.chunks[i].audio = blobData
}
data.id = data.id.replace('-', `_noise_${20 + noiseVolume}-`)
downloadRecordedSample(data)
}
playButton.addEventListener('click', async () => {
await runAudio()
})
}
const fileInput = sectionWrapper.querySelector('input')
fileInput.addEventListener('change', (event) => {
if (fileInput.files && fileInput.files.length > 0) {
const reader = new FileReader()
reader.onloadend = () => {
const data = JSON.parse(reader.result)
initPlayer(data)
initEditor(data)
}
reader.readAsText(fileInput.files[0])
} else {
playerElement.innerHTML = ''
editorElement.innerHTML = ''
}
})
})
})()
</script>
<details class="debug">
<summary>Debug</summary>
<p>Funzione di debug per controllare che la registrazione sia avvenuta con successo. Ricorda che la registrazione è divisa in più chunk, parzialmente sovrapposti.</p>
<input type="file" accept=".json" name="Carica registrazione">
<div class="player"></div>
<div class="editor"></div>
</details>
</body>
</html>