File size: 24,570 Bytes
69bd3cb
 
 
 
 
 
 
 
 
7643321
69bd3cb
 
 
 
 
d9feb41
 
69bd3cb
 
 
 
d9feb41
2ab07b8
69bd3cb
 
 
d9feb41
69bd3cb
 
 
d9feb41
 
 
 
69bd3cb
 
 
 
 
 
 
d9feb41
 
69bd3cb
 
 
d9feb41
69bd3cb
 
 
d9feb41
 
69bd3cb
 
d9feb41
69bd3cb
 
89e3334
 
 
 
69bd3cb
d9feb41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69bd3cb
d9feb41
 
 
 
 
69bd3cb
d9feb41
 
 
 
 
 
 
 
 
 
69bd3cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9feb41
69bd3cb
 
 
 
 
 
 
 
 
 
 
 
 
2ab07b8
 
69bd3cb
 
 
 
 
 
 
 
 
d9feb41
 
69bd3cb
 
2ab07b8
69bd3cb
 
 
 
 
 
d9feb41
 
69bd3cb
 
 
d9feb41
69bd3cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ab07b8
69bd3cb
 
 
 
d9feb41
69bd3cb
 
 
 
 
 
 
 
2ab07b8
 
69bd3cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9feb41
 
 
 
 
 
69bd3cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d97eda8
69bd3cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9feb41
 
 
 
 
 
 
 
89e3334
4f4f3a0
d9feb41
 
 
69bd3cb
 
 
 
 
 
d9feb41
69bd3cb
ecd3f4b
 
37f1896
 
d97eda8
 
 
69bd3cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4f4f3a0
 
 
 
 
 
 
 
 
 
89e3334
4f4f3a0
 
69bd3cb
4f4f3a0
89e3334
4f4f3a0
89e3334
69bd3cb
4f4f3a0
 
 
 
 
 
69bd3cb
 
 
 
 
 
 
 
 
 
 
89e3334
 
4f4f3a0
89e3334
 
4f4f3a0
 
 
 
 
 
 
 
 
89e3334
4f4f3a0
 
89e3334
4f4f3a0
 
 
 
89e3334
 
 
4f4f3a0
 
89e3334
69bd3cb
 
 
 
 
0c9255f
 
69bd3cb
 
 
 
 
 
 
4f4f3a0
0c9255f
 
69bd3cb
 
 
 
 
0c9255f
 
 
 
 
 
69bd3cb
 
 
 
 
 
 
 
 
4f4f3a0
69bd3cb
 
4f4f3a0
 
69bd3cb
 
 
4f4f3a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69bd3cb
d9feb41
4f4f3a0
 
 
69bd3cb
 
 
 
 
d9feb41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69bd3cb
 
 
d9feb41
 
 
 
 
 
 
69bd3cb
 
 
 
 
 
 
d9feb41
 
 
 
 
69bd3cb
 
 
 
d9feb41
69bd3cb
 
 
89e3334
69bd3cb
89e3334
 
 
 
 
 
 
 
 
69bd3cb
 
 
 
d9feb41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89e3334
 
69bd3cb
 
 
 
 
89e3334
 
 
 
 
69bd3cb
89e3334
 
 
 
 
 
 
 
69bd3cb
 
d9feb41
69bd3cb
 
89e3334
69bd3cb
 
 
 
 
 
4f4f3a0
 
89e3334
4f4f3a0
 
 
89e3334
 
 
4f4f3a0
 
 
 
 
 
89e3334
 
69bd3cb
 
 
 
 
 
