-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathscripts.js
More file actions
1454 lines (1278 loc) · 46.4 KB
/
Copy pathscripts.js
File metadata and controls
1454 lines (1278 loc) · 46.4 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
document.addEventListener("DOMContentLoaded", function () {
// Global state
window.audioLoaded = false;
// Initialize components
initWaveform();
initNavigation();
initFormatListeners();
/**
* Simple file upload handler
*/
(function () {
// Get DOM elements
const fileInput = document.getElementById("file-input");
const uploadBtn = document.getElementById("upload-btn");
const uploadDropzone = document.getElementById("upload-dropzone");
const fileList = document.getElementById("file-list");
if (!fileInput || !uploadBtn || !uploadDropzone || !fileList) {
console.error("Required upload elements not found");
return;
}
// State flags
let isUploading = false;
let isProcessingClick = false;
// Store uploaded files
window.uploadedFiles = [];
// Event listeners
fileInput.addEventListener("change", (e) => {
if (isUploading) return;
isUploading = true;
if (e.target.files?.length > 0) handleFiles(e.target.files);
isUploading = false;
});
uploadBtn.addEventListener("click", () => {
if (isProcessingClick) return;
isProcessingClick = true;
fileInput.click();
setTimeout(() => {
isProcessingClick = false;
}, 300);
});
// Drag and drop handlers
uploadDropzone.addEventListener("dragover", function (e) {
e.preventDefault();
this.classList.add("active");
});
uploadDropzone.addEventListener("dragleave", function () {
this.classList.remove("active");
});
uploadDropzone.addEventListener("drop", function (e) {
e.preventDefault();
this.classList.remove("active");
if (isUploading) return;
isUploading = true;
if (e.dataTransfer.files?.length > 0) handleFiles(e.dataTransfer.files);
isUploading = false;
});
// Make dropzone clickable
uploadDropzone.addEventListener("click", (e) => {
if (e.target !== fileInput) fileInput.click();
});
// Process uploaded files
function handleFiles(files) {
// Hide hero section when files are uploaded
hideMarketingSectionsOnFileUpload();
let addedCount = 0;
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (!file.type.startsWith("audio/")) {
console.warn("Skipping non-audio file:", file.name);
continue;
}
// Add to global uploaded files array
window.uploadedFiles.push(file);
// Create file item in the list
const fileItem = document.createElement("li");
fileItem.className = "list-group-item file-item";
fileItem.innerHTML = `
<div class="d-flex justify-content-between align-items-center">
<span>${file.name}</span>
<span class="badge">${formatFileSize(file.size)}</span>
</div>
`;
// Add click handler to select file
fileItem.addEventListener("click", function () {
document
.querySelectorAll(".file-item")
.forEach((item) => item.classList.remove("active"));
fileItem.classList.add("active");
window.loadAudioFile(file, file.name);
});
fileList.appendChild(fileItem);
addedCount++;
}
// If we added any audio files, hide the empty placeholder and update the badge immediately
if (addedCount > 0) {
const emptyPlaceholder = document.getElementById("empty-file-list");
if (emptyPlaceholder) emptyPlaceholder.style.display = "none";
const fileCountBadge = document.getElementById("file-count");
if (fileCountBadge) {
const countNow = fileList.querySelectorAll(".file-item").length;
fileCountBadge.textContent = countNow;
}
}
}
// Format file size for display
function formatFileSize(bytes) {
if (bytes < 1024) return bytes + " B";
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + " KB";
return (bytes / (1024 * 1024)).toFixed(1) + " MB";
}
})();
});
// Initialize format change listeners
function initFormatListeners() {
// Listen for settings format changes
document.addEventListener("app:formatChanged", (e) => {
if (e.detail?.format) updateNormalizedColumnVisibility(e.detail.format);
});
// Listen for settings loaded event
document.addEventListener("app:settingsLoaded", (e) => {
if (e.detail?.settings)
updateNormalizedColumnVisibility(e.detail.settings.transcriptFormat);
});
// Listen for audio loaded event
document.addEventListener("app:audioLoaded", (e) => {
window.audioLoaded = true;
if (window.settingsHandler?.getSettings) {
const settings = window.settingsHandler.getSettings();
updateNormalizedColumnVisibility(settings.transcriptFormat);
}
});
// Initially hide normalized column by default
setTimeout(() => {
const normalizedColumn = document.getElementById("normalized-column");
if (normalizedColumn) normalizedColumn.classList.add("d-none");
}, 100);
}
// Helper function to update normalized column visibility
function updateNormalizedColumnVisibility(format) {
const normalizedColumn = document.getElementById("normalized-column");
if (!normalizedColumn) return;
if (format === "ljspeech" && window.audioLoaded) {
normalizedColumn.classList.remove("d-none");
} else {
normalizedColumn.classList.add("d-none");
}
}
// Function to initialize navigation
function initNavigation() {
document.querySelectorAll(".nav-link").forEach((tab) => {
tab.addEventListener("click", function (e) {
// Get the clicked tab's id
const tabId = this.id;
// First, remove active class from all tabs
document.querySelectorAll(".nav-link").forEach((t) => {
t.classList.remove("active");
});
// Then add active class to clicked tab
this.classList.add("active");
// Toggle marketing sections visibility based on active tab
toggleMarketingSections(tabId);
// Perform tab-specific actions
if (tabId === "files-tab") {
// Show file management interface
document.getElementById("file-sidebar").classList.remove("d-none");
document.getElementById("audio-editor").classList.remove("d-none");
// Hide settings if visible
const settingsContainer = document.getElementById("settings-container");
if (settingsContainer) settingsContainer.classList.add("d-none");
// Hide export if visible
const exportContainer = document.getElementById("export-container");
if (exportContainer) exportContainer.classList.add("d-none");
} else if (tabId === "settings-tab") {
// Show settings interface
document.getElementById("file-sidebar").classList.add("d-none");
document.getElementById("audio-editor").classList.add("d-none");
// Create settings UI if not already created
let settingsContainer = document.getElementById("settings-container");
if (!settingsContainer) {
settingsContainer = window.settingsHandler?.createSettingsUI();
}
if (settingsContainer) {
settingsContainer.classList.remove("d-none");
}
// Hide export if visible
const exportContainer = document.getElementById("export-container");
if (exportContainer) exportContainer.classList.add("d-none");
} else if (tabId === "export-tab") {
// Show export interface
document.getElementById("file-sidebar").classList.add("d-none");
document.getElementById("audio-editor").classList.add("d-none");
// Hide settings if visible
const settingsContainer = document.getElementById("settings-container");
if (settingsContainer) settingsContainer.classList.add("d-none");
// Create or show export UI
let exportContainer = document.getElementById("export-container");
if (exportContainer) {
exportContainer.classList.remove("d-none");
}
}
});
});
}
// Function to toggle visibility of marketing sections (hero, features, how-it-works)
function toggleMarketingSections(activeTabId) {
const marketingSections = [
document.querySelector(".hero-section"),
document.querySelector(".features-section"),
document.querySelector(".how-it-works-section"),
];
// Only show marketing sections on the files tab (main view)
const shouldShowMarketing = activeTabId === "files-tab";
marketingSections.forEach((section) => {
if (section) {
if (shouldShowMarketing) {
// Reset any inline styles that may have been set during collapse
section.style.opacity = "";
section.style.height = "";
section.style.margin = "";
section.classList.remove("d-none");
} else {
section.classList.add("d-none");
}
}
});
}
// Function to hide marketing sections when files are uploaded
function hideMarketingSectionsOnFileUpload() {
const marketingSections = [
document.querySelector(".hero-section"),
document.querySelector(".features-section"),
document.querySelector(".how-it-works-section"),
];
// Hide marketing sections with a nice fade-out effect
marketingSections.forEach((section) => {
if (section) {
// Add transition if it doesn't exist
if (!section.style.transition) {
section.style.transition =
"opacity 0.5s ease, height 0.5s ease, margin 0.5s ease";
}
// First fade out
section.style.opacity = "0";
// Then hide after transition completes
setTimeout(() => {
section.classList.add("d-none");
// Do not permanently set height/margin to avoid layout break when showing again
}, 500);
}
});
// Set a flag to remember that marketing sections have been hidden
window.marketingSectionsHidden = true;
}
// Function to initialize WaveSurfer
function initWaveform() {
// Define gradient colors for waveform
const gradient = document.createElement("canvas").getContext("2d");
const gradientFill = gradient.createLinearGradient(0, 0, 0, 128);
gradientFill.addColorStop(0, "rgba(58, 134, 255, 0.8)");
gradientFill.addColorStop(1, "rgba(109, 93, 252, 0.4)");
const progressGradient = document.createElement("canvas").getContext("2d");
const progressGradientFill = progressGradient.createLinearGradient(
0,
0,
0,
128
);
progressGradientFill.addColorStop(0, "rgba(58, 134, 255, 1)");
progressGradientFill.addColorStop(1, "rgba(109, 93, 252, 0.8)");
// Create WaveSurfer instance with enhanced styling - Updated for WaveSurfer v7.x
// Resolve plugins across versions (v6/v7 UMD names)
const RegionsPluginFactory =
(window.Regions && window.Regions.create ? window.Regions : null) ||
(window.RegionsPlugin && window.RegionsPlugin.create
? window.RegionsPlugin
: null) ||
(WaveSurfer.regions && WaveSurfer.regions.create
? WaveSurfer.regions
: null);
const CursorPluginFactory =
(window.Cursor && window.Cursor.create ? window.Cursor : null) ||
(window.CursorPlugin && window.CursorPlugin.create
? window.CursorPlugin
: null) ||
(WaveSurfer.cursor && WaveSurfer.cursor.create ? WaveSurfer.cursor : null);
const pluginList = [];
if (RegionsPluginFactory) {
pluginList.push(
RegionsPluginFactory.create({
dragSelection: true,
slop: 5,
maxRegions: 1,
color: "rgba(115, 104, 208, 0.52)",
maxRegions: 1,
formatTimeCallback: function (sec) {
return formatTime(sec);
},
})
);
}
if (CursorPluginFactory) {
pluginList.push(
CursorPluginFactory.create({
showTime: true,
opacity: 1,
customShowTimeStyle: {
"background-color": "#000",
color: "#fff",
padding: "2px 5px",
"font-size": "10px",
"border-radius": "3px",
},
})
);
}
window.wavesurfer = WaveSurfer.create({
container: "#waveform",
waveColor: gradientFill,
progressColor: progressGradientFill,
cursorColor: "rgba(58, 134, 255, 0.7)",
height: 140,
barWidth: 3,
barGap: 1,
barRadius: 3,
normalize: true,
minPxPerSec: 50,
hideScrollbar: true,
autoCenter: true,
plugins: pluginList,
});
// Add loading indicator
const loadingIndicator = document.createElement("div");
loadingIndicator.id = "waveform-loading";
loadingIndicator.innerHTML = `
<div class="spinner">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
<div class="loading-text">Loading audio...</div>
`;
loadingIndicator.style.cssText = `
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(255, 255, 255, 0.8);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
z-index: 10;
transition: opacity 0.3s ease;
opacity: 0;
pointer-events: none;
border-radius: var(--border-radius);
`;
const spinnerStyle = document.createElement("style");
spinnerStyle.textContent = `
.spinner {
width: 70px;
text-align: center;
}
.spinner > div {
width: 12px;
height: 12px;
background-color: var(--primary-color);
border-radius: 100%;
display: inline-block;
animation: sk-bouncedelay 1.4s infinite ease-in-out both;
margin: 0 3px;
}
.spinner .bounce1 {
animation-delay: -0.32s;
}
.spinner .bounce2 {
animation-delay: -0.16s;
}
.loading-text {
margin-top: 12px;
font-size: 14px;
color: var(--text-secondary);
}
@keyframes sk-bouncedelay {
0%, 80%, 100% {
transform: scale(0);
} 40% {
transform: scale(1.0);
}
}
`;
document.head.appendChild(spinnerStyle);
const waveformContainer = document.getElementById("waveform-container");
if (waveformContainer) {
waveformContainer.style.position = "relative";
waveformContainer.appendChild(loadingIndicator);
}
// Set up WaveSurfer event listeners
window.wavesurfer.on("loading", function (percent) {
const loadingElement = document.getElementById("waveform-loading");
if (loadingElement) {
loadingElement.style.opacity = "1";
loadingElement.querySelector(
".loading-text"
).textContent = `Loading audio... ${Math.round(percent)}%`;
}
});
window.wavesurfer.on("ready", function () {
// Hide loading indicator with fade effect
const loadingElement = document.getElementById("waveform-loading");
if (loadingElement) {
loadingElement.style.opacity = "0";
}
showAudioEditor();
updateTimeDisplay();
// Add a subtle animation to the waveform to draw attention
const waveformElement = document.querySelector("#waveform wave");
if (waveformElement) {
waveformElement.style.transition = "transform 0.5s ease-out";
waveformElement.style.transform = "scaleY(0.9)";
setTimeout(() => {
waveformElement.style.transform = "scaleY(1)";
}, 100);
}
document.dispatchEvent(new CustomEvent("wavesurfer:ready"));
// Auto-play if enabled in settings
if (window.settingsHandler?.getSettings) {
const settings = window.settingsHandler.getSettings();
if (settings.audioSettings?.autoPlay) {
window.wavesurfer.play();
updatePlayButton(true);
}
}
});
// Region events - updated for v7
window.wavesurfer.on("region-created", function (region) {
ensureSingleRegion(region);
updateRegionControls(true);
// Add subtle animation to region
region.element.style.transition = "background 0.3s ease";
const originalColor = region.element.style.background;
region.element.style.background = "rgba(109, 93, 252, 0.4)";
setTimeout(() => {
region.element.style.background = originalColor;
}, 300);
});
window.wavesurfer.on("region-update-end", () => updateRegionControls(true));
window.wavesurfer.on("region-removed", () => updateRegionControls(false));
window.wavesurfer.on("error", (err) => {
console.error("WaveSurfer error:", err);
const loadingElement = document.getElementById("waveform-loading");
if (loadingElement) {
loadingElement.querySelector(
".loading-text"
).textContent = `Error loading audio: ${err.message}`;
loadingElement.querySelector(".loading-text").style.color =
"var(--danger-color)";
// Add a retry button
if (!loadingElement.querySelector(".retry-button")) {
const retryButton = document.createElement("button");
retryButton.className = "btn btn-sm btn-primary mt-3 retry-button";
retryButton.innerHTML = '<i class="fas fa-redo-alt me-2"></i>Retry';
retryButton.addEventListener("click", function () {
const fileName = document.getElementById("current-file").textContent;
// Find the file in the uploaded files
const file = window.uploadedFiles.find((f) => f.name === fileName);
if (file) {
window.loadAudioFile(file, fileName);
} else {
alert("File not found. Please try uploading again.");
}
});
loadingElement.appendChild(retryButton);
}
}
});
window.wavesurfer.on("timeupdate", updateTimeDisplay);
window.wavesurfer.on("seeking", updateTimeDisplay);
// Add play/pause animation
window.wavesurfer.on("play", function () {
updatePlayButton(true);
// Add a subtle pulse animation to the waveform
const waveformElement = document.querySelector("#waveform wave");
if (waveformElement) {
waveformElement.classList.add("pulse-animation");
}
});
window.wavesurfer.on("pause", function () {
updatePlayButton(false);
// Remove pulse animation
const waveformElement = document.querySelector("#waveform wave");
if (waveformElement) {
waveformElement.classList.remove("pulse-animation");
}
});
// Add pulse animation style
const pulseStyle = document.createElement("style");
pulseStyle.textContent = `
.pulse-animation {
animation: pulse 2s infinite;
}
@keyframes pulse {
0% {
transform: scaleY(1);
}
50% {
transform: scaleY(1.02);
}
100% {
transform: scaleY(1);
}
}
`;
document.head.appendChild(pulseStyle);
// Set up play/stop toggle button
setupPlayButton();
// Set up volume control
setupVolumeControl();
// Set up playback speed control
setupPlaybackSpeed();
// Initialize audio cutting controls
initAudioCuttingControls();
}
// Show audio editor and hide empty state
function showAudioEditor() {
const playbackControls = document.getElementById("playback-controls");
const waveformContainer = document.getElementById("waveform-container");
const editingTools = document.getElementById("editing-tools");
const emptyState = document.getElementById("empty-state");
const transcriptSection = document.getElementById("transcript-section");
if (playbackControls) playbackControls.classList.remove("d-none");
if (waveformContainer) waveformContainer.classList.remove("d-none");
if (editingTools) editingTools.classList.remove("d-none");
if (transcriptSection) transcriptSection.classList.remove("d-none");
if (emptyState) emptyState.classList.add("d-none");
// Enable buttons that require audio to be loaded
document.querySelectorAll("#editing-tools button").forEach((btn) => {
btn.removeAttribute("disabled");
});
}
// Ensure only one region exists at a time
function ensureSingleRegion(region) {
const regions = getRegionsList();
if (regions.length > 1) {
regions.forEach((existingRegion) => {
if (existingRegion.id !== region.id) existingRegion.remove();
});
}
}
// Resolve regions plugin across versions
function getRegionsPlugin() {
if (!window.wavesurfer) return null;
return (
window.wavesurfer.regions ||
(window.wavesurfer.plugins && window.wavesurfer.plugins.regions) ||
null
);
}
function getRegionsList() {
const plugin = getRegionsPlugin();
if (!plugin) return [];
if (plugin.list) return Object.values(plugin.list);
if (typeof plugin.getRegions === "function") {
const r = plugin.getRegions();
if (Array.isArray(r)) return r;
if (r && typeof r === "object") return Object.values(r);
}
return [];
}
// Setup play/pause button
function setupPlayButton() {
const playBtn = document.getElementById("play-btn");
if (!playBtn) return;
playBtn.addEventListener("click", function () {
if (window.wavesurfer.isPlaying()) {
window.wavesurfer.pause();
} else {
window.wavesurfer.play();
}
});
// Update button state when playback ends
wavesurfer.on("finish", function () {
updatePlayButton(false);
});
}
// Update play button state
function updatePlayButton(isPlaying) {
const playBtn = document.getElementById("play-btn");
if (!playBtn) return;
if (isPlaying) {
playBtn.innerHTML = '<i class="fas fa-pause" style="margin: 0px"></i>';
playBtn.classList.remove("btn-primary");
playBtn.classList.add("btn-danger");
} else {
playBtn.innerHTML = '<i class="fas fa-play" style="margin: 0px"></i>';
playBtn.classList.remove("btn-danger");
playBtn.classList.add("btn-primary");
}
}
// Setup volume slider
function setupVolumeControl() {
const volumeSlider = document.getElementById("volume-slider");
if (volumeSlider) {
volumeSlider.addEventListener("input", function () {
wavesurfer.setVolume(this.value / 100);
});
}
}
// Setup playback speed control
function setupPlaybackSpeed() {
const playbackSpeedSelect = document.getElementById("playback-speed");
if (!playbackSpeedSelect) return;
playbackSpeedSelect.addEventListener("change", function () {
const speed = parseFloat(this.value);
wavesurfer.setPlaybackRate(speed);
showSpeedNotification(speed);
});
// Set initial value from settings if available
if (window.settingsHandler?.getSettings) {
const settings = window.settingsHandler.getSettings();
if (settings.audioSettings?.playbackRate) {
const rate = settings.audioSettings.playbackRate.toString();
playbackSpeedSelect.value = rate;
wavesurfer.setPlaybackRate(parseFloat(rate));
}
}
}
// Show speed change notification
function showSpeedNotification(speed) {
const notification = document.createElement("div");
notification.className = "alert alert-info";
notification.innerHTML = `<i class="fas fa-tachometer-alt me-2"></i> Playback speed: ${speed}x`;
notification.style.position = "fixed";
notification.style.bottom = "10px";
notification.style.right = "10px";
notification.style.zIndex = "9999";
notification.style.boxShadow = "0 2px 10px rgba(0,0,0,0.1)";
notification.style.padding = "8px 16px";
document.body.appendChild(notification);
// Remove notification after 1.5 seconds
setTimeout(() => {
notification.style.opacity = "0";
notification.style.transition = "opacity 0.5s ease-out";
setTimeout(() => {
if (notification.parentNode)
notification.parentNode.removeChild(notification);
}, 500);
}, 1500);
}
// Initialize audio cutting controls
function initAudioCuttingControls() {
const editingTools = document.getElementById("editing-tools");
if (!editingTools) {
console.error("Editing tools container not found");
return;
}
// Create cutting controls row
const cuttingControlsRow = document.createElement("div");
cuttingControlsRow.className = "row g-2 mt-2";
cuttingControlsRow.id = "cutting-controls";
cuttingControlsRow.innerHTML = `
<div class="col-md-4">
<button class="btn btn-outline-primary w-100" id="play-region" disabled>
<i class="fas fa-play-circle"></i><br>
Play Selected Region
</button>
</div>
<div class="col-md-4">
<button class="btn btn-outline-danger w-100" id="trim-audio" disabled>
<i class="fas fa-cut"></i><br>
Trim to Selection
</button>
</div>
<div class="col-md-4">
<button class="btn btn-outline-secondary w-100" id="clear-region" disabled>
<i class="fas fa-times-circle"></i><br>
Clear Selection
</button>
</div>
`;
// Add controls to the editing tools container
editingTools.appendChild(cuttingControlsRow);
// Set up button event handlers
document
.getElementById("play-region")
?.addEventListener("click", playSelectedRegion);
document
.getElementById("trim-audio")
?.addEventListener("click", trimAudioToSelection);
document
.getElementById("clear-region")
?.addEventListener("click", clearRegions);
}
// Function to enable/disable region control buttons
function updateRegionControls(hasRegion) {
const playRegionBtn = document.getElementById("play-region");
const trimAudioBtn = document.getElementById("trim-audio");
const clearRegionBtn = document.getElementById("clear-region");
if (playRegionBtn) playRegionBtn.disabled = !hasRegion;
if (trimAudioBtn) trimAudioBtn.disabled = !hasRegion;
if (clearRegionBtn) clearRegionBtn.disabled = !hasRegion;
}
// Function to play the selected region
function playSelectedRegion() {
if (!window.wavesurfer) return;
const regions = getRegionsList();
if (regions.length === 0) return;
regions[0].play();
}
// Function to trim the audio to the selected region
function trimAudioToSelection() {
if (!window.wavesurfer) return;
const regions = getRegionsList();
if (regions.length === 0) return;
const region = regions[0];
const curFileName = document.getElementById("current-file")?.textContent;
let audioBuffer = null;
try {
if (window.wavesurfer.backend?.buffer) {
audioBuffer = window.wavesurfer.backend.buffer; // v6 style
} else if (typeof window.wavesurfer.getDecodedData === "function") {
audioBuffer = window.wavesurfer.getDecodedData(); // v7 style
}
} catch {}
if (!audioBuffer || !audioBuffer.sampleRate) {
showTransientNotice(
"Trimming isn't available with the current audio engine.",
"warning"
);
return;
}
// Store the current audio for potential restoration
if (!window.originalAudio) {
window.originalAudio = {
buffer: audioBuffer,
filename: curFileName,
};
}
// Calculate new buffer parameters
const start = Math.floor(region.start * audioBuffer.sampleRate);
const end = Math.floor(region.end * audioBuffer.sampleRate);
const channels = audioBuffer.numberOfChannels;
const newDuration = region.end - region.start;
// Create a new audio buffer
const ac =
window.wavesurfer.backend?.ac ||
(typeof AudioContext !== "undefined" ? new AudioContext() : null);
if (!ac) {
showTransientNotice("Browser doesn't support audio trimming.", "warning");
return;
}
const newBuffer = ac.createBuffer(
channels,
end - start,
audioBuffer.sampleRate
);
// Copy each channel's data to the new buffer
for (let channel = 0; channel < channels; channel++) {
const sourceData = audioBuffer.getChannelData(channel);
const newData = newBuffer.getChannelData(channel);
for (let i = 0; i < end - start; i++) {
newData[i] = sourceData[start + i];
}
}
// Load the new buffer (only if supported)
if (typeof window.wavesurfer.loadDecodedBuffer === "function") {
window.wavesurfer.loadDecodedBuffer(newBuffer);
} else if (typeof window.wavesurfer.loadBlob === "function") {
// Fallback: encode to WAV and load as blob
try {
const wavBlob = audioBufferToWavBlob(newBuffer);
window.wavesurfer.loadBlob(wavBlob);
} catch (err) {
console.warn("Failed to load trimmed audio buffer:", err);
showTransientNotice("Trimming is limited in this browser.", "warning");
return;
}
} else {
showTransientNotice(
"Trimming isn't supported with the current player.",
"warning"
);
return;
}
// Show notification to user
const notification = document.createElement("div");
notification.className = "alert alert-success";
notification.innerHTML = `<i class="fas fa-check-circle"></i> Audio trimmed successfully (${newDuration.toFixed(
2
)} seconds)`;
notification.style.position = "fixed";
notification.style.top = "10px";
notification.style.right = "10px";
notification.style.zIndex = "9999";
document.body.appendChild(notification);
// Remove notification after 3 seconds
setTimeout(() => {
document.body.removeChild(notification);
}, 3000);
// Clear regions after trimming
clearRegions();
}
// Minimal WAV encoder to support loadBlob fallback
function audioBufferToWavBlob(buffer) {
const numOfChan = buffer.numberOfChannels;
const sampleRate = buffer.sampleRate;
const format = 1; // PCM
const bitDepth = 16;
let result;
if (numOfChan === 2) {
result = interleave(buffer.getChannelData(0), buffer.getChannelData(1));
} else {
result = buffer.getChannelData(0);
}
const bytesPerSample = bitDepth / 8;
const blockAlign = numOfChan * bytesPerSample;
const bufferLength = result.length * bytesPerSample;
const wavBuffer = new ArrayBuffer(44 + bufferLength);
const view = new DataView(wavBuffer);
/* RIFF identifier */ writeString(view, 0, "RIFF");
/* file length */ view.setUint32(4, 36 + bufferLength, true);
/* RIFF type */ writeString(view, 8, "WAVE");
/* format chunk identifier */ writeString(view, 12, "fmt ");
/* format chunk length */ view.setUint32(16, 16, true);
/* sample format (raw) */ view.setUint16(20, format, true);
/* channel count */ view.setUint16(22, numOfChan, true);
/* sample rate */ view.setUint32(24, sampleRate, true);
/* byte rate (sample rate * block align) */
view.setUint32(28, sampleRate * blockAlign, true);
/* block align (channel count * bytes per sample) */
view.setUint16(32, blockAlign, true);
/* bits per sample */ view.setUint16(34, bitDepth, true);
/* data chunk identifier */ writeString(view, 36, "data");
/* data chunk length */ view.setUint32(40, bufferLength, true);
floatTo16BitPCM(view, 44, result);
return new Blob([view], { type: "audio/wav" });
}
function writeString(view, offset, string) {
for (let i = 0; i < string.length; i++) {
view.setUint8(offset + i, string.charCodeAt(i));
}
}
function floatTo16BitPCM(output, offset, input) {
for (let i = 0; i < input.length; i++, offset += 2) {
const s = Math.max(-1, Math.min(1, input[i]));
output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7fff, true);
}
}
function interleave(inputL, inputR) {
const length = inputL.length + inputR.length;
const result = new Float32Array(length);
let index = 0;
let inputIndex = 0;
while (index < length) {
result[index++] = inputL[inputIndex];
result[index++] = inputR[inputIndex];
inputIndex++;
}
return result;
}
function showTransientNotice(message, type = "info") {
const notification = document.createElement("div");
const cls =
type === "danger"
? "alert-danger"
: type === "warning"
? "alert-warning"
: type === "success"
? "alert-success"
: "alert-info";
notification.className = `alert ${cls}`;
notification.textContent = message;