-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1228 lines (993 loc) · 42 KB
/
Copy pathscript.js
File metadata and controls
1228 lines (993 loc) · 42 KB
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// DOM elements
const hamburger = document.querySelector('.hamburger');
const navMenu = document.querySelector('.nav-menu');
// Configuration for GitHub Pages deployment
const CONFIG = {
// Automatically detect if we're on GitHub Pages
isGitHubPages: window.location.hostname.includes('github.io'),
basePath: window.location.hostname.includes('github.io') ? '/MAGE' : '',
baseUrl: window.location.origin + (window.location.hostname.includes('github.io') ? '/MAGE' : '')
};
// Utility function to construct proper file paths
function getFilePath(relativePath) {
return CONFIG.basePath + '/' + relativePath;
}
// Initialize the application
document.addEventListener('DOMContentLoaded', function() {
initializeNavigation();
initializeAudioShowcase();
initializeScrollAnimations();
initializeLiveDemo();
});
// Navigation functionality
function initializeNavigation() {
// Mobile menu toggle
if (hamburger && navMenu) {
hamburger.addEventListener('click', () => {
hamburger.classList.toggle('active');
navMenu.classList.toggle('active');
});
}
// Smooth scrolling for navigation links
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
const target = document.querySelector(this.getAttribute('href'));
if (target) {
const offsetTop = target.offsetTop - 80; // Account for fixed navbar
window.scrollTo({
top: offsetTop,
behavior: 'smooth'
});
// Close mobile menu if open
if (hamburger && navMenu) {
hamburger.classList.remove('active');
navMenu.classList.remove('active');
}
}
});
});
// Update active navigation link on scroll
window.addEventListener('scroll', updateActiveNavLink);
}
function updateActiveNavLink() {
const sections = document.querySelectorAll('section[id]');
const scrollPos = window.scrollY + 100;
sections.forEach(section => {
const sectionTop = section.offsetTop;
const sectionHeight = section.offsetHeight;
const sectionId = section.getAttribute('id');
const navLink = document.querySelector(`a[href="#${sectionId}"]`);
if (scrollPos >= sectionTop && scrollPos < sectionTop + sectionHeight) {
document.querySelectorAll('.nav-link').forEach(link => link.classList.remove('active'));
if (navLink) navLink.classList.add('active');
}
});
}
// Audio showcase functionality
async function initializeAudioShowcase() {
const experimentsContainer = document.getElementById('experiments-container');
if (!experimentsContainer) return;
try {
console.log('Initializing audio showcase...');
console.log('Configuration:', CONFIG);
// Define experiment order as per instructions
const experimentOrder = ['librispeech', 'dns_no_reverb', 'dns_with_reverb', 'dns_real_records'];
// Load experiments that we know exist from workspace inspection
const knownExperiments = ['librispeech', 'dns_real_records'];
experimentsContainer.innerHTML = '';
for (const experiment of knownExperiments) {
console.log(`Loading experiment: ${experiment}`);
await loadExperiment(experiment, experimentsContainer);
}
console.log('Audio showcase initialization complete');
} catch (error) {
console.error('Error initializing audio showcase:', error);
experimentsContainer.innerHTML = `
<div class="error">
<h3>Error loading audio samples</h3>
<p>Please check the browser console for more details.</p>
<details>
<summary>Technical Details</summary>
<pre>${error.message}</pre>
</details>
</div>
`;
}
}
async function loadExperiment(experimentName, container) {
try {
console.log(`Loading experiment: ${experimentName}`);
// Get available models for this experiment
const models = await getAvailableModels(experimentName);
console.log(`Available models for ${experimentName}:`, models);
// Load transcript data from all available model directories
let allTranscripts = {};
for (const modelKey of Object.keys(models)) {
try {
const transcriptPath = getFilePath(`sample/${experimentName}/${modelKey}/trans.txt`);
console.log(`Attempting to load transcript from: ${transcriptPath}`);
const transcriptResponse = await fetch(transcriptPath);
console.log(`Transcript response for ${modelKey}:`, transcriptResponse.status, transcriptResponse.ok);
if (transcriptResponse.ok) {
const transcriptText = await transcriptResponse.text();
console.log(`Transcript text for ${modelKey}:`, transcriptText.substring(0, 100) + '...');
const modelTranscripts = parseTranscripts(transcriptText);
console.log(`Parsed transcripts for ${modelKey}:`, modelTranscripts);
allTranscripts[modelKey] = modelTranscripts;
}
} catch (error) {
console.log(`No transcripts found for ${experimentName}/${modelKey}:`, error);
}
}
console.log(`All transcripts for ${experimentName}:`, allTranscripts);
// Get sample files
const samples = await getSampleFiles(experimentName, models);
console.log(`Sample files for ${experimentName}:`, samples);
// Create experiment container
const experimentDiv = document.createElement('div');
experimentDiv.className = 'experiment';
experimentDiv.innerHTML = createExperimentHTML(experimentName, models, samples, allTranscripts);
container.appendChild(experimentDiv);
// Add event listeners for audio players
addAudioEventListeners(experimentDiv);
} catch (error) {
console.error(`Error loading experiment ${experimentName}:`, error);
}
}
async function getAvailableModels(experimentName) {
// Based on workspace inspection, define available models for each experiment
const modelMapping = {
'librispeech': {
'noisy': 'Noisy',
'clean': 'Clean',
'mage': 'MAGE',
'flow_se': 'Flow SE',
'sgmse': 'SGMSE',
'storm': 'STORM'
},
'dns_real_records': {
'noisy': 'Noisy',
'mage': 'MAGE',
'masksr': 'MaskSR'
}
};
return modelMapping[experimentName] || {};
}
async function getSampleFiles(experimentName, models) {
// Based on workspace inspection, get actual filenames
const sampleMapping = {
'librispeech': [
'1188-133604-0004',
'1284-1180-0029',
'4992-23283-0011',
'61-70970-0015'
],
'dns_real_records': [
'audioset_realrec_airconditioner_8v4sEeK2Owc',
'audioset_realrec_airconditioner_EK746oGQz6E',
'audioset_realrec_car_0AVTgzegI4s'
]
};
return sampleMapping[experimentName] || [];
}
function parseTranscripts(transcriptText) {
const transcripts = {};
const lines = transcriptText.trim().split('\n');
for (const line of lines) {
const colonIndex = line.indexOf(':');
if (colonIndex > -1) {
const filename = line.substring(0, colonIndex).replace('.wav', '');
const transcript = line.substring(colonIndex + 1).trim();
transcripts[filename] = transcript;
}
}
return transcripts;
}
function createExperimentHTML(experimentName, models, samples, allTranscripts) {
const experimentTitle = experimentName.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase());
const experimentDescription = getExperimentDescription(experimentName);
// Create table headers
const modelOrder = getModelOrder(models);
const headers = ['Sample', ...modelOrder.map(model => models[model])];
let html = `
<h3 class="experiment-title">${experimentTitle}</h3>
<p class="experiment-description">${experimentDescription}</p>
<div class="table-container">
<table class="samples-table">
<thead>
<tr>
${headers.map(header => `<th>${header}</th>`).join('')}
</tr>
</thead>
<tbody>
`;
// Create rows for each sample
samples.forEach((sample, index) => {
html += `
<tr>
<td class="sample-index" data-label="Sample">${index + 1}</td>
`;
modelOrder.forEach(modelKey => {
const modelLabel = models[modelKey];
const fileExtension = experimentName === 'librispeech' && modelKey === 'clean' ? 'flac' : 'wav';
const audioPath = getFilePath(`sample/${experimentName}/${modelKey}/${sample}.${fileExtension}`);
// Get transcript for this model/sample combination
// Prefer clean/ground truth transcript, fall back to model-specific transcript
let transcript = '';
let transcriptClass = '';
if (allTranscripts['clean'] && allTranscripts['clean'][sample]) {
transcript = allTranscripts['clean'][sample];
transcriptClass = 'ground-truth';
console.log(`Using clean transcript for ${sample}: ${transcript}`);
} else if (allTranscripts[modelKey] && allTranscripts[modelKey][sample]) {
transcript = allTranscripts[modelKey][sample];
console.log(`Using ${modelKey} transcript for ${sample}: ${transcript}`);
}
html += `
<td data-label="${modelLabel}">
<div class="audio-item">
<div class="audio-label ${modelKey === 'clean' ? 'ground-truth' : ''} ${modelKey === 'mage' ? 'mage' : ''}">${modelLabel}</div>
<div class="audio-player">
<audio controls data-sample="${sample}" data-model="${modelKey}" data-audio-path="${audioPath}">
<source src="${audioPath}" type="audio/${fileExtension === 'flac' ? 'flac' : 'wav'}">
Your browser does not support the audio element.
</audio>
</div>
${transcript ? `<div class="transcript ${transcriptClass}">"${transcript}"</div>` : ''}
<div class="spectrogram-container" id="spectrogram-${sample}-${modelKey}">
<div class="spectrogram-label">Spectrogram - ${modelLabel}</div>
<div class="spectrogram-placeholder">
<i class="fas fa-chart-line"></i> Spectrogram visualization
</div>
</div>
</div>
</td>
`;
});
html += '</tr>';
});
html += `
</tbody>
</table>
</div>
`;
return html;
}
function getModelOrder(models) {
// Define the order based on instructions: Noisy, Clean (Ground Truth), MAGE (ours), Others
const order = ['noisy', 'clean', 'mage'];
const others = Object.keys(models).filter(key => !order.includes(key));
return [...order.filter(key => models[key]), ...others];
}
function getExperimentDescription(experimentName) {
const descriptions = {
'librispeech': 'Clean speech samples from LibriSpeech dataset with various noise conditions and enhancement results.',
'dns_real_records': 'Real-world recorded audio samples with background noise, comparing different enhancement methods.',
'dns_no_reverb': 'DNS Challenge dataset samples without reverberation effects.',
'dns_with_reverb': 'DNS Challenge dataset samples with reverberation effects.'
};
return descriptions[experimentName] || 'Audio enhancement comparison samples.';
}
function addAudioEventListeners(experimentDiv) {
const audioElements = experimentDiv.querySelectorAll('audio');
audioElements.forEach(audio => {
// Add load event listener for debugging
audio.addEventListener('loadstart', function() {
console.log(`Loading audio: ${this.dataset.audioPath}`);
});
audio.addEventListener('loadeddata', function() {
console.log(`Successfully loaded audio: ${this.dataset.audioPath}`);
});
audio.addEventListener('canplay', function() {
console.log(`Audio ready to play: ${this.dataset.audioPath}`);
});
// Add click event for spectrogram toggle
audio.addEventListener('click', function(e) {
const sample = this.dataset.sample;
const model = this.dataset.model;
const spectrogramContainer = document.getElementById(`spectrogram-${sample}-${model}`);
if (spectrogramContainer) {
spectrogramContainer.classList.toggle('show');
// Animate the toggle
if (spectrogramContainer.classList.contains('show')) {
spectrogramContainer.style.maxHeight = spectrogramContainer.scrollHeight + 'px';
} else {
spectrogramContainer.style.maxHeight = '0';
}
}
});
// Sync audio playback - pause others when one plays
audio.addEventListener('play', function() {
audioElements.forEach(otherAudio => {
if (otherAudio !== this && !otherAudio.paused) {
otherAudio.pause();
}
});
});
// Enhanced error handling for GitHub Pages
audio.addEventListener('error', function(e) {
const audioPath = this.dataset.audioPath;
const parent = this.parentElement;
console.error(`Audio loading error for: ${audioPath}`, e);
console.error(`Error details:`, {
error: e.target.error,
code: e.target.error ? e.target.error.code : 'unknown',
networkState: this.networkState,
readyState: this.readyState,
currentSrc: this.currentSrc
});
// Try alternative path construction for GitHub Pages
if (CONFIG.isGitHubPages && !audioPath.startsWith('http')) {
console.log(`Attempting alternative path for GitHub Pages...`);
const alternativePath = `${CONFIG.baseUrl}/${audioPath.replace(/^\/+/, '')}`;
console.log(`Trying alternative path: ${alternativePath}`);
// Create a new source element with the alternative path
const newSource = document.createElement('source');
newSource.src = alternativePath;
newSource.type = this.querySelector('source').type;
// Replace the existing source
const existingSource = this.querySelector('source');
if (existingSource) {
existingSource.remove();
}
this.appendChild(newSource);
this.load(); // Reload the audio with new source
return;
}
// If still failing, show error message
parent.innerHTML = `
<div class="audio-error">
<i class="fas fa-exclamation-triangle"></i>
<span>Audio file not available</span>
<div class="error-details">Path: ${audioPath}</div>
</div>
`;
});
});
}
// Scroll animations
function initializeScrollAnimations() {
const observerOptions = {
threshold: 0.1,
rootMargin: '0px 0px -50px 0px'
};
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('animate');
}
});
}, observerOptions);
// Observe elements for animation
document.querySelectorAll('.section-title, .experiment, .metric-card').forEach(el => {
observer.observe(el);
});
}
// Navbar background on scroll
window.addEventListener('scroll', () => {
const navbar = document.querySelector('.navbar');
if (navbar) {
if (window.scrollY > 50) {
navbar.style.background = 'rgba(240, 240, 240, 0.98)';
navbar.style.boxShadow = '0 2px 20px rgba(51, 51, 51, 0.1)';
} else {
navbar.style.background = 'rgba(240, 240, 240, 0.95)';
navbar.style.boxShadow = 'none';
}
}
});
// Utility function for copying citation (if needed)
function copyCitation() {
const citationText = document.getElementById('citation-text');
if (!citationText) return;
const text = citationText.textContent;
navigator.clipboard.writeText(text).then(() => {
const copyBtn = document.querySelector('.copy-btn');
if (copyBtn) {
const originalText = copyBtn.innerHTML;
copyBtn.innerHTML = '<i class="fas fa-check"></i> Copied!';
copyBtn.style.background = '#059669';
setTimeout(() => {
copyBtn.innerHTML = originalText;
copyBtn.style.background = '#2563eb';
}, 2000);
}
}).catch(err => {
console.error('Failed to copy citation: ', err);
});
}
// Export functions for global access
window.copyCitation = copyCitation;
// Live Demo Functionality
let mediaRecorder = null;
let recordedChunks = [];
let recordingTimer = null;
let recordingStartTime = null;
let currentAudioBlob = null;
let isRecording = false;
function initializeLiveDemo() {
console.log('Initializing live demo...');
// Initialize tab switching
initializeTabs();
// Initialize recording functionality
initializeRecording();
// Initialize file upload
initializeFileUpload();
// Initialize process button
initializeProcessButton();
console.log('Live demo initialized');
}
// Tab Functionality
function initializeTabs() {
const tabButtons = document.querySelectorAll('.tab-button');
const tabContents = document.querySelectorAll('.tab-content');
tabButtons.forEach(button => {
button.addEventListener('click', () => {
const targetTab = button.dataset.tab;
// Update active tab button
tabButtons.forEach(btn => btn.classList.remove('active'));
button.classList.add('active');
// Update active tab content
tabContents.forEach(content => {
content.classList.remove('active');
if (content.id === `${targetTab}-tab`) {
content.classList.add('active');
}
});
// Reset demo state when switching tabs
resetDemo();
});
});
}
// Recording Functionality
async function initializeRecording() {
const startBtn = document.getElementById('start-recording');
const stopBtn = document.getElementById('stop-recording');
const clearBtn = document.getElementById('clear-recording');
if (!startBtn || !stopBtn || !clearBtn) {
console.error('Recording buttons not found');
return;
}
// Check if browser supports MediaRecorder
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
showError('Your browser does not support audio recording. Please use a modern browser like Chrome, Firefox, or Safari.');
startBtn.disabled = true;
return;
}
startBtn.addEventListener('click', startRecording);
stopBtn.addEventListener('click', stopRecording);
clearBtn.addEventListener('click', clearRecording);
}
async function startRecording() {
try {
console.log('Starting recording...');
// Request microphone access
const stream = await navigator.mediaDevices.getUserMedia({
audio: {
sampleRate: 16000, // Request 16kHz sample rate
channelCount: 1, // Mono audio
echoCancellation: true,
noiseSuppression: true
}
});
console.log('Microphone access granted');
// Check if browser supports the required audio format
const options = {
mimeType: 'audio/webm',
audioBitsPerSecond: 128000
};
// Fallback for browsers that don't support webm
if (!MediaRecorder.isTypeSupported(options.mimeType)) {
options.mimeType = 'audio/mp4';
if (!MediaRecorder.isTypeSupported(options.mimeType)) {
options.mimeType = 'audio/wav';
if (!MediaRecorder.isTypeSupported(options.mimeType)) {
delete options.mimeType; // Use default
}
}
}
console.log('Using MIME type:', options.mimeType || 'default');
mediaRecorder = new MediaRecorder(stream, options.mimeType ? options : undefined);
recordedChunks = [];
mediaRecorder.ondataavailable = (event) => {
if (event.data.size > 0) {
recordedChunks.push(event.data);
}
};
mediaRecorder.onstop = async () => {
console.log('Recording stopped');
// Stop all tracks to release microphone
stream.getTracks().forEach(track => track.stop());
// Create blob from recorded chunks
const mimeType = mediaRecorder.mimeType || 'audio/wav';
const audioBlob = new Blob(recordedChunks, { type: mimeType });
console.log('Audio blob created:', {
size: audioBlob.size,
type: audioBlob.type
});
// Convert to 16kHz WAV format
await processRecordedAudio(audioBlob);
};
// Start recording
mediaRecorder.start(100); // Collect data every 100ms
isRecording = true;
recordingStartTime = Date.now();
// Update UI
updateRecordingUI(true);
startRecordingTimer();
console.log('Recording started successfully');
} catch (error) {
console.error('Error starting recording:', error);
if (error.name === 'NotAllowedError') {
showError('Microphone access denied. Please allow microphone access and try again.');
} else if (error.name === 'NotFoundError') {
showError('No microphone found. Please connect a microphone and try again.');
} else {
showError(`Recording error: ${error.message}`);
}
updateRecordingUI(false);
}
}
function stopRecording() {
if (mediaRecorder && isRecording) {
console.log('Stopping recording...');
mediaRecorder.stop();
isRecording = false;
// Update UI
updateRecordingUI(false);
stopRecordingTimer();
}
}
function clearRecording() {
console.log('Clearing recording...');
// Stop recording if active
if (isRecording) {
stopRecording();
}
// Clear recorded data
recordedChunks = [];
currentAudioBlob = null;
// Hide preview
const preview = document.getElementById('recording-preview');
if (preview) {
preview.style.display = 'none';
}
// Reset UI
updateRecordingUI(false);
updateProcessButton();
// Reset timer
const timer = document.querySelector('.recording-timer');
if (timer) {
timer.textContent = '00:00';
}
}
function updateRecordingUI(recording) {
const startBtn = document.getElementById('start-recording');
const stopBtn = document.getElementById('stop-recording');
const clearBtn = document.getElementById('clear-recording');
const indicator = document.getElementById('recording-indicator');
const statusText = indicator.querySelector('.status-text');
if (recording) {
startBtn.disabled = true;
stopBtn.disabled = false;
clearBtn.disabled = true;
indicator.classList.add('recording');
statusText.textContent = 'Recording...';
} else {
startBtn.disabled = false;
stopBtn.disabled = true;
clearBtn.disabled = currentAudioBlob ? false : true;
indicator.classList.remove('recording');
statusText.textContent = currentAudioBlob ? 'Recording complete' : 'Ready to record';
}
}
function startRecordingTimer() {
const timer = document.querySelector('.recording-timer');
recordingTimer = setInterval(() => {
if (recordingStartTime) {
const elapsed = Date.now() - recordingStartTime;
const seconds = Math.floor(elapsed / 1000);
const minutes = Math.floor(seconds / 60);
const displaySeconds = seconds % 60;
timer.textContent = `${minutes.toString().padStart(2, '0')}:${displaySeconds.toString().padStart(2, '0')}`;
}
}, 1000);
}
function stopRecordingTimer() {
if (recordingTimer) {
clearInterval(recordingTimer);
recordingTimer = null;
}
}
async function processRecordedAudio(audioBlob) {
try {
console.log('Processing recorded audio...');
// Convert audio to 16kHz WAV format
const processedBlob = await convertAudioTo16kHz(audioBlob);
currentAudioBlob = processedBlob;
// Show preview
showAudioPreview(processedBlob, 'recording-preview', 'recording-info');
// Update process button
updateProcessButton();
console.log('Audio processing complete');
} catch (error) {
console.error('Error processing audio:', error);
showError(`Audio processing error: ${error.message}`);
}
}
// File Upload Functionality
function initializeFileUpload() {
const uploadArea = document.getElementById('file-upload-area');
const fileInput = document.getElementById('audio-file-input');
if (!uploadArea || !fileInput) {
console.error('Upload elements not found');
return;
}
// Click to upload
uploadArea.addEventListener('click', () => {
fileInput.click();
});
// File selection
fileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
if (file) {
handleFileUpload(file);
}
});
// Drag and drop
uploadArea.addEventListener('dragover', (event) => {
event.preventDefault();
uploadArea.classList.add('drag-over');
});
uploadArea.addEventListener('dragleave', () => {
uploadArea.classList.remove('drag-over');
});
uploadArea.addEventListener('drop', (event) => {
event.preventDefault();
uploadArea.classList.remove('drag-over');
const file = event.dataTransfer.files[0];
if (file && file.type.startsWith('audio/')) {
handleFileUpload(file);
} else {
showError('Please upload a valid audio file.');
}
});
}
async function handleFileUpload(file) {
try {
console.log('Handling file upload:', {
name: file.name,
size: file.size,
type: file.type
});
// Validate file type
if (!file.type.startsWith('audio/')) {
showError('Please select a valid audio file.');
return;
}
// Validate file size (limit to 50MB)
const maxSize = 50 * 1024 * 1024; // 50MB
if (file.size > maxSize) {
showError('File size must be less than 50MB.');
return;
}
// Convert file to blob and process
const audioBlob = new Blob([file], { type: file.type });
// Convert to 16kHz WAV format
const processedBlob = await convertAudioTo16kHz(audioBlob);
currentAudioBlob = processedBlob;
// Show file info
showFileInfo(file);
showAudioPreview(processedBlob, 'upload-info', 'upload-info');
// Update process button
updateProcessButton();
console.log('File upload complete');
} catch (error) {
console.error('Error handling file upload:', error);
showError(`File upload error: ${error.message}`);
}
}
function showFileInfo(file) {
const fileInfo = document.getElementById('file-info');
const fileName = document.getElementById('file-name');
const fileSize = document.getElementById('file-size');
if (!fileInfo || !fileName || !fileSize) return;
fileName.textContent = file.name;
fileSize.textContent = formatFileSize(file.size);
fileInfo.style.display = 'block';
}
function showAudioPreview(audioBlob, containerId, infoId) {
const container = document.getElementById(containerId);
const audioElement = container.querySelector('audio');
const infoElement = document.getElementById(infoId);
if (!container || !audioElement) return;
// Create object URL for audio playback
const audioUrl = URL.createObjectURL(audioBlob);
audioElement.src = audioUrl;
// Show container
container.style.display = 'block';
// Show audio info
if (infoElement) {
infoElement.textContent = `Processed: 16kHz WAV, ${formatFileSize(audioBlob.size)}`;
}
// Clean up URL when audio is loaded
audioElement.addEventListener('loadstart', () => {
console.log('Audio preview loaded');
});
}
// Audio Processing Utilities
async function convertAudioTo16kHz(audioBlob) {
return new Promise((resolve, reject) => {
try {
console.log('Converting audio to 16kHz...');
// Create audio context with 16kHz sample rate
const audioContext = new (window.AudioContext || window.webkitAudioContext)({
sampleRate: 16000
});
const fileReader = new FileReader();
fileReader.onload = async (event) => {
try {
const arrayBuffer = event.target.result;
const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
console.log('Original audio:', {
sampleRate: audioBuffer.sampleRate,
channels: audioBuffer.numberOfChannels,
duration: audioBuffer.duration
});
// Resample to 16kHz if needed
let resampledBuffer = audioBuffer;
if (audioBuffer.sampleRate !== 16000) {
resampledBuffer = await resampleAudio(audioBuffer, 16000);
}
// Convert to mono if stereo
if (resampledBuffer.numberOfChannels > 1) {
resampledBuffer = convertToMono(resampledBuffer);
}
console.log('Processed audio:', {
sampleRate: resampledBuffer.sampleRate,
channels: resampledBuffer.numberOfChannels,
duration: resampledBuffer.duration
});
// Convert to WAV blob
const wavBlob = audioBufferToWav(resampledBuffer);
// Clean up
audioContext.close();
resolve(wavBlob);
} catch (error) {
console.error('Error processing audio:', error);
audioContext.close();
reject(error);
}
};
fileReader.onerror = () => {
audioContext.close();
reject(new Error('Error reading audio file'));
};
fileReader.readAsArrayBuffer(audioBlob);
} catch (error) {
console.error('Error setting up audio conversion:', error);
reject(error);
}
});
}
async function resampleAudio(audioBuffer, targetSampleRate) {
const sourceContext = audioBuffer.context || new AudioContext();
const targetContext = new OfflineAudioContext(1, audioBuffer.duration * targetSampleRate, targetSampleRate);
// Create source and destination
const source = targetContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(targetContext.destination);
// Start processing
source.start();
const resampledBuffer = await targetContext.startRendering();
targetContext.close();
return resampledBuffer;
}
function convertToMono(audioBuffer) {
const context = audioBuffer.context || new AudioContext();
const monoBuffer = context.createBuffer(1, audioBuffer.length, audioBuffer.sampleRate);
const monoData = monoBuffer.getChannelData(0);
// Mix all channels to mono
for (let i = 0; i < audioBuffer.length; i++) {
let sum = 0;
for (let channel = 0; channel < audioBuffer.numberOfChannels; channel++) {
sum += audioBuffer.getChannelData(channel)[i];
}
monoData[i] = sum / audioBuffer.numberOfChannels;
}
return monoBuffer;
}
function audioBufferToWav(audioBuffer) {
const length = audioBuffer.length;
const sampleRate = audioBuffer.sampleRate;
const channelData = audioBuffer.getChannelData(0);
// Calculate buffer size
const bufferLength = 44 + length * 2; // WAV header (44 bytes) + data
const arrayBuffer = new ArrayBuffer(bufferLength);
const view = new DataView(arrayBuffer);
// WAV header
const writeString = (offset, string) => {
for (let i = 0; i < string.length; i++) {
view.setUint8(offset + i, string.charCodeAt(i));
}
};
writeString(0, 'RIFF');
view.setUint32(4, bufferLength - 8, true);