-
Notifications
You must be signed in to change notification settings - Fork 96
Expand file tree
/
Copy pathv2.html
More file actions
617 lines (554 loc) · 26.5 KB
/
Copy pathv2.html
File metadata and controls
617 lines (554 loc) · 26.5 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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Wario Synth v2 Beta — Authentic Game Boy Sound Chip Emulator</title>
<meta name="description" content="Turn any song into an authentic Game Boy chiptune in your browser. Experimental v2 engine: real 15-bit LFSR noise, duty-cycle pulse channels, custom wavetables." />
<meta name="keywords" content="game boy sound chip emulator, sharp lr35902, chiptune converter, 8-bit music generator, midi to game boy" />
<link rel="canonical" href="https://www.wario.style/v2" />
<link rel="icon" type="image/png" href="/wario-sprite.png" />
<link rel="apple-touch-icon" href="/wario-sprite.png" />
<meta name="theme-color" content="#0b0b0b" />
<meta property="og:title" content="Wario Synth v2 Beta — Authentic Game Boy Sound Chip Emulator" />
<meta property="og:description" content="Turn any song into an authentic Game Boy chiptune in your browser. Real 15-bit LFSR noise, duty-cycle pulse channels, custom wavetables." />
<meta property="og:image" content="https://www.wario.style/warioX.png" />
<meta property="og:image:width" content="1472" />
<meta property="og:image:height" content="704" />
<meta property="og:type" content="website" />
<meta property="og:site_name" content="Wario Synth" />
<meta property="og:url" content="https://www.wario.style/v2" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="Wario Synth v2 Beta — Authentic Game Boy Sound Chip Emulator" />
<meta name="twitter:description" content="Turn any song into an authentic Game Boy chiptune in your browser. Real 15-bit LFSR noise, duty-cycle pulse channels, custom wavetables." />
<meta name="twitter:image" content="https://www.wario.style/warioX.png" />
<link rel="stylesheet" href="/src/styles/wario.css" />
</head>
<body>
<div class="container">
<div class="hero">
<div class="hero-top">
<h1>WARIO SYNTH <span class="version-tag">v2 beta</span></h1>
<button id="faqBtnTop" class="faq-link" type="button">FAQ</button>
</div>
<div class="engine-tabs">
<a id="v1Tab" href="/" class="engine-tab">v1</a>
<a href="/v2.html" class="engine-tab active">v2 beta</a>
</div>
</div>
<div class="v2-disclaimer">
<p><strong>Heads up:</strong> v1 is honestly closer to a SNES sound card. v2 is our go at the real Game Boy chip, the Sharp LR35902: a true 15-bit LFSR noise channel, pulse channels with proper duty cycles, and custom wavetables.</p>
<p>It's experimental right now. The noise channels have some low-mid distortion, so take it as a fun work in progress.</p>
</div>
<div class="controls">
<input type="text" id="songInput" placeholder="Search for a song…" />
<button id="searchBtn" class="primary">Search</button>
</div>
<div id="status">Ready. Search any song to hear it on the Game Boy chip.</div>
<div id="resultsSection" class="results-section">
<div class="results-header">
<h3>Search Results</h3>
</div>
<table class="results-table">
<thead>
<tr>
<th>Song</th>
<th class="source-col">Source</th>
<th class="action-col">Action</th>
</tr>
</thead>
<tbody id="resultsBody"></tbody>
</table>
</div>
<div id="playerSection" class="player-section">
<div class="selected-card">
<h2 id="selectedTitle" class="selected-title">No source selected</h2>
<div id="selectedMeta" class="selected-meta">Search for a song, then choose a source.</div>
<div class="selected-actions">
<button id="btn-play" class="primary" disabled>Play</button>
<button id="btn-stop" type="button" disabled>Stop</button>
</div>
<div class="motif-progress-container" id="progress-row" style="display:none;">
<div class="progress-time">
<span id="play-current">0:00</span>
<span id="play-total">0:00</span>
</div>
<div class="progress-bar-wrapper">
<input type="range" id="play-seek" class="progress-bar" min="0" max="100" value="0" step="0.1" />
<div class="progress-fill" id="play-progress-fill" style="width:0%;"></div>
</div>
</div>
<div id="iosAudioBanner" class="ios-audio-banner" aria-live="polite" style="display:none;">
<div class="row">
<div class="copy"><strong>iPhone:</strong> not on silent, volume up, Focus off. Then tap:</div>
<button id="enableAudioBtn" type="button">Enable Audio</button>
</div>
<div id="iosAudioState" class="state"></div>
</div>
<div id="shareRow" class="selected-actions" style="display:none; margin-top:14px;">
<button id="saveAudioBtn" type="button">Save Audio</button>
<button id="copyLinkBtn" type="button">Copy link</button>
<button id="shareToXBtn" type="button">Share to X</button>
</div>
<div id="shareFallback" style="display:none; margin-top:12px;">
<p style="font-size:8px; margin:0 0 8px 0; color:var(--gb-medium);">Copy didn't work on your device. Here's the link:</p>
<input id="shareFallbackInput" type="text" readonly style="width:100%; padding:8px; font-size:8px; font-family:'Press Start 2P', monospace; background:var(--gb-darkest); color:var(--gb-lightest); border:2px solid var(--gb-light);" />
</div>
</div>
</div>
</div>
<div id="faqModalBackdrop" class="modal-backdrop" role="dialog" aria-modal="true" aria-labelledby="faqTitle">
<div class="modal" role="document">
<header>
<h3 id="faqTitle">FAQ</h3>
<div class="spacer"></div>
<button id="faqCloseBtn" type="button">Close</button>
</header>
<main>
<div class="faq-grid">
<div class="faq-item">
<h4>How it works</h4>
<p>Search a song or upload your own MIDI, pick a source, hit Generate. The Wario Synthesis Engine analyses the MIDI and resynthesises it with Web Audio oscillators into a chunky 8-bit chiptune. (Honestly it's closer to a SNES than a Game Boy — the <strong>v2 beta</strong> tab goes for the real Game Boy chip.) All processing runs in your browser.</p>
</div>
<div class="faq-item">
<h4>What's the "v2 beta" tab?</h4>
<p>An experimental engine that goes for the actual Game Boy sound chip (the Sharp LR35902): real pulse, wave and noise channels. It's a rough work in progress, so v1 stays the default — but try it from the <strong>v2 beta</strong> tab up top.</p>
</div>
<div class="faq-item">
<h4>Can I upload my own MIDI?</h4>
<p>Yes. Use <strong>Upload MIDI</strong> next to Search and pick a <code>.mid</code> or <code>.midi</code> file from your device. It is parsed locally in your browser — nothing is uploaded to our servers.</p>
</div>
<div class="faq-item">
<h4>Can I save the generated version?</h4>
<p>After Generate finishes, use <strong>Save Audio</strong> (WAV) or <strong>Save MIDI</strong> to download the Game Boy-style result.</p>
</div>
<div class="faq-item">
<h4>Can I share my result?</h4>
<p>Yes — if you used <strong>Search</strong> and picked an online MIDI source, <strong>Copy link</strong> and <strong>Share to X</strong> appear after Generate. They create a link others can open at wario.style/play.</p>
</div>
<div class="faq-item">
<h4>Why can't I share an uploaded MIDI?</h4>
<p>Share links need a fetchable online MIDI URL. Files you upload stay on your device only, so Copy link and Share to X are hidden for those — you can still play, generate, and export them.</p>
</div>
<div class="faq-item">
<h4>Why "Enable Audio" on iPhone?</h4>
<p>Apple blocks sound until you tap something. Hit the button once and you're good. Still silent? Check your ringer switch.</p>
</div>
<div class="faq-item">
<h4>About</h4>
<p>A non-commercial project by <a href="https://x.com/b1rdmania" target="_blank" rel="noopener noreferrer">@b1rdmania</a> for lols. Please don't sue me. Built with Claude Code.</p>
<p style="margin-top: 8px;"><a href="https://github.com/b1rdmania/motif" target="_blank" rel="noopener noreferrer">GitHub repo</a></p>
</div>
<div class="faq-item">
<h4>Ps. I love Claude Code.</h4>
<img src="/wario.png" alt="Wario moment" style="margin-top: 8px; max-width: 100%; opacity: 0.85;" />
</div>
</div>
</main>
</div>
</div>
<div class="footer-mascot">
<img src="/wario-sprite.png" alt="Wario" class="wario-sprite" />
</div>
<div class="footer" style="margin-top:18px; font-size:8px; color:var(--gb-medium); text-align:center; gap:10px;">
<a href="https://github.com/b1rdmania/motif" target="_blank" rel="noopener noreferrer" style="color:var(--gb-dark);">GitHub</a>
<span style="opacity:0.75;">·</span>
<span>Built by <a href="https://github.com/b1rdmania" target="_blank" rel="noopener noreferrer" style="color:var(--gb-dark);">b1rdmania</a> (<a href="https://x.com/b1rdmania" target="_blank" rel="noopener noreferrer" style="color:var(--gb-dark);">X</a>)</span>
</div>
<script type="module">
import { GameBoyPlayer } from './src-v2/core/GameBoyPlayer.ts';
import { MIDIService } from './src/services/MIDIService.ts';
import { audioBufferToWavBytes } from './src/utils/export.ts';
const player = new GameBoyPlayer();
const midiService = new MIDIService();
let currentMIDI = null;
let searchResults = [];
let progressInterval = null;
const songInput = document.getElementById('songInput');
const searchBtn = document.getElementById('searchBtn');
const resultsBody = document.getElementById('resultsBody');
const resultsSection = document.getElementById('resultsSection');
const playerSection = document.getElementById('playerSection');
const statusEl = document.getElementById('status');
const selectedTitle = document.getElementById('selectedTitle');
const selectedMeta = document.getElementById('selectedMeta');
const btnPlay = document.getElementById('btn-play');
const btnStop = document.getElementById('btn-stop');
const v1Tab = document.getElementById('v1Tab');
// FAQ modal — same markup/behaviour as v1.
const faqBtnTop = document.getElementById('faqBtnTop');
const faqBackdrop = document.getElementById('faqModalBackdrop');
const faqCloseBtn = document.getElementById('faqCloseBtn');
const openFaq = () => { faqBackdrop.classList.add('open'); faqCloseBtn.focus(); };
const closeFaq = () => { faqBackdrop.classList.remove('open'); };
faqBtnTop?.addEventListener('click', openFaq);
faqCloseBtn?.addEventListener('click', closeFaq);
faqBackdrop?.addEventListener('click', (e) => { if (e.target === faqBackdrop) closeFaq(); });
document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeFaq(); });
const progressRow = document.getElementById('progress-row');
const progressFill = document.getElementById('play-progress-fill');
const seekBar = document.getElementById('play-seek');
const playCurrentEl = document.getElementById('play-current');
const playTotalEl = document.getElementById('play-total');
let songDuration = 0; // seconds, set when a song is loaded
let resumeOffset = 0; // where Play resumes / where a seek landed
let uiPlaying = false; // actively playing (vs paused/stopped)
let hasLoaded = false; // has playMIDI run for the current song
const iosBanner = document.getElementById('iosAudioBanner');
const enableAudioBtn = document.getElementById('enableAudioBtn');
const iosState = document.getElementById('iosAudioState');
const shareRow = document.getElementById('shareRow');
const saveAudioBtn = document.getElementById('saveAudioBtn');
const copyLinkBtn = document.getElementById('copyLinkBtn');
const shareToXBtn = document.getElementById('shareToXBtn');
const shareFallback = document.getElementById('shareFallback');
const shareFallbackInput = document.getElementById('shareFallbackInput');
let shareId = null; // BitMidi id of the loaded song
let shareTitle = ''; // raw title of the loaded song
function setStatus(msg) { statusEl.textContent = msg; }
function formatTime(seconds) {
const mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds % 60);
return `${mins}:${secs.toString().padStart(2, '0')}`;
}
function titleCase(input) {
return (input || '').split(/\s+/).filter(Boolean)
.map(w => /^[A-Z0-9]+$/.test(w) ? w : w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
.join(' ');
}
function cleanTitle(raw) {
const cleaned = (raw || '').replace(/\.mid$/i, '').replace(/[_.]+/g, ' ')
.replace(/\b(midi?)\b/gi, '').replace(/\s+/g, ' ').trim();
return titleCase(cleaned || 'Unknown');
}
function formatSource(s) {
const v = String(s || '').toLowerCase();
return v === 'bitmidi' ? 'BitMidi' : titleCase(v);
}
function isIOSLike() {
const ua = navigator.userAgent || '';
return /iPad|iPhone|iPod/.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1);
}
function audioRunning() {
try { return player.getAPU().getAudioContext().state === 'running'; } catch { return false; }
}
function updateIOSBanner() {
iosBanner.style.display = (isIOSLike() && !audioRunning()) ? 'block' : 'none';
}
// --- playback controls (mirrors v1: Play/Pause toggle + seekable bar) ---
function paintPlayButton() {
btnPlay.textContent = uiPlaying ? 'Pause' : 'Play';
}
function updateProgressUI(posSec) {
const pct = songDuration > 0 ? Math.max(0, Math.min(100, (posSec / songDuration) * 100)) : 0;
progressFill.style.width = `${pct}%`;
seekBar.value = String(pct);
playCurrentEl.textContent = formatTime(posSec);
playTotalEl.textContent = formatTime(songDuration);
}
function startTicker() {
if (progressInterval) clearInterval(progressInterval);
progressInterval = setInterval(() => {
const pos = player.getElapsedTime();
if (songDuration > 0 && pos >= songDuration) { onPlaybackEnded(); return; }
if (!player.getIsPlaying() && uiPlaying) { onPlaybackEnded(); return; }
updateProgressUI(pos);
}, 150);
}
function stopTicker() {
if (progressInterval) { clearInterval(progressInterval); progressInterval = null; }
}
function onPlaybackEnded() {
stopTicker();
uiPlaying = false;
resumeOffset = 0;
player.stop();
paintPlayButton();
btnStop.disabled = true;
updateProgressUI(songDuration);
setStatus('');
}
async function play() {
await player.resume();
updateIOSBanner();
if (resumeOffset > 0 && hasLoaded) {
player.playFrom(resumeOffset);
} else {
const info = await player.playMIDI(currentMIDI);
hasLoaded = true;
songDuration = info.duration;
}
uiPlaying = true;
paintPlayButton();
btnStop.disabled = false;
progressRow.style.display = 'block';
startTicker();
setStatus('Playing…');
}
function pause() {
const pos = Math.max(0, Math.min(songDuration, player.getElapsedTime()));
resumeOffset = pos;
player.stop();
uiPlaying = false;
stopTicker();
paintPlayButton();
updateProgressUI(pos);
setStatus('Paused.');
}
// Reset playback state for a freshly loaded song.
function resetPlayback() {
stopTicker();
player.stop();
uiPlaying = false;
hasLoaded = false;
resumeOffset = 0;
songDuration = 0;
btnStop.disabled = true;
paintPlayButton();
progressRow.style.display = 'none';
progressFill.style.width = '0%';
seekBar.value = '0';
playCurrentEl.textContent = '0:00';
playTotalEl.textContent = '0:00';
shareRow.style.display = 'none';
shareFallback.style.display = 'none';
shareId = null;
shareTitle = '';
}
// --- search ---
async function handleSearch() {
const query = songInput.value.trim();
if (!query) { setStatus('Enter a song name to search.'); return; }
setStatus('Searching…');
searchBtn.disabled = true;
resultsBody.innerHTML = '';
try {
const results = await midiService.search(query);
searchResults = results;
if (!results.length) { setStatus('No MIDI files found. Try a different search.'); return; }
displayResults();
resultsSection.classList.add('visible');
setStatus('Pick a source. Try another if it sounds rough, some MIDIs map better than others.');
updateIOSBanner();
} catch (e) {
setStatus(`Search error: ${e && e.message ? e.message : 'unknown'}`);
} finally {
searchBtn.disabled = false;
}
}
function displayResults() {
resultsBody.innerHTML = '';
searchResults.forEach((result, index) => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${cleanTitle(result.title)}</td>
<td class="source-col">${formatSource(result.source)}</td>
<td class="action-col">
<div style="display:flex; gap:10px; justify-content:flex-end; align-items:center;">
<button type="button" class="row-use-btn">Use</button>
</div>
</td>`;
row.querySelector('button.row-use-btn').addEventListener('click', (e) => {
e.stopPropagation();
void selectResult(index);
});
resultsBody.appendChild(row);
});
}
async function selectResult(index) {
if (index < 0 || index >= searchResults.length) return;
const result = searchResults[index];
const rows = resultsBody.querySelectorAll('tr');
rows.forEach((r, i) => r.classList.toggle('selected', i === index));
resetPlayback();
setStatus('Loading…');
btnPlay.disabled = true;
try {
const buffer = await midiService.fetchMIDI(result.midiUrl);
if (!buffer) throw new Error('Failed to fetch MIDI');
currentMIDI = buffer;
const info = player.analyzeMIDI(buffer);
songDuration = info.duration;
const m = String(result.midiUrl || '').match(/\/uploads\/(\d+)\.mid/i);
shareId = m && m[1] ? m[1] : null;
shareTitle = result.title || '';
selectedTitle.textContent = cleanTitle(result.title);
selectedMeta.textContent = `Source: ${formatSource(result.source)} · ${info.noteCount} notes · ${formatTime(info.duration)}`;
if (v1Tab) v1Tab.href = `/?song=${encodeURIComponent(result.title || '')}`;
playerSection.classList.add('visible');
resultsSection.classList.add('collapsed');
progressRow.style.display = 'block';
updateProgressUI(0);
if (shareId) shareRow.style.display = 'flex';
btnPlay.disabled = false;
setStatus('');
updateIOSBanner();
try { playerSection.scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch {}
} catch (e) {
setStatus(`Load error: ${e && e.message ? e.message : 'unknown'}`);
}
}
// --- playback ---
btnPlay.addEventListener('click', async () => {
if (!currentMIDI) return;
try {
if (uiPlaying) { pause(); } else { await play(); }
} catch (e) {
setStatus(`Playback error: ${e && e.message ? e.message : 'unknown'}`);
}
});
btnStop.addEventListener('click', () => {
stopTicker();
player.stop();
uiPlaying = false;
resumeOffset = 0;
btnStop.disabled = true;
paintPlayButton();
updateProgressUI(0);
setStatus('');
});
// Seek: drag the bar to jump. While playing, relaunch from the new spot.
function handleSeek() {
if (songDuration <= 0) return;
const target = (parseFloat(seekBar.value) / 100) * songDuration;
resumeOffset = target;
updateProgressUI(target);
if (uiPlaying) {
player.playFrom(target);
startTicker();
}
}
seekBar.addEventListener('input', handleSeek);
seekBar.addEventListener('change', handleSeek);
// --- share (mirrors v1: copy a deep link + tweet it) ---
function buildShareUrl() {
const base = `${window.location.origin}/v2.html`;
if (!shareId) return base;
return `${base}?id=${encodeURIComponent(shareId)}&title=${encodeURIComponent(shareTitle || '')}`;
}
async function handleCopyLink() {
const url = buildShareUrl();
let copied = false;
try {
if (navigator.clipboard?.writeText) { await navigator.clipboard.writeText(url); copied = true; }
} catch {}
if (!copied) {
try {
const ta = document.createElement('textarea');
ta.value = url; ta.style.position = 'fixed'; ta.style.left = '-9999px'; ta.setAttribute('readonly', '');
document.body.appendChild(ta); ta.focus(); ta.select();
try { ta.setSelectionRange(0, url.length); } catch {}
copied = document.execCommand('copy'); document.body.removeChild(ta);
} catch {}
}
if (copied) {
const orig = copyLinkBtn.textContent;
copyLinkBtn.textContent = 'Copied!';
shareFallback.style.display = 'none';
setTimeout(() => { copyLinkBtn.textContent = orig; }, 1500);
} else {
shareFallbackInput.value = url;
shareFallback.style.display = 'block';
shareFallbackInput.focus();
shareFallbackInput.select();
}
}
function handleShareToX() {
const url = buildShareUrl();
const title = cleanTitle(shareTitle || 'a song');
const text = `I made a Game Boy version of ${title}\n\nUsing @b1rdmania's Wario Synth (v2 engine)\n\nCheck it out`;
window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(text)}&url=${encodeURIComponent(url)}`, '_blank');
}
copyLinkBtn.addEventListener('click', () => void handleCopyLink());
shareToXBtn.addEventListener('click', handleShareToX);
// --- save audio (WAV) — offline-render the GB engine ---
function sanitizeFileBase(name) {
const clean = cleanTitle(name).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
return clean || 'wario-synth';
}
function downloadBytes(bytes, fileName, mime) {
const raw = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
const blob = new Blob([raw], { type: mime });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.download = fileName;
document.body.appendChild(a); a.click(); document.body.removeChild(a);
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
saveAudioBtn.addEventListener('click', async () => {
if (!currentMIDI) return;
const orig = saveAudioBtn.textContent;
saveAudioBtn.disabled = true;
saveAudioBtn.textContent = 'Rendering…';
setStatus('Rendering audio…');
try {
// Make sure the engine has arranged the current song (no sound).
if (!hasLoaded) { player.prepareMIDI(currentMIDI); hasLoaded = true; }
const buffer = await player.renderToBuffer();
if (!buffer) throw new Error('Nothing to render');
const bytes = audioBufferToWavBytes(buffer);
downloadBytes(bytes, `${sanitizeFileBase(shareTitle)}-gameboy.wav`, 'audio/wav');
setStatus('Saved a 30s clip (.wav).');
} catch (e) {
setStatus(`Export error: ${e && e.message ? e.message : 'unknown'}`);
} finally {
saveAudioBtn.disabled = false;
saveAudioBtn.textContent = orig;
}
});
enableAudioBtn.addEventListener('click', async () => {
iosState.textContent = 'Audio: enabling…';
try { await player.resume(); } catch {}
iosState.textContent = audioRunning() ? 'Audio: running' : 'Still locked. Tap again.';
updateIOSBanner();
});
searchBtn.addEventListener('click', handleSearch);
songInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') handleSearch(); });
// --- deep links: ?id=<bitmidi>&title=... or ?q=<search> ---
async function loadFromBitMidiId(id, title) {
resetPlayback();
setStatus(`Loading ${title || id}…`);
try {
const buffer = await midiService.fetchMIDI(`https://bitmidi.com/uploads/${id}.mid`);
if (!buffer) throw new Error('Failed to fetch MIDI');
currentMIDI = buffer;
const info = player.analyzeMIDI(buffer);
songDuration = info.duration;
shareId = id;
shareTitle = title || '';
selectedTitle.textContent = cleanTitle(title || `BitMidi ${id}`);
selectedMeta.textContent = `Source: BitMidi · ${info.noteCount} notes · ${formatTime(info.duration)}`;
if (v1Tab) v1Tab.href = `/?song=${encodeURIComponent(title || '')}`;
playerSection.classList.add('visible');
progressRow.style.display = 'block';
updateProgressUI(0);
shareRow.style.display = 'flex';
btnPlay.disabled = false;
setStatus('Loaded. Press Play.');
updateIOSBanner();
try { playerSection.scrollIntoView({ behavior: 'smooth', block: 'start' }); } catch {}
return true;
} catch (e) {
setStatus(`Link load error: ${e && e.message ? e.message : 'unknown'}`);
return false;
}
}
async function initFromUrl() {
const params = new URLSearchParams(window.location.search);
const id = params.get('id');
const q = params.get('q');
const title = params.get('title') || '';
if (id && /^\d+$/.test(id)) {
if (title) songInput.value = title;
await loadFromBitMidiId(id, title);
} else if (q) {
songInput.value = q;
await handleSearch();
if (searchResults.length > 0) await selectResult(0);
}
}
updateIOSBanner();
initFromUrl();
</script>
</body>
</html>