-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAudio2Img2audio_20205_z5_mod19-C.html
More file actions
685 lines (621 loc) · 37.4 KB
/
Audio2Img2audio_20205_z5_mod19-C.html
File metadata and controls
685 lines (621 loc) · 37.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Audio-Image Weaver (High-Fidelity & Synthesis)</title>
<style>
/* Dark Mode Base Styles */
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
margin: 0;
padding: 20px;
background-color: #1a1a1a;
color: #e0e0e0;
line-height: 1.6;
overflow-x: hidden;
}
.container {
background-color: #2a2a2a;
padding: 30px;
border-radius: 12px;
box-shadow: 0 8px 20px rgba(0,0,0,0.4);
width: 90%;
max-width: 1400px;
margin-bottom: 25px;
border: 1px solid #3a3a3a;
}
h1, h2, h3 {
color: #8bbce0;
text-align: center;
margin-bottom: 25px;
font-weight: 600;
}
h3 {
margin-top: 10px;
width: 100%;
border-bottom: 1px solid #444;
padding-bottom: 10px;
}
.section {
margin-bottom: 35px;
padding-bottom: 25px;
border-bottom: 1px dashed #3a3a3a;
}
.section:last-child {
border-bottom: none;
margin-bottom: 0;
padding-bottom: 0;
}
label {
display: block;
margin-bottom: 10px;
font-weight: bold;
color: #c0c0c0;
font-size: 1.05em;
}
label.checkbox-label {
display: flex;
align-items: center;
font-weight: normal;
cursor: pointer;
margin-bottom: 0;
}
input[type="number"], button, select {
padding: 12px 18px;
border: 1px solid #555;
border-radius: 8px;
font-size: 1em;
transition: all 0.2s ease-in-out;
box-sizing: border-box;
background-color: #383838;
color: #e0e0e0;
}
select { cursor: pointer; }
button { background-color: #007bff; color: white; cursor: pointer; }
button:hover { background-color: #0056b3; transform: translateY(-1px); }
button:active { transform: translateY(0); }
.controls {
display: flex;
flex-direction: column;
align-items: center;
gap: 15px;
margin-top: 20px;
width: 100%;
}
/* Canvas and Audio Player Styles */
canvas {
border: 2px solid #555;
background-color: #444;
display: block;
margin-top: 15px;
width: 100%;
max-width: 512px;
height: auto;
border-radius: 8px;
box-shadow: inset 0 2px 5px rgba(0,0,0,0.2);
}
audio {
width: 100%;
margin-top: 15px;
border-radius: 8px;
background-color: #383838;
filter: invert(0.8) hue-rotate(180deg);
}
/* Flex containers for sections */
.io-section-content {
display: flex;
flex-wrap: wrap;
gap: 40px;
width: 100%;
margin-top: 20px;
justify-content: space-around;
align-items: flex-start;
}
.content-column {
flex: 1;
min-width: 320px;
max-width: 600px;
display: flex;
flex-direction: column;
align-items: center;
}
/* Download Link Styles */
a.download-link {
display: inline-block;
margin-top: 15px;
padding: 10px 20px;
background-color: #28a745;
color: white;
text-decoration: none;
border-radius: 8px;
font-weight: 600;
}
a.download-link:hover { background-color: #218838; transform: translateY(-1px); }
/* Status Message Styles */
#status { margin-top: 20px; font-weight: bold; text-align: center; padding: 10px; border: 1px solid; border-radius: 8px; display: none; }
#status.active { display: block; }
#status.error { color: #ff9999; background-color: #4a2a2a; border-color: #6a3a3a; }
#status.info { color: #99ccff; background-color: #2a3a4a; border-color: #3a5a6a; }
#status.success { color: #99ff99; background-color: #2a4a2a; border-color: #3a6a3a; }
/* Note Section Styles */
#note { font-size: 0.95em; color: #a0a0a0; margin-top: 15px; padding: 15px; border: 1px solid #3a3a3a; background-color: #2a2a2a; border-radius: 8px; line-height: 1.5; }
#note strong { color: #8bbce0; }
#note code { background-color: #333; padding: 2px 5px; border-radius: 4px; font-family: 'Courier New', Courier, monospace; }
/* Drag and Drop Zone Styles */
.file-input-zone { border: 2px dashed #555; border-radius: 8px; padding: 30px 20px; text-align: center; transition: all 0.2s ease-in-out; margin-bottom: 5px; background-color: #2e2e2e; color: #c0c0c0; width: 100%; }
.file-input-zone.drag-over { border-color: #8bbce0; background-color: #3a3a3a; }
.file-input-zone p { margin: 0 0 15px 0; font-size: 1.1em; }
.file-input-zone label { padding: 12px 25px; border-radius: 8px; background-color: #007bff; color: white; display: inline-block; cursor: pointer; font-weight: 600; }
.file-input-zone label:hover { background-color: #0056b3; }
.file-input-zone input[type="file"] { display: none; }
.file-info-display { font-size: 1.1em; color: #c0c0c0; text-align: center; margin: 10px 0 25px 0; padding: 8px 15px; border-radius: 5px; background-color: #333; box-shadow: inset 0 1px 3px rgba(0,0,0,0.2); word-wrap: break-word; overflow-wrap: break-word; min-height: 2.5em; display: flex; align-items: center; justify-content: center; width: 100%; }
.file-info-display.has-file { color: #8bbce0; font-weight: bold; }
/* Controls Styles */
.control-group, #encodeDimensionControls { background-color: #333; padding: 20px; border-radius: 8px; margin-top: 20px; border: 1px solid #444; width: 100%; max-width: 512px; }
.control-group-inner { display: flex; align-items: center; justify-content: space-between; margin-bottom: 15px; }
.control-group-inner:last-child { margin-bottom: 0; }
.control-group-inner label { margin: 0 15px 0 0; flex-shrink: 0; }
.control-group-inner input[type="number"], .control-group-inner select { width: 150px; padding: 8px 12px; }
#encodeDimensionControls { display: flex; flex-direction: column; gap: 15px; }
</style>
</head>
<body>
<div class="container">
<h1>Audio-Image Weaver</h1>
<p id="note">
This tool has two modes: High-Fidelity storage and Fallback Synthesis.
<br><br>
<strong>Encode:</strong> Converts an audio file into a PNG image. By default, it uses a high-fidelity mode that prioritizes data integrity. Check <strong>"Overwrite first pixels"</strong> and provide dimensions to prioritize matching a specific image size, which may overwrite a tiny fraction of audio data.
<br><br>
<strong>Decode:</strong> Reads an image file. If it's a specially encoded audio-image, it will reconstruct the audio. If it's a <strong>normal image</strong>, it will switch to <strong>Fallback Synthesis Mode</strong>, allowing you to generate experimental audio.
</p>
<div class="section">
<h2>1. Encode Audio to Image</h2>
<div class="io-section-content">
<div class="content-column">
<h3>Input Audio</h3>
<div class="file-input-zone" id="audioDropZone"><p>Drag & drop an audio file here</p><label for="audioFile">Select Audio File</label><input type="file" id="audioFile" accept="audio/*"></div>
<div class="file-info-display" id="audioFileInfoDisplay">No audio file selected.</div>
<audio id="previewAudio" controls></audio>
<div class="controls">
<label class="checkbox-label" for="overwritePixelsCheckbox">
<input type="checkbox" id="overwritePixelsCheckbox" style="margin-right: 8px;">
Overwrite first pixels (Visual Priority)
</label>
<label class="checkbox-label" for="sizeFromFilenameCheckbox">
<input type="checkbox" id="sizeFromFilenameCheckbox" style="margin-right: 8px;">
Size from Filename (for Encoding)
</label>
<div id="encodeDimensionControls" style="display: none;">
<div class="control-group-inner">
<label for="encodeWidth">Image Width:</label>
<input type="number" id="encodeWidth" value="1024" min="1">
</div>
<div class="control-group-inner">
<label for="encodeHeight">Image Height:</label>
<input type="number" id="encodeHeight" value="1024" min="1">
</div>
</div>
<button id="encodeImageBtn">Encode to Image</button>
</div>
</div>
<div class="content-column">
<h3>Encoded Image Output</h3>
<canvas id="encodedCanvas"></canvas>
<a id="downloadImageLink" class="download-link" style="display: none;">Download Image</a>
</div>
</div>
</div>
<div class="section">
<h2>2. Decode Image to Audio</h2>
<div class="io-section-content">
<div class="content-column">
<h3>Input Image</h3>
<div class="file-input-zone" id="imageDropZone"><p>Drag & drop an image file here</p><label for="imageFile">Select Image File</label><input type="file" id="imageFile" accept="image/png, image/jpeg, image/gif"></div>
<div class="file-info-display" id="imageFileInfoDisplay">No image file selected.</div>
<canvas id="inputImagePreviewCanvas"></canvas>
</div>
<div class="content-column">
<h3>Decoded Audio Output</h3>
<div id="fallbackControls" class="control-group" style="display: none;">
<div>
<h3>Fallback Synthesis Controls</h3>
<div class="control-group-inner"><label for="fallbackSampleRate">Sample Rate (Hz):</label><input type="number" id="fallbackSampleRate" value="44100" min="8000" max="96000"></div>
<div class="control-group-inner"><label for="fallbackDuration">Duration (s):</label><input type="number" id="fallbackDuration" value="5" min="1" max="300"></div>
</div>
</div>
<div class="output-controls control-group">
<div class="control-group-inner"><label for="compressionSelect">Download Format:</label><select id="compressionSelect"><option value="16" selected>16-bit WAV (High Quality)</option><option value="8">8-bit WAV (Smaller File)</option></select></div>
</div>
<audio id="decodedAudio" controls></audio>
<a id="downloadAudioLink" class="download-link" style="display: none;">Download Audio</a>
<div id="synthesisPreviewContainer" style="display: none;">
<h3>Synthesized Audio Preview</h3>
<canvas id="synthesisPreviewCanvas"></canvas>
</div>
<div class="controls"><button id="decodeAudioBtn">Decode to Audio</button></div>
</div>
</div>
</div>
<div id="status"></div>
</div>
<script>
// --- DOM Elements ---
const audioFileIn = document.getElementById('audioFile'), previewAudioElement = document.getElementById('previewAudio'),
encodeImageBtn = document.getElementById('encodeImageBtn'), encodedCanvas = document.getElementById('encodedCanvas'),
downloadImageLink = document.getElementById('downloadImageLink'), audioFileInfoDisplay = document.getElementById('audioFileInfoDisplay'),
audioDropZone = document.getElementById('audioDropZone'), overwritePixelsCheckbox = document.getElementById('overwritePixelsCheckbox'),
sizeFromFilenameCheckbox = document.getElementById('sizeFromFilenameCheckbox'), // New checkbox
encodeDimensionControls = document.getElementById('encodeDimensionControls'), encodeWidthInput = document.getElementById('encodeWidth'),
encodeHeightInput = document.getElementById('encodeHeight');
const imageFileIn = document.getElementById('imageFile'), inputImagePreviewCanvas = document.getElementById('inputImagePreviewCanvas'),
decodeAudioBtn = document.getElementById('decodeAudioBtn'), decodedAudioElement = document.getElementById('decodedAudio'),
downloadAudioLink = document.getElementById('downloadAudioLink'), imageFileInfoDisplay = document.getElementById('imageFileInfoDisplay'),
imageDropZone = document.getElementById('imageDropZone');
const fallbackControls = document.getElementById('fallbackControls'), fallbackSampleRateInput = document.getElementById('fallbackSampleRate'),
fallbackDurationInput = document.getElementById('fallbackDuration');
const synthesisPreviewContainer = document.getElementById('synthesisPreviewContainer'),
synthesisPreviewCanvas = document.getElementById('synthesisPreviewCanvas');
const compressionSelect = document.getElementById('compressionSelect'), statusDiv = document.getElementById('status');
// --- Global State ---
let audioContext, audioBufferCache, originalAudioFileName = '', lastDecodedAudioData = null, lastDecodedSampleRate = 0;
// New global state to store parsed dimensions for fallback image preview
let fallbackImagePreviewWidth = 0;
let fallbackImagePreviewHeight = 0;
// START getAudioContext
function getAudioContext() {
if (!audioContext) audioContext = new (window.AudioContext || window.webkitAudioContext)();
if (audioContext.state === 'suspended') audioContext.resume().catch(console.error);
return audioContext;
}
// END getAudioContext
// START updateStatus
function updateStatus(message, type = 'info') {
statusDiv.textContent = message;
statusDiv.className = `active ${type}`;
}
// END updateStatus
// START updateFileInfoDisplay
function updateFileInfoDisplay(file, displayElement) {
const defaultText = displayElement.id.includes('audio') ? 'No audio file selected.' : 'No image file selected.';
displayElement.textContent = file ? `File loaded: ${file.name}` : defaultText;
displayElement.classList.toggle('has-file', !!file);
}
// END updateFileInfoDisplay
// START dataURLtoBlob
function dataURLtoBlob(dataurl) {
const arr = dataurl.split(','), mimeMatch = arr[0].match(/:(.*?);/), bstr = atob(arr.pop());
if (!mimeMatch) return null;
let n = bstr.length; const u8arr = new Uint8Array(n);
while (n--) u8arr[n] = bstr.charCodeAt(n);
return new Blob([u8arr], { type: mimeMatch[1] });
}
// END dataURLtoBlob
// START renderAudioToCanvas
/**
* Renders audio data to a canvas. Has two modes based on options.
* Default: High-fidelity mode, calculates canvas size to fit audio + metadata.
* Overwrite Mode: Forces canvas to a specific size and overwrites first two pixels with metadata.
* Custom Dimensions for Fallback Preview: Uses provided customWidth/Height if available for overwrite mode.
*/
function renderAudioToCanvas(audioData, sampleRate, targetCanvas, options = {}) {
const numSamples = audioData.length;
let width, height;
if (options.overwrite) { // This path is used for synthesisPreviewCanvas AND for encoding with overwrite
if (options.customWidth && options.customHeight) { // For synthesis preview when filename provides dimensions
width = options.customWidth;
height = options.customHeight;
} else if (options.width && options.height) { // For encoding with overwrite, or synthesis fallback to original image dims
width = options.width;
height = options.height;
} else { // Fallback for overwrite if no specific dimensions given (shouldn't happen with current logic)
const requiredPixels = numSamples + 2; // Still consider space for metadata if overwrite is general
width = Math.ceil(Math.sqrt(requiredPixels));
height = width;
}
} else { // This path is used for encodedCanvas (high-fidelity audio encoding without overwrite)
const requiredPixels = numSamples + 2;
width = Math.ceil(Math.sqrt(requiredPixels));
height = width;
}
targetCanvas.width = width;
targetCanvas.height = height;
const ctx = targetCanvas.getContext('2d');
const imageData = ctx.createImageData(width, height);
const pixels = imageData.data;
// Determine the starting offset for audio data based on whether we are in overwrite mode or high-fidelity mode.
// In high-fidelity mode, metadata takes the first 2 pixels (8 bytes).
// In overwrite mode for synthesis preview, audio data effectively starts from pixel 0,
// and metadata is written over the first two pixels (which will be part of the audio visualization).
// For encoding with overwrite, metadata is written over the first two pixels of the user-defined image.
const metadataOffset = options.overwrite ? 0 : 2;
for (let i = 0; i < numSamples; i++) {
// Map the linear audio sample index 'i' to a 2D pixel coordinate (x, y)
// based on the targetCanvas's (potentially new) width.
const x = i % width;
const y = Math.floor(i / width);
// Calculate pixel index for the new layout, respecting metadataOffset for high-fidelity encoding
// For overwrite/synthesis, metadataOffset is 0, so it's just (y*width+x)*4
const pixelIndex = (y * width + x + metadataOffset) * 4;
if (pixelIndex >= pixels.length) { // Prevent writing out of bounds
// This can happen if the provided width/height for overwrite mode is too small
// for the total number of samples.
console.warn('Audio data exceeds image pixel capacity based on provided dimensions. Truncating.');
break;
}
const uint16Sample = Math.round(audioData[i] * 32767) + 32768;
pixels[pixelIndex] = (uint16Sample >> 8) & 0xFF; // Red channel
pixels[pixelIndex + 1] = uint16Sample & 0xFF; // Green channel
// pixels[pixelIndex + 2] (Blue) remains 0 by default for synthesis preview from createImageData
// For high-fidelity encode, blue is intentionally 0 unless overwritten
pixels[pixelIndex + 3] = 255; // Alpha channel
}
// Always write metadata to the first two pixels regardless of mode
// For high-fidelity, this is dedicated space.
// For overwrite/synthesis, this overwrites the first two visual pixels.
pixels[0] = (sampleRate >> 16) & 0xFF; pixels[1] = (sampleRate >> 8) & 0xFF; pixels[2] = sampleRate & 0xFF; pixels[3] = 255;
pixels[4] = (numSamples >> 16) & 0xFF; pixels[5] = (numSamples >> 8) & 0xFF; pixels[6] = numSamples & 0xFF; pixels[7] = 255;
ctx.putImageData(imageData, 0, 0);
}
// END renderAudioToCanvas
// START encodeAudioToImage
async function encodeAudioToImage() {
if (!audioBufferCache) { updateStatus('Please load an audio file first.', 'error'); return; }
const isOverwrite = overwritePixelsCheckbox.checked;
let renderOptions = { overwrite: isOverwrite };
if (isOverwrite) {
const width = parseInt(encodeWidthInput.value, 10);
const height = parseInt(encodeHeightInput.value, 10);
if (!width || !height || width <= 0 || height <= 0) {
updateStatus('Please provide valid positive dimensions for overwrite mode.', 'error');
return;
}
renderOptions.width = width;
renderOptions.height = height;
}
updateStatus('Encoding audio to image...', 'info');
await new Promise(resolve => setTimeout(resolve, 50));
try {
// Use the appropriate rendering mode based on the checkbox
renderAudioToCanvas(audioBufferCache.getChannelData(0), audioBufferCache.sampleRate, encodedCanvas, renderOptions);
const fileName = (originalAudioFileName.split('.').slice(0, -1).join('.') || 'encoded_audio') + '.png';
downloadImageLink.href = encodedCanvas.toDataURL('image/png');
downloadImageLink.download = fileName;
downloadImageLink.style.display = 'block';
updateStatus('Encoding complete. Automatically decoding...', 'success');
const blob = dataURLtoBlob(downloadImageLink.href);
if (blob) {
const imageFile = new File([blob], fileName, { type: 'image/png' });
const dataTransfer = new DataTransfer();
dataTransfer.items.add(imageFile);
imageFileIn.files = dataTransfer.files;
await handleImageFileSelect(imageFile);
decodeAudioBtn.click();
}
} catch (e) { updateStatus(`Error during encoding: ${e.message}`, 'error'); }
}
// END encodeAudioToImage
// START decodeImageToAudio
async function decodeImageToAudio() {
if (!imageFileIn.files[0]) { updateStatus('Please select an image file to decode.', 'error'); return; }
updateStatus('Decoding...', 'info');
await new Promise(resolve => setTimeout(resolve, 50));
try {
const tempCanvas = document.createElement('canvas');
const ctx = tempCanvas.getContext('2d');
tempCanvas.width = inputImagePreviewCanvas.width;
tempCanvas.height = inputImagePreviewCanvas.height;
ctx.drawImage(inputImagePreviewCanvas, 0, 0);
const pixels = ctx.getImageData(0, 0, tempCanvas.width, tempCanvas.height).data;
const totalPixels = tempCanvas.width * tempCanvas.height;
let decodedSampleRate = (pixels[0] << 16) | (pixels[1] << 8) | pixels[2];
let decodedNumSamples = (pixels[4] << 16) | (pixels[5] << 8) | pixels[6];
let isFallback = decodedSampleRate < 8000 || decodedSampleRate > 192000 || decodedNumSamples <= 0 || decodedNumSamples > (totalPixels - 2);
fallbackControls.style.display = isFallback ? 'block' : 'none';
synthesisPreviewContainer.style.display = isFallback ? 'block' : 'none';
let audioData, finalSampleRate;
if (isFallback) {
updateStatus('Not a valid audio-image. Using Fallback Synthesis Mode.', 'info');
finalSampleRate = parseInt(fallbackSampleRateInput.value, 10);
// Number of samples for fallback synthesis is limited by total pixels available in the image
// and by the user-defined duration.
const finalNumSamples = Math.min(totalPixels, Math.round(finalSampleRate * parseFloat(fallbackDurationInput.value)));
audioData = new Float32Array(finalNumSamples);
for (let i = 0; i < finalNumSamples; i++) {
const pIdx = i * 4; // Read R and G from each pixel
audioData[i] = (((pixels[pIdx] << 8) | pixels[pIdx + 1]) - 32768) / 32767.0;
}
// Render synthesis preview using parsed dimensions for custom width/height
renderAudioToCanvas(audioData, finalSampleRate, synthesisPreviewCanvas, {
overwrite: true,
width: tempCanvas.width, // Pass original image width (as a fallback if custom not provided)
height: tempCanvas.height, // Pass original image height (as a fallback if custom not provided)
customWidth: fallbackImagePreviewWidth, // Use parsed width if available
customHeight: fallbackImagePreviewHeight // Use parsed height if available
});
} else {
updateStatus(`Valid audio-image detected. Decoding ${decodedNumSamples} samples.`, 'info');
finalSampleRate = decodedSampleRate;
audioData = new Float32Array(decodedNumSamples);
for (let i = 0; i < decodedNumSamples; i++) {
const pIdx = (i + 2) * 4; // Skip metadata pixels
audioData[i] = (((pixels[pIdx] << 8) | pixels[pIdx + 1]) - 32768) / 32767.0;
}
}
lastDecodedAudioData = audioData;
lastDecodedSampleRate = finalSampleRate;
updateDecodedAudioOutput();
updateStatus(`Successfully processed ${audioData.length} samples at ${finalSampleRate} Hz.`, 'success');
} catch (e) { updateStatus(`Error during decoding: ${e.message}`, 'error'); }
}
// END decodeImageToAudio
// START updateDecodedAudioOutput
function updateDecodedAudioOutput() {
if (!lastDecodedAudioData) return;
const bitDepth = parseInt(compressionSelect.value, 10);
const audioBlob = createWavFile(lastDecodedAudioData, lastDecodedSampleRate, bitDepth);
if (decodedAudioElement.src) URL.revokeObjectURL(decodedAudioElement.src);
decodedAudioElement.src = URL.createObjectURL(audioBlob);
// Get dimensions from the *input image* preview canvas, which holds the original image's dimensions.
let imgWidth = inputImagePreviewCanvas.width;
const imgHeight = inputImagePreviewCanvas.height;
// Apply 9% increase to width for the audio filename
imgWidth = Math.round(imgWidth * 1.09);
const dimensionsTag = `[[${imgWidth}x${imgHeight}]]`;
let originalFileNameWithoutExt = (imageFileIn.files[0].name.split('.').slice(0, -1).join('.') || 'decoded_audio');
// Remove existing [[WxH]] tag if present before adding the new one
originalFileNameWithoutExt = originalFileNameWithoutExt.trim().replace(/\[\[\d+x\d+\]\]/g, '');
const fileName = `${originalFileNameWithoutExt}${dimensionsTag}_${bitDepth}bit.wav`;
downloadAudioLink.href = decodedAudioElement.src;
downloadAudioLink.download = fileName;
downloadAudioLink.style.display = 'block';
}
// END updateDecodedAudioOutput
// START createWavFile
function createWavFile(audioData, sampleRate, bitDepth = 16) {
const bytesPerSample = bitDepth / 8;
const buffer = new ArrayBuffer(44 + audioData.length * bytesPerSample);
const view = new DataView(buffer);
writeString(view, 0, 'RIFF'); view.setUint32(4, 36 + audioData.length * bytesPerSample, true);
writeString(view, 8, 'WAVE'); writeString(view, 12, 'fmt ');
view.setUint32(16, 16, true); view.setUint16(20, 1, true); view.setUint16(22, 1, true);
view.setUint32(24, sampleRate, true);
view.setUint32(28, sampleRate * bytesPerSample, true);
view.setUint16(32, bytesPerSample, true);
view.setUint16(34, bitDepth, true);
writeString(view, 36, 'data');
view.setUint32(40, audioData.length * bytesPerSample, true);
let offset = 44;
for (let i = 0; i < audioData.length; i++) {
const sample = Math.max(-1, Math.min(1, audioData[i]));
if (bitDepth === 16) { view.setInt16(offset, sample * 0x7FFF, true); offset += 2; }
else { view.setUint8(offset, sample * 127 + 128); offset += 1; }
}
return new Blob([view], { type: 'audio/wav' });
}
// END createWavFile
// START writeString
function writeString(view, offset, string) { for (let i = 0; i < string.length; i++) view.setUint8(offset + i, string.charCodeAt(i)); }
// END writeString
// START handleAudioFileSelect
async function handleAudioFileSelect(file) {
if (!file) return;
updateFileInfoDisplay(file, audioFileInfoDisplay);
updateStatus('Loading audio...', 'info'); getAudioContext();
previewAudioElement.src = URL.createObjectURL(file); originalAudioFileName = file.name;
try {
audioBufferCache = await audioContext.decodeAudioData(await file.arrayBuffer());
updateStatus(`Audio loaded: ${originalAudioFileName}. Ready to encode.`, 'success');
downloadImageLink.style.display = 'none';
encodedCanvas.getContext('2d').clearRect(0,0,encodedCanvas.width, encodedCanvas.height);
// If "Size from Filename" is checked, try to get dimensions from the WAV filename
if (sizeFromFilenameCheckbox.checked) {
const dimMatch = originalAudioFileName.match(/\[\[(\d+)x(\d+)\]\]/);
if (dimMatch) {
const parsedWidth = parseInt(dimMatch[1], 10);
const parsedHeight = parseInt(dimMatch[2], 10);
if (parsedWidth > 0 && parsedHeight > 0) {
encodeWidthInput.value = parsedWidth;
encodeHeightInput.value = parsedHeight;
// Ensure overwritePixelsCheckbox is checked and controls are visible
overwritePixelsCheckbox.checked = true;
encodeDimensionControls.style.display = 'flex';
updateStatus(`Loaded dimensions from audio filename: ${parsedWidth}x${parsedHeight}.`, 'info');
} else {
updateStatus('Invalid dimensions found in audio filename. Using default encoding dimensions.', 'info');
}
} else {
updateStatus('No dimensions found in audio filename. Using default encoding dimensions.', 'info');
}
}
} catch (e) { updateStatus(`Error loading audio: ${e.message}.`, 'error'); }
}
// END handleAudioFileSelect
// START handleImageFileSelect
async function handleImageFileSelect(file) {
if (!file) return;
updateFileInfoDisplay(file, imageFileInfoDisplay);
updateStatus('Image loaded. Ready to decode.', 'success');
decodedAudioElement.src = ''; decodedAudioElement.pause();
downloadAudioLink.style.display = 'none';
lastDecodedAudioData = null;
fallbackControls.style.display = 'none';
synthesisPreviewContainer.style.display = 'none';
// Reset fallback preview dimensions
fallbackImagePreviewWidth = 0;
fallbackImagePreviewHeight = 0;
// Parse filename for custom preview dimensions
const dimMatch = file.name.match(/\[\[(\d+)x(\d+)\]\]/);
if (dimMatch) {
fallbackImagePreviewWidth = parseInt(dimMatch[1], 10);
fallbackImagePreviewHeight = parseInt(dimMatch[2], 10);
if (fallbackImagePreviewWidth <= 0 || fallbackImagePreviewHeight <= 0) {
updateStatus('Invalid dimensions found in filename. Using default.', 'info');
fallbackImagePreviewWidth = 0; // Reset to default if invalid
fallbackImagePreviewHeight = 0; // Reset to default if invalid
} else {
updateStatus(`Using custom preview dimensions from filename: ${fallbackImagePreviewWidth}x${fallbackImagePreviewHeight}`, 'info');
}
}
await new Promise((resolve, reject) => {
const img = new Image();
img.src = URL.createObjectURL(file);
img.onload = () => {
const ctx = inputImagePreviewCanvas.getContext('2d');
inputImagePreviewCanvas.width = img.width;
inputImagePreviewCanvas.height = img.height;
ctx.drawImage(img, 0, 0);
URL.revokeObjectURL(img.src);
resolve();
};
img.onerror = reject;
}).catch(() => updateStatus('Error loading image preview.', 'error'));
}
// END handleImageFileSelect
// --- Event Listeners ---
encodeImageBtn.addEventListener('click', encodeAudioToImage);
decodeAudioBtn.addEventListener('click', decodeImageToAudio);
audioFileIn.addEventListener('change', (e) => handleAudioFileSelect(e.target.files[0]));
imageFileIn.addEventListener('change', (e) => handleImageFileSelect(e.target.files[0]));
fallbackSampleRateInput.addEventListener('change', decodeImageToAudio);
fallbackDurationInput.addEventListener('change', decodeImageToAudio);
compressionSelect.addEventListener('change', updateDecodedAudioOutput);
overwritePixelsCheckbox.addEventListener('change', () => {
encodeDimensionControls.style.display = overwritePixelsCheckbox.checked ? 'flex' : 'none';
if (!overwritePixelsCheckbox.checked) {
sizeFromFilenameCheckbox.checked = false; // Uncheck "Size from Filename" if "Overwrite first pixels" is unchecked
}
});
sizeFromFilenameCheckbox.addEventListener('change', () => {
if (sizeFromFilenameCheckbox.checked) {
overwritePixelsCheckbox.checked = true; // Automatically check "Overwrite first pixels"
encodeDimensionControls.style.display = 'flex'; // Show controls
// If an audio file is already loaded, try to parse its filename
if (audioFileIn.files[0]) {
handleAudioFileSelect(audioFileIn.files[0]); // Re-run to populate dimensions
}
}
// If it's unchecked, no automatic action on overwritePixelsCheckbox or controls visibility
// as overwritePixelsCheckbox controls that.
});
// START setupDragAndDrop
function setupDragAndDrop(dropZone, fileInput, fileHandler) {
dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.classList.add('drag-over'); });
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('drag-over'));
dropZone.addEventListener('drop', (e) => {
e.preventDefault(); dropZone.classList.remove('drag-over');
if (e.dataTransfer.files.length) { fileInput.files = e.dataTransfer.files; fileHandler(e.dataTransfer.files[0]); }
});
}
// END setupDragAndDrop
setupDragAndDrop(audioDropZone, audioFileIn, handleAudioFileSelect);
setupDragAndDrop(imageDropZone, imageFileIn, handleImageFileSelect);
document.body.addEventListener('click', getAudioContext, { once: true });
document.body.addEventListener('dragover', getAudioContext, { once: true });
</script>
</body>
</html>