4f4f3a0
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Audio Transcription</title>
    <style>
        body {
            font-family: ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
            margin: 20px;
            text-align: center;
        }

        #recordButton {
            width: 50px;
            height: 50px;
            border: none;
            border-radius: 50%;
            background-color: white;
            cursor: pointer;
            transition: all 0.3s ease;
            border: 1px solid rgb(233, 233, 233);
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
        }

        #recordButton.recording {
            width: 180px;
            border-radius: 40px;
            justify-content: flex-start;
            padding-left: 20px;
        }

        #recordButton:active {
            transform: scale(0.95);
        }

        .shape-container {
            width: 25px;
            height: 25px;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }

        .shape {
            width: 25px;
            height: 25px;
            background-color: rgb(209, 61, 53);
            border-radius: 50%;
            transition: all 0.3s ease;
        }

        #recordButton:disabled .shape {
            background-color: #6e6d6d;
        }

        #recordButton.recording .shape {
            border-radius: 5px;
            width: 25px;
            height: 25px;
        }

        /* Recording elements */
        .recording-info {
            display: none;
            align-items: center;
            margin-left: 15px;
            flex-grow: 1;
        }

        #recordButton.recording .recording-info {
            display: flex;
        }

        .wave-container {
            width: 60px;
            height: 30px;
            position: relative;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        #waveCanvas {
            width: 100%;
            height: 100%;
        }

        .timer {
            font-size: 14px;
            font-weight: 500;
            color: #333;
            margin-left: 10px;
        }

        #status {
            margin-top: 20px;
            font-size: 16px;
            color: #333;
        }

        .settings-container {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 15px;
            margin-top: 20px;
        }

        .settings {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            gap: 5px;
        }

        #chunkSelector,
        #websocketInput {
            font-size: 16px;
            padding: 5px;
            border-radius: 5px;
            border: 1px solid #ddd;
            background-color: #ffffff;
            max-height: 30px;
        }

        #websocketInput {
            width: 200px;
        }

        #chunkSelector:focus,
        #websocketInput:focus {
            outline: none;
            border-color: #007bff;
        }

        label {
            font-size: 14px;
        }

        /* Speaker-labeled transcript area */
        #linesTranscript {
            margin: 20px auto;
            max-width: 700px;
            text-align: left;
            font-size: 16px;
        }

        #linesTranscript p {
            margin: 0px 0;
        }

        #linesTranscript strong {
            color: #333;
        }

        #speaker {
            border: 1px solid rgb(229, 229, 229);
            border-radius: 100px;
            padding: 2px 10px;
            font-size: 14px;
            margin-bottom: 0px;
        }
        .label_diarization {
            background-color: #ffffff66;
            border-radius: 8px 8px 8px 8px;
            padding: 2px 10px;
            margin-left: 10px;
            display: inline-block;
            white-space: nowrap;
            font-size: 14px;
            margin-bottom: 0px;
            color: rgb(134, 134, 134)
        }

        .label_transcription {
            background-color: #ffffff66;
            border-radius: 8px 8px 8px 8px;
            padding: 2px 10px;
            display: inline-block;
            white-space: nowrap;
            margin-left: 10px;
            font-size: 14px;
            margin-bottom: 0px;
            color: #000000
        }

        #timeInfo {
            color: #666;
            margin-left: 10px;
        }

        .textcontent {
            font-size: 16px;
            /* margin-left: 10px; */
            padding-left: 10px;
            margin-bottom: 10px;
            margin-top: 1px;
            padding-top: 5px;
            border-radius: 0px 0px 0px 10px;
        }

        .buffer_diarization {
            color: rgb(134, 134, 134);
            margin-left: 4px;
        }

        .buffer_transcription {
            color: #7474748c;
            margin-left: 4px;
        }


        .spinner {
            display: inline-block;
            width: 8px;
            height: 8px;
            border: 2px solid #8d8d8d5c;
            border-top: 2px solid #6c6c6ce5;
            border-radius: 50%;
            animation: spin 0.6s linear infinite;
            vertical-align: middle;
            margin-bottom: 2px;
            margin-right: 5px;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        .silence {
            color: #666;
            background-color: #f3f3f3;
            font-size: 13px;
            border-radius: 30px;
            padding: 2px 10px;
        }

        .loading {
            color: #666;
            background-color: #ff4d4d0f;
            border-radius: 8px 8px 8px 0px;
            padding: 2px 10px;
            font-size: 14px;
            margin-bottom: 0px;
        }
    </style>
</head>

<body>

    <div class="settings-container">
        <button id="recordButton">
            <div class="shape-container">
                <div class="shape"></div>
            </div>
            <div class="recording-info">
                <div class="wave-container">
                    <canvas id="waveCanvas"></canvas>
                </div>
                <div class="timer">00:00</div>
            </div>
        </button>
        <div class="settings">
            <div>
                <label for="chunkSelector">Chunk size (ms):</label>
                <select id="chunkSelector">
                    <option value="500">500 ms</option>
                    <option value="1000" selected>1000 ms</option>
                    <option value="2000">2000 ms</option>
                    <option value="3000">3000 ms</option>
                    <option value="4000">4000 ms</option>
                    <option value="5000">5000 ms</option>
                </select>
            </div>
            <div>
                <label for="websocketInput">WebSocket URL:</label>
                <input id="websocketInput" type="text" />
            </div>
        </div>
    </div>

    <p id="status"></p>

    <!-- Speaker-labeled transcript -->
    <div id="linesTranscript"></div>

    <script>
        let isRecording = false;
        let websocket = null;
        let recorder = null;
        let chunkDuration = 1000;
        let websocketUrl = "ws://localhost:8000/asr";
        let userClosing = false;
        let startTime = null;
        let timerInterval = null;
        let audioContext = null;
        let analyser = null;
        let microphone = null;
        let waveCanvas = document.getElementById("waveCanvas");
        let waveCtx = waveCanvas.getContext("2d");
        let animationFrame = null;
        let waitingForStop = false;
        let lastReceivedData = null;
        waveCanvas.width = 60 * (window.devicePixelRatio || 1);
        waveCanvas.height = 30 * (window.devicePixelRatio || 1);
        waveCtx.scale(window.devicePixelRatio || 1, window.devicePixelRatio || 1);

        const statusText = document.getElementById("status");
        const recordButton = document.getElementById("recordButton");
        const chunkSelector = document.getElementById("chunkSelector");
        const websocketInput = document.getElementById("websocketInput");
        const linesTranscriptDiv = document.getElementById("linesTranscript");
        const timerElement = document.querySelector(".timer");

        const host = window.location.hostname || "localhost";
        const port = window.location.port || "8000";
        const protocol = window.location.protocol === "https:" ? "wss" : "ws";
        const defaultWebSocketUrl = `${protocol}://${host}:${port}/asr`;
        websocketInput.value = defaultWebSocketUrl;
        websocketUrl = defaultWebSocketUrl;

        chunkSelector.addEventListener("change", () => {
            chunkDuration = parseInt(chunkSelector.value);
        });

        websocketInput.addEventListener("change", () => {
            const urlValue = websocketInput.value.trim();
            if (!urlValue.startsWith("ws://") && !urlValue.startsWith("wss://")) {
                statusText.textContent = "Invalid WebSocket URL (must start with ws:// or wss://)";
                return;
            }
            websocketUrl = urlValue;
            statusText.textContent = "WebSocket URL updated. Ready to connect.";
        });

        function setupWebSocket() {
            return new Promise((resolve, reject) => {
                try {
                    websocket = new WebSocket(websocketUrl);
                } catch (error) {
                    statusText.textContent = "Invalid WebSocket URL. Please check and try again.";
                    reject(error);
                    return;
                }

                websocket.onopen = () => {
                    statusText.textContent = "Connected to server.";
                    resolve();
                };

                websocket.onclose = () => {
                    if (userClosing) {
                        if (waitingForStop) {
                            statusText.textContent = "Processing finalized or connection closed.";
                            if (lastReceivedData) {
                                renderLinesWithBuffer(
                                    lastReceivedData.lines || [],
                                    lastReceivedData.buffer_diarization || "",
                                    lastReceivedData.buffer_transcription || "",
                                    0, 0, true // isFinalizing = true
                                );
                            }
                        }
                        // If ready_to_stop was received, statusText is already "Finished processing..."
                        // and waitingForStop is false.
                    } else {
                        statusText.textContent = "Disconnected from the WebSocket server. (Check logs if model is loading.)";
                        if (isRecording) {
                            stopRecording(); 
                        }
                    }
                    isRecording = false;  
                    waitingForStop = false; 
                    userClosing = false;  
                    lastReceivedData = null;  
                    websocket = null;    
                    updateUI();  
                };

                websocket.onerror = () => {
                    statusText.textContent = "Error connecting to WebSocket.";
                    reject(new Error("Error connecting to WebSocket"));
                };

                // Handle messages from server
                websocket.onmessage = (event) => {
                    const data = JSON.parse(event.data);
                    
                    // Check for status messages
                    if (data.type === "ready_to_stop") {
                        console.log("Ready to stop received, finalizing display and closing WebSocket.");
                        waitingForStop = false;

                        if (lastReceivedData) {
                            renderLinesWithBuffer(
                                lastReceivedData.lines || [],
                                lastReceivedData.buffer_diarization || "",
                                lastReceivedData.buffer_transcription || "",
                                0, // No more lag
                                0, // No more lag
                                true // isFinalizing = true
                            );
                        }
                        statusText.textContent = "Finished processing audio! Ready to record again.";
                        recordButton.disabled = false;
                        
                        if (websocket) {
                            websocket.close(); // will trigger onclose
                            // websocket = null; // onclose handle setting websocket to null
                        }
                        return;
                    }
                    
                    lastReceivedData = data; 
                    
                    // Handle normal transcription updates
                    const { 
                        lines = [], 
                        buffer_transcription = "", 
                        buffer_diarization = "",
                        remaining_time_transcription = 0,
                        remaining_time_diarization = 0,
                        status = "active_transcription"
                    } = data;
                    
                    renderLinesWithBuffer(
                        lines, 
                        buffer_diarization, 
                        buffer_transcription, 
                        remaining_time_diarization,
                        remaining_time_transcription,
                        false,
                        status
                    );
                };
            });
        }

        function renderLinesWithBuffer(lines, buffer_diarization, buffer_transcription, remaining_time_diarization, remaining_time_transcription, isFinalizing = false, current_status = "active_transcription") {
            if (current_status === "no_audio_detected") {
                linesTranscriptDiv.innerHTML = "<p style='text-align: center; color: #666; margin-top: 20px;'><em>No audio detected...</em></p>";
                return; 
            }

            const linesHtml = lines.map((item, idx) => {
                let timeInfo = "";
                if (item.beg !== undefined && item.end !== undefined) {
                    timeInfo = ` ${item.beg} - ${item.end}`;
                }

                let speakerLabel = "";
                if (item.speaker === -2) {
                    speakerLabel = `<span class="silence">Silence<span id='timeInfo'>${timeInfo}</span></span>`;
                } else if (item.speaker == 0 && !isFinalizing) {
                    speakerLabel = `<span class='loading'><span class="spinner"></span><span id='timeInfo'>${remaining_time_diarization} second(s) of audio are undergoing diarization</span></span>`;
                } else if (item.speaker == -1) {
                    speakerLabel = `<span id="speaker">Speaker 1<span id='timeInfo'>${timeInfo}</span></span>`;
                } else if (item.speaker !== -1 && item.speaker !== 0) {
                    speakerLabel = `<span id="speaker">Speaker ${item.speaker}<span id='timeInfo'>${timeInfo}</span></span>`;
                }


                let currentLineText = item.text || "";

                if (idx === lines.length - 1) { 
                    if (!isFinalizing) {
                        if (remaining_time_transcription > 0) {
                             speakerLabel += `<span class="label_transcription"><span class="spinner"></span>Transcription lag <span id='timeInfo'>${remaining_time_transcription}s</span></span>`;
                        }
                        if (buffer_diarization && remaining_time_diarization > 0) {
                             speakerLabel += `<span class="label_diarization"><span class="spinner"></span>Diarization lag<span id='timeInfo'>${remaining_time_diarization}s</span></span>`;
                        }
                    }

                    if (buffer_diarization) {
                        if (isFinalizing) {
                            currentLineText += (currentLineText.length > 0 && buffer_diarization.trim().length > 0 ? " " : "") + buffer_diarization.trim();
                        } else {
                            currentLineText += `<span class="buffer_diarization">${buffer_diarization}</span>`;
                        }
                    }
                    if (buffer_transcription) {
                        if (isFinalizing) {
                            currentLineText += (currentLineText.length > 0 && buffer_transcription.trim().length > 0 ? " " : "") + buffer_transcription.trim();
                        } else {
                            currentLineText += `<span class="buffer_transcription">${buffer_transcription}</span>`;
                        }
                    }
                }
                
                return currentLineText.trim().length > 0 || speakerLabel.length > 0
                    ? `<p>${speakerLabel}<br/><div class='textcontent'>${currentLineText}</div></p>`
                    : `<p>${speakerLabel}<br/></p>`; 
            }).join("");

            linesTranscriptDiv.innerHTML = linesHtml;
        }

        function updateTimer() {
            if (!startTime) return;
            
            const elapsed = Math.floor((Date.now() - startTime) / 1000);
            const minutes = Math.floor(elapsed / 60).toString().padStart(2, "0");
            const seconds = (elapsed % 60).toString().padStart(2, "0");
            timerElement.textContent = `${minutes}:${seconds}`;
        }

        function drawWaveform() {
            if (!analyser) return;
            
            const bufferLength = analyser.frequencyBinCount;
            const dataArray = new Uint8Array(bufferLength);
            analyser.getByteTimeDomainData(dataArray);
            
            waveCtx.clearRect(0, 0, waveCanvas.width / (window.devicePixelRatio || 1), waveCanvas.height / (window.devicePixelRatio || 1));
            waveCtx.lineWidth = 1;
            waveCtx.strokeStyle = 'rgb(0, 0, 0)';
            waveCtx.beginPath();
            
            const sliceWidth = (waveCanvas.width / (window.devicePixelRatio || 1)) / bufferLength;
            let x = 0;
            
            for (let i = 0; i < bufferLength; i++) {
                const v = dataArray[i] / 128.0;
                const y = v * (waveCanvas.height / (window.devicePixelRatio || 1)) / 2;
                
                if (i === 0) {
                    waveCtx.moveTo(x, y);
                } else {
                    waveCtx.lineTo(x, y);
                }
                
                x += sliceWidth;
            }
            
            waveCtx.lineTo(waveCanvas.width / (window.devicePixelRatio || 1), waveCanvas.height / (window.devicePixelRatio || 1) / 2);
            waveCtx.stroke();
            
            animationFrame = requestAnimationFrame(drawWaveform);
        }

        async function startRecording() {
            try {
                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                
                audioContext = new (window.AudioContext || window.webkitAudioContext)();
                analyser = audioContext.createAnalyser();
                analyser.fftSize = 256;
                microphone = audioContext.createMediaStreamSource(stream);
                microphone.connect(analyser);
                
                recorder = new MediaRecorder(stream, { mimeType: "audio/webm" });
                recorder.ondataavailable = (e) => {
                    if (websocket && websocket.readyState === WebSocket.OPEN) {
                        websocket.send(e.data);
                    }
                };
                recorder.start(chunkDuration);
                
                startTime = Date.now();
                timerInterval = setInterval(updateTimer, 1000);
                drawWaveform();
                
                isRecording = true;
                updateUI();
            } catch (err) {
                statusText.textContent = "Error accessing microphone. Please allow microphone access.";
                console.error(err);
            }
        }

        async function stopRecording() {
            userClosing = true;
            waitingForStop = true;
            
            if (websocket && websocket.readyState === WebSocket.OPEN) {
                // Send empty audio buffer as stop signal
                const emptyBlob = new Blob([], { type: 'audio/webm' });
                websocket.send(emptyBlob);
                statusText.textContent = "Recording stopped. Processing final audio...";
            }
            
            if (recorder) {
                recorder.stop();
                recorder = null;
            }
            
            if (microphone) {
                microphone.disconnect();
                microphone = null;
            }
            
            if (analyser) {
                analyser = null;
            }
            
            if (audioContext && audioContext.state !== 'closed') {
                try {
                    audioContext.close();
                } catch (e) {
                    console.warn("Could not close audio context:", e);
                }
                audioContext = null;
            }
            
            if (animationFrame) {
                cancelAnimationFrame(animationFrame);
                animationFrame = null;
            }
            
            if (timerInterval) {
                clearInterval(timerInterval);
                timerInterval = null;
            }            
            timerElement.textContent = "00:00";
            startTime = null;
            
            
            isRecording = false;
            updateUI();	
        }

        async function toggleRecording() {
            if (!isRecording) {
                if (waitingForStop) {
                    console.log("Waiting for stop, early return");
                    return;  // Early return, UI is already updated
                }
                console.log("Connecting to WebSocket");
                try {
                    // If we have an active WebSocket that's still processing, just restart audio capture
                    if (websocket && websocket.readyState === WebSocket.OPEN) {
                        await startRecording();
                    } else {
                        // If no active WebSocket or it's closed, create new one
                        await setupWebSocket();
                        await startRecording();
                    }
                } catch (err) {
                    statusText.textContent = "Could not connect to WebSocket or access mic. Aborted.";
                    console.error(err);
                }
            } else {
                console.log("Stopping recording");
                stopRecording();
            }
        }

        function updateUI() {
            recordButton.classList.toggle("recording", isRecording);
            recordButton.disabled = waitingForStop;

            if (waitingForStop) {
                if (statusText.textContent !== "Recording stopped. Processing final audio...") {
                     statusText.textContent = "Please wait for processing to complete...";
                }
            } else if (isRecording) {
                statusText.textContent = "Recording...";
            } else {
                if (statusText.textContent !== "Finished processing audio! Ready to record again." &&
                    statusText.textContent !== "Processing finalized or connection closed.") {
                    statusText.textContent = "Click to start transcription";
                }
            }
            if (!waitingForStop) {
                recordButton.disabled = false;
            }
        }

        recordButton.addEventListener("click", toggleRecording);
    </script>
</body>

</html>