Got it. You want a HTML/CSS/JS chiptune tracker/sequencer with features:
html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Chiptune Tracker</title>
<style>
body {
font-family: monospace, monospace;
background: #181818;
color: #f0f0f0;
display: flex;
flex-direction: column;
margin: 0; padding: 0;
height: 100vh;
}
header {
background: #333;
padding: 0.3em 1em;
display: flex; align-items: center; justify-content: space-between;
}
main {
flex-grow: 1;
display: grid;
grid-template-columns: 300px auto 300px;
gap: 8px;
padding: 0.5em;
}
.section {
background: #222;
border: 1px solid #444;
padding: 0.5em;
overflow: hidden;
display: flex;
flex-direction: column;
}
.section h2 {
margin-top: 0;
font-weight: normal;
font-size: 1.2em;
padding-bottom: 0.5em;
border-bottom: 1px solid #444;
}
button {
background: #444;
border: none;
color: #eee;
padding: 0.3em 0.7em;
margin: 0.15em;
cursor: pointer;
}
button:hover {
background: #666;
}
select, input[type=number], input[type=text], input[type=range] {
background: #111;
border: 1px solid #444;
color: #eee;
padding: 0.2em 0.4em;
font-family: monospace;
font-size: 1em;
}
label {
display: block;
margin-top: 0.5em;
}
#patternGrid {
flex: 1;
overflow: auto;
background: #101010;
font-size: 0.9em;
border: 1px solid #555;
}
table {
border-collapse: collapse;
width: max-content;
}
td {
border: 1px solid #333;
width: 3em;
height: 1.6em;
text-align: center;
user-select: none;
}
td.selected {
background: #3a7;
color: #000;
font-weight: bold;
}
td.note {
cursor: pointer;
}
td.note:hover {
background: #575;
}
.controls {
display: flex;
gap: 0.7em;
flex-wrap: wrap;
margin-top: 0.3em;
}
#playStatus {
font-weight: bold;
color: #6f6;
}
.instrParam {
margin-top: 0.2em;
}
.footer {
background: #222;
padding: 0.3em 1em;
font-size: 0.9em;
text-align: center;
color: #777;
}
</style>
</head>
<body>
<header>
<div>
BPM: <input type="number" min="30" max="300" step="1" value="120" id="bpmInput" style="width: 4em" />
Patterns: <input type="number" min="1" max="32" step="1" value="4" id="patternsCount" style="width: 3em" />
Rows/Pattern: <input type="number" min="1" max="64" step="1" value="16" id="rowsPerPattern" style="width: 3em" />
Instruments: <input type="number" min="1" max="8" step="1" value="3" id="instrumentsCount" style="width: 3em" />
<button id="resetSongBtn" title="Reset song data">Reset</button>
</div>
<div class="controls">
<button id="playBtn">▶ Play</button>
<button id="stopBtn" disabled>■ Stop</button>
Loop: <input type="checkbox" id="loopToggle" checked />
<button id="copyPatternBtn" title="Copy selected pattern">Copy</button>
<button id="pastePatternBtn" title="Paste to selected pattern">Paste</button>
<button id="dupePatternBtn" title="Duplicate selected pattern">Dupe</button>
<button id="deletePatternBtn" title="Delete selected pattern">Delete</button>
<button id="shareBtn" title="Share song (copy URL)">Share</button>
</div>
</header>
<main>
<section class="section" id="patternsSection">
<h2>Patterns</h2>
<div id="patternSelector"></div>
<div id="patternGrid"></div>
</section>
<section class="section" id="sequencerSection">
<h2>Sequencer</h2>
<div>
<label>Song sequence (pattern order):</label>
<div id="sequenceRow"></div>
</div>
</section>
<section class="section" id="instrumentsSection">
<h2>Instruments</h2>
<select id="instrumentSelect"></select>
<div id="instrumentParameters">
<label class="instrParam">Waveform:
<select id="waveformSelect">
<option value="sine">Sine</option>
<option value="square">Square</option>
<option value="triangle">Triangle</option>
<option value="sawtooth">Sawtooth</option>
<option value="custom">Custom (PWM)</option>
</select>
</label>
<label class="instrParam">Volume: <input type="range" id="volumeRange" min="0" max="1" step="0.01" value="0.5" /></label>
<label class="instrParam">Detune (cents): <input type="number" id="detuneInput" min="-1200" max="1200" step="1" value="0"/></label>
<fieldset class="instrParam">
<legend>ADSR Envelope (ms)</legend>
<label>Attack: <input type="number" id="attackInput" min="0" max="3000" step="10" value="10" /></label><br>
<label>Decay: <input type="number" id="decayInput" min="0" max="3000" step="10" value="50" /></label><br>
<label>Sustain (0..1): <input type="number" id="sustainInput" min="0" max="1" step="0.01" value="0.3" /></label><br>
<label>Release: <input type="number" id="releaseInput" min="0" max="3000" step="10" value="100" /></label>
</fieldset>
<fieldset class="instrParam">
<legend>Filter</legend>
<label>Type:
<select id="filterTypeSelect">
<option value="none">None</option>
<option value="lowpass">Low-pass</option>
<option value="highpass">High-pass</option>
<option value="bandpass">Band-pass</option>
</select>
</label>
<label>Frequency (Hz):
<input type="number" id="filterFreqInput" min="20" max="20000" value="1500" />
</label>
<label>Q:
<input type="number" id="filterQInput" min="0.1" max="20" step="0.1" value="1" />
</label>
</fieldset>
<label class="instrParam">Noise Amount: <input type="range" id="noiseAmountRange" min="0" max="1" step="0.01" value="0" /></label>
</div>
</section>
</main>
<div class="footer">
Keyboard shortucts:<br>
Arrows: navigate cells | Space/Enter: edit note | Ctrl+C/V: copy/paste pattern | Del: delete cell | L: toggle loop | P: play/stop
</div>
<script>
// --- Constants & helpers ---
const NOTES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#','G','G#','A','A#','B'];
const MIDI_A4 = 69;
const FREQ_A4 = 440;
const NOTE_FREQUENCIES = (() => {
// MIDI note to frequency map: 0= C-1 ~ 127=G9
let map = {};
for(let i=0; i<=127; i++) {
map[i] = FREQ_A4 * Math.pow(2, (i - MIDI_A4)/12);
}
return map;
})();
function midiNoteToName(midi) {
if(midi < 0) return "---";
let octave = Math.floor(midi/12) - 1;
let noteName = NOTES[midi % 12];
return noteName + octave;
}
function nameToMidiNote(note) {
// Parse e.g. "C4" or "A#3"
let m = note.match(/^([A-G]#?)(-?\d)$/);
if(!m) return -1;
let n = NOTES.indexOf(m[1]);
let octave = Number(m[2]);
if (n < 0) return -1;
return (octave+1)*12 + n;
}
// --- Song Data Structures ---
class Instrument {
constructor() {
this.waveform = 'square'; // sine, square, triangle, sawtooth, custom
this.volume = 0.5;
this.detune = 0;
this.adsr = { attack: 0.01, decay: 0.05, sustain: 0.3, release: 0.1 };
this.filter = { type: 'none', frequency: 1500, Q: 1 };
this.noise = 0; // noise amount 0..1
}
}
class Pattern {
constructor(rows, channels) {
// rows x channels array of notes (note = midi note number or -1 for empty)
this.rows = rows;
this.channels = channels;
this.data = [];
for(let r=0; r<rows; r++) {
this.data[r] = [];
for(let c=0; c<channels; c++) {
this.data[r][c] = -1;
}
}
}
clone() {
let p = new Pattern(this.rows,this.channels);
for(let r=0; r<this.rows; r++) {
for(let c=0; c<this.channels; c++) {
p.data[r][c] = this.data[r][c];
}
}
return p;
}
}
class Song {
constructor(bpm=120, patternsCount=4, rowsPerPattern=16, instrumentsCount=3) {
this.bpm = bpm;
this.rowsPerPattern = rowsPerPattern;
this.channels = instrumentsCount;
this.patterns = [];
this.sequence = []; // pattern indexes in song order
this.instruments = [];
for(let i=0; i<instrumentsCount; i++) {
this.instruments.push(new Instrument());
}
for(let i=0; i<patternsCount; i++) {
this.patterns.push(new Pattern(rowsPerPattern, instrumentsCount));
this.sequence.push(i);
}
}
}
// --- Global State ---
let song = new Song();
let audioCtx = null;
let timerId = null;
let playing = false;
let currentRow = 0;
let currentSeqPos = 0;
let loop = true;
let selectedPatternIndex = 0;
let copiedPattern = null;
let selectedCell = {row:0, col:0};
const SEMITONES = 12;
const ROW_INTERVAL_DEFAULT = 0.125; // quarter beat, to be calculated
// --- DOM Elements ---
const bpmInput = document.getElementById('bpmInput');
const patternsCountInput = document.getElementById('patternsCount');
const rowsPerPatternInput = document.getElementById('rowsPerPattern');
const instrumentsCountInput = document.getElementById('instrumentsCount');
const resetSongBtn = document.getElementById('resetSongBtn');
const playBtn = document.getElementById('playBtn');
const stopBtn = document.getElementById('stopBtn');
const loopToggle = document.getElementById('loopToggle');
const patternSelector = document.getElementById('patternSelector');
const patternGrid = document.getElementById('patternGrid');
const sequenceRow = document.getElementById('sequenceRow');
const instrumentSelect = document.getElementById('instrumentSelect');
const waveformSelect = document.getElementById('waveformSelect');
const volumeRange = document.getElementById('volumeRange');
const detuneInput = document.getElementById('detuneInput');
const attackInput = document.getElementById('attackInput');
const decayInput = document.getElementById('decayInput');
const sustainInput = document.getElementById('sustainInput');
const releaseInput = document.getElementById('releaseInput');
const filterTypeSelect = document.getElementById('filterTypeSelect');
const filterFreqInput = document.getElementById('filterFreqInput');
const filterQInput = document.getElementById('filterQInput');
const noiseAmountRange = document.getElementById('noiseAmountRange');
const copyPatternBtn = document.getElementById('copyPatternBtn');
const pastePatternBtn = document.getElementById('pastePatternBtn');
const dupePatternBtn = document.getElementById('dupePatternBtn');
const deletePatternBtn = document.getElementById('deletePatternBtn');
const shareBtn = document.getElementById('shareBtn');
// --- Functions ---
function initAudio() {
if (!audioCtx) {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
}
}
// Calculate ms per row step time based on BPM and assuming 4 rows = 1 beat (16th notes)
function calcRowInterval(bpm, rowsPerBeat = 4) {
return (60000 / bpm) / rowsPerBeat;
}
function createCustomWaveform(audioCtx, dutyCycle=0.5) {
// Create custom PWM square wave with variable duty cycle
// Using periodicWave
let real = new Float32Array(32);
let imag = new Float32Array(32);
for(let n=1; n<32; n+=2) {
real[n] = 4/ (Math.PI * n) * Math.sin(Math.PI * n * dutyCycle);
}
return audioCtx.createPeriodicWave(real, imag);
}
function playNote(instrument, frequency, lengthSeconds) {
if(!audioCtx) return;
let osc = audioCtx.createOscillator();
let gainNode = audioCtx.createGain();
let filterNode = audioCtx.createBiquadFilter();
const now = audioCtx.currentTime;
// Waveform
if(instrument.waveform==='custom') {
osc.setPeriodicWave(createCustomWaveform(audioCtx, 0.3));
} else {
osc.type = instrument.waveform;
}
osc.frequency.setValueAtTime(frequency, now);
osc.detune.setValueAtTime(instrument.detune, now);
// Filter config
if(instrument.filter.type==='none') {
filterNode.frequency.setValueAtTime(audioCtx.sampleRate/2, now);
filterNode.Q.setValueAtTime(0, now);
filterNode.type = 'allpass'; // effectively no filter
}
else {
filterNode.type = instrument.filter.type;
filterNode.frequency.setValueAtTime(instrument.filter.frequency, now);
filterNode.Q.setValueAtTime(instrument.filter.Q, now);
}
// Connect nodes
osc.connect(filterNode);
filterNode.connect(gainNode);
// Noise source - white noise buffer trick
let noiseGainNode = audioCtx.createGain();
noiseGainNode.gain.setValueAtTime(instrument.noise * instrument.volume, now);
gainNode.gain.setValueAtTime(0, now); // will shape with ADSR
let noiseSource = null;
if(instrument.noise > 0) {
noiseSource = audioCtx.createBufferSource();
const bufferSize = audioCtx.sampleRate;
const buffer = audioCtx.createBuffer(1, bufferSize, audioCtx.sampleRate);
const data = buffer.getChannelData(0);
for(let i=0; i<bufferSize; i++) {
data[i] = (Math.random()*2 - 1);
}
noiseSource.buffer = buffer;
noiseSource.loop = true;
noiseSource.connect(noiseGainNode);
noiseGainNode.connect(gainNode);
noiseSource.start(now);
}
gainNode.connect(audioCtx.destination);
// ADSR envelope
let env = instrument.adsr;
// Quick safety for zero attack etc.
let attack = Math.max(0.001, env.attack);
let decay = env.decay;
let sustain = env.sustain;
let release = Math.max(0.01, env.release);
gainNode.gain.cancelScheduledValues(now);
gainNode.gain.setValueAtTime(0, now);
gainNode.gain.linearRampToValueAtTime(instrument.volume, now + attack);
gainNode.gain.linearRampToValueAtTime(instrument.volume * sustain, now + attack + decay);
osc.start(now);
// Stop after lengthSeconds using release envelope
gainNode.gain.setValueAtTime(instrument.volume * sustain, now + lengthSeconds);
gainNode.gain.linearRampToValueAtTime(0, now + lengthSeconds + release);
osc.stop(now + lengthSeconds + release + 0.05);
if(noiseSource) {
noiseGainNode.gain.setValueAtTime(instrument.noise * instrument.volume * sustain, now + lengthSeconds);
noiseGainNode.gain.linearRampToValueAtTime(0, now + lengthSeconds + release);
noiseSource.stop(now + lengthSeconds + release + 0.05);
}
}
// Playback sequencer
function playSong() {
if (playing) return;
initAudio();
playing = true;
playBtn.disabled = true;
stopBtn.disabled = false;
currentRow = 0;
currentSeqPos = 0;
tickPlayback();
}
function stopSong() {
playing = false;
playBtn.disabled = false;
stopBtn.disabled = true;
if (timerId) {
clearTimeout(timerId);
timerId = null;
}
currentRow = 0;
currentSeqPos = 0;
renderPatternGrid();
renderSequenceRow();
}
// Play one step and schedule next
function tickPlayback() {
if(!playing) return;
const patternIndex = song.sequence[currentSeqPos];
const pattern = song.patterns[patternIndex];
if(!pattern) {
// skip missing patterns
nextTick();
return;
}
const row = currentRow;
// Play notes for this row and all channels (instruments)
for(let c=0; c<song.channels; c++) {
let note = pattern.data[row][c];
if(note >= 0) {
// Note freq
let freq = NOTE_FREQUENCIES[note];
if(freq) {
// Play sound length 1 row interval approx
playNote(song.instruments[c], freq, rowIntervalMs/1000 * 0.9);
}
}
}
highlightPlayingCell(row);
nextTick();
function nextTick() {
currentRow++;
if(currentRow >= song.rowsPerPattern) {
currentRow = 0;
currentSeqPos++;
if(currentSeqPos >= song.sequence.length) {
if(loop) {
currentSeqPos = 0;
}
else {
// End
stopSong();
return;
}
}
}
timerId = setTimeout(tickPlayback, rowIntervalMs);
}
}
// --- UI Rendering & interaction ---
function renderPatternSelector() {
patternSelector.innerHTML = "";
for(let i=0; i<song.patterns.length; i++) {
let btn = document.createElement('button');
btn.textContent = "Pattern " + i;
if(i === selectedPatternIndex) btn.style.backgroundColor = '#3a7';
btn.onclick = () => {
selectedPatternIndex = i;
selectedCell.row = 0;
selectedCell.col = 0;
renderPatternSelector();
renderPatternGrid();
renderSequenceRow();
renderInstrumentSelect();
};
patternSelector.appendChild(btn);
}
}
function renderPatternGrid() {
patternGrid.innerHTML = "";
const pattern = song.patterns[selectedPatternIndex];
if(!pattern) return;
let table = document.createElement('table');
// Header row: channel number (instrument)
let header = document.createElement('tr');
let cell = document.createElement('th');
cell.textContent = "Row";
header.appendChild(cell);
for(let c=0; c < song.channels; c++) {
let th = document.createElement('th');
th.textContent = "Ch " + c;
header.appendChild(th);
}
table.appendChild(header);
for(let r=0; r<pattern.rows; r++) {
let tr = document.createElement('tr');
let rowLabel = document.createElement('td');
rowLabel.textContent = r;
tr.appendChild(rowLabel);
for(let c=0; c < song.channels; c++) {
let td = document.createElement('td');
let note = pattern.data[r][c];
td.className = "note";
td.textContent = midiNoteToName(note);
if(r === selectedCell.row && c === selectedCell.col) {
td.classList.add('selected');
}
td.onclick = () => {
selectedCell = {row: r, col: c};
renderPatternGrid();
};
tr.appendChild(td);
}
table.appendChild(tr);
}
patternGrid.appendChild(table);
}
function highlightPlayingCell(row) {
// highlight current playing row in pattern
let rows = patternGrid.querySelectorAll('tr');
rows.forEach((r, i) => {
if(i===row+1) { // offset 1 for header
r.style.backgroundColor = '#222';
}
else {
r.style.backgroundColor = '';
}
});
}
function renderSequenceRow() {
sequenceRow.innerHTML = "";
for(let i=0; i<song.sequence.length; i++) {
let btn = document.createElement('button');
btn.textContent = song.sequence[i];
if(i === currentSeqPos) btn.style.backgroundColor = '#3a7';
btn.onclick = () => {
currentSeqPos = i;
currentRow = 0;
renderSequenceRow();
renderPatternSelector();
renderPatternGrid();
};
sequenceRow.appendChild(btn);
}
}
function renderInstrumentSelect() {
instrumentSelect.innerHTML = "";
for(let i=0; i<song.instruments.length; i++) {
let opt = document.createElement('option');
opt.value = i;
opt.textContent = "Instrument " + i;
instrumentSelect.appendChild(opt);
}
instrumentSelect.value = selectedCell.col;
renderInstrumentParams(selectedCell.col);
}
function renderInstrumentParams(index) {
if(index < 0 || index >= song.instruments.length) return;
let instr = song.instruments[index];
waveformSelect.value = instr.waveform;
volumeRange.value = instr.volume;
detuneInput.value = instr.detune;
attackInput.value = instr.adsr.attack*1000;
decayInput.value = instr.adsr.decay*1000;
sustainInput.value = instr.adsr.sustain;
releaseInput.value = instr.adsr.release*1000;
filterTypeSelect.value = instr.filter.type;
filterFreqInput.value = instr.filter.frequency;
filterQInput.value = instr.filter.Q;
noiseAmountRange.value = instr.noise;
}
// --- Event Handlers ---
bpmInput.onchange = () => {
let val = Number(bpmInput.value);
if(val < 30) val = 30;
if(val > 300) val = 300;
bpmInput.value = val;
song.bpm = val;
updateIntervals();
};
patternsCountInput.onchange = () => {
let val = Number(patternsCountInput.value);
if(val < 1) val = 1;
if(val > 32) val = 32;
patternsCountInput.value = val;
while(song.patterns.length < val) {
song.patterns.push(new Pattern(song.rowsPerPattern, song.channels));
song.sequence.push(song.patterns.length-1);
}
if(song.patterns.length > val) {
song.patterns.splice(val);
song.sequence = song.sequence.filter(pi => pi < val);
}
renderPatternSelector();
renderPatternGrid();
renderSequenceRow();
};
rowsPerPatternInput.onchange = () => {
let val = Number(rowsPerPatternInput.value);
if(val < 1) val = 1;
if(val > 64) val = 64;
rowsPerPatternInput.value = val;
song.rowsPerPattern = val;
// Resize patterns
song.patterns.forEach(p => {
if(val > p.rows) {
// Add rows
for(let r=p.rows; r<val; r++) {
p.data[r] = new Array(song.channels).fill(-1);
}
p.rows = val;
} else if(val < p.rows) {
p.data.splice(val);
p.rows = val;
}
});
renderPatternGrid();
};
instrumentsCountInput.onchange = () => {
let val = Number(instrumentsCountInput.value);
if(val < 1) val = 1;
if(val > 8) val = 8;
instrumentsCountInput.value = val;
if(val > song.channels) {
for(let i=song.channels; i<val; i++) {
song.instruments.push(new Instrument());
song.patterns.forEach(p =>{
p.data.forEach(row => {
row.push(-1);
});
p.channels++;
});
}
} else if(val < song.channels) {
song.instruments.splice(val);
song.patterns.forEach(p => {
p.data.forEach(row => row.splice(val));
p.channels = val;
});
}
song.channels = val;
renderPatternGrid();
renderInstrumentSelect();
};
resetSongBtn.onclick = () => {
if(confirm("Reset song? All data will be lost.")) {
song = new Song(bpmInput.value, patternsCountInput.value, rowsPerPatternInput.value, instrumentsCountInput.value);
selectedPatternIndex = 0;
selectedCell = {row:0, col:0};
updateIntervals();
renderAll();
}
};
playBtn.onclick = () => playSong();
stopBtn.onclick = () => stopSong();
loopToggle.onchange = () => {
loop = loopToggle.checked;
};
// Pattern edit buttons
copyPatternBtn.onclick = () => {
copiedPattern = song.patterns[selectedPatternIndex].clone();
alert("Pattern copied");
};
pastePatternBtn.onclick = () => {
if(copiedPattern) {
song.patterns[selectedPatternIndex] = copiedPattern.clone();
renderPatternGrid();
alert("Pattern pasted");
}
};
dupePatternBtn.onclick = () => {
let p = song.patterns[selectedPatternIndex].clone();
song.patterns.splice(selectedPatternIndex+1, 0, p);
song.sequence.splice(selectedPatternIndex + 1, 0, selectedPatternIndex + 1);
patternsCountInput.value = song.patterns.length;
renderPatternSelector();
renderSequenceRow();
alert("Pattern duplicated");
};
deletePatternBtn.onclick = () => {
if(song.patterns.length <= 1) {
alert("Cannot delete the last pattern");
return;
}
song.patterns.splice(selectedPatternIndex,1);
song.sequence = song.sequence.filter(pi => pi !== selectedPatternIndex)
.map(pi => pi > selectedPatternIndex ? pi -1 : pi);
if(selectedPatternIndex >= song.patterns.length) selectedPatternIndex = song.patterns.length -1;
patternsCountInput.value = song.patterns.length;
renderPatternSelector();
renderPatternGrid();
renderSequenceRow();
};
// Pattern cell editing with note input, delete etc
patternGrid.addEventListener('keydown', e => {
e.preventDefault(); // prevent scrolling
if(!patternGrid.contains(document.activeElement)) {
return;
}
const p = song.patterns[selectedPatternIndex];
let r = selectedCell.row;
let c = selectedCell.col;
switch(e.key) {
case 'ArrowUp': r = (r - 1 + p.rows) % p.rows; break;
case 'ArrowDown': r = (r + 1) % p.rows; break;
case 'ArrowLeft': c = (c - 1 + song.channels) % song.channels; break;
case 'ArrowRight': c = (c + 1) % song.channels; break;
case ' ': // toggle note on/off (add middle C4 as default)
case 'Enter':
if(p.data[r][c] < 0) p.data[r][c] = 60;
else p.data[r][c] = -1;
break;
case 'Delete':
case 'Backspace':
p.data[r][c] = -1;
break;
default:
// check note input keys (C, C#, D, etc)
let noteNameUpper = e.key.toUpperCase();
if(['A','B','C','D','E','F','G'].includes(noteNameUpper)) {
// Insert note with octave 4 by default.
let baseNote = noteNameUpper;
let semi = NOTES.indexOf(baseNote);
if(semi < 0) {
// maybe sharp?
if(e.shiftKey) {
baseNote = baseNote + '#';
semi = NOTES.indexOf(baseNote);
}
}
let midi = nameToMidiNote(baseNote + "4"); // default octave 4
if(midi >= 0) {
p.data[r][c] = midi;
}
}
}
selectedCell.row = r;
selectedCell.col = c;
renderPatternGrid();
});
patternGrid.tabIndex = 0;
patternGrid.focus();
function updateIntervals() {
rowIntervalMs = calcRowInterval(song.bpm, 4);
}
waveformSelect.onchange = () => {
song.instruments[selectedCell.col].waveform = waveformSelect.value;
};
volumeRange.oninput = () => {
song.instruments[selectedCell.col].volume = Number(volumeRange.value);
};
detuneInput.onchange = () => {
song.instruments[selectedCell.col].detune = Number(detuneInput.value);
};
attackInput.onchange = () => {
song.instruments[selectedCell.col].adsr.attack = Number(attackInput.value)/1000;
};
decayInput.onchange = () => {
song.instruments[selectedCell.col].adsr.decay = Number(decayInput.value)/1000;
};
sustainInput.onchange = () => {
let s = Number(sustainInput.value);
s = Math.min(1, Math.max(0, s));
song.instruments[selectedCell.col].adsr.sustain = s;
sustainInput.value = s;
};
releaseInput.onchange = () => {
song.instruments[selectedCell.col].adsr.release = Number(releaseInput.value)/1000;
};
filterTypeSelect.onchange = () => {
song.instruments[selectedCell.col].filter.type = filterTypeSelect.value;
};
filterFreqInput.onchange = () => {
let v = Number(filterFreqInput.value);
if(v < 20) v = 20;
if(v > 20000) v = 20000;
filterFreqInput.value = v;
song.instruments[selectedCell.col].filter.frequency = v;
};
filterQInput.onchange = () => {
let v = Number(filterQInput.value);
if(v < 0.1) v = 0.1;
if(v > 20) v = 20;
filterQInput.value = v;
song.instruments[selectedCell.col].filter.Q = v;
};
noiseAmountRange.oninput = () => {
song.instruments[selectedCell.col].noise = Number(noiseAmountRange.value);
};
instrumentSelect.onchange = () => {
selectedCell.col = Number(instrumentSelect.value);
renderInstrumentParams(selectedCell.col);
renderPatternGrid();
};
// Share functionality (serialize song data in URL hash)
function serializeSong() {
// Simple JSON string base64 compressed (try compress later)
return btoa(JSON.stringify(song));
}
function deserializeSong(str) {
try {
let json = atob(str);
let obj = JSON.parse(json);
// minimal validation here, rebuild Song
let s = new Song(obj.bpm, obj.patterns.length, obj.rowsPerPattern, obj.instruments.length);
s.bpm = obj.bpm;
s.rowsPerPattern = obj.rowsPerPattern;
s.channels = obj.channels;
s.sequence = obj.sequence || s.sequence;
s.instruments = obj.instruments.map(i => {
let instr = new Instrument();
Object.assign(instr, i);
return instr;
});
s.patterns = obj.patterns.map(p => {
let pat = new Pattern(p.rows, p.channels);
pat.rows = p.rows;
pat.channels = p.channels;
pat.data = p.data;
return pat;
});
return s;
} catch(e) {
alert("Error decoding song from URL");
return null;
}
}
shareBtn.onclick = () => {
let str = serializeSong();
let url = location.origin + location.pathname + "/#" + str;
navigator.clipboard.writeText(url).then(() => {
alert("Share URL copied to clipboard");
}, () => {
alert("Copy failed, here is the URL:\n" + url);
});
};
function loadFromUrlHash() {
if(location.hash.length > 2) {
let s = location.hash.substring(2);
let loaded = deserializeSong(s);
if(loaded) {
song = loaded;
bpmInput.value = song.bpm;
rowsPerPatternInput.value = song.rowsPerPattern;
patternsCountInput.value = song.patterns.length;
instrumentsCountInput.value = song.channels;
selectedPatternIndex = 0;
selectedCell = {row:0, col:0};
updateIntervals();
renderAll();
}
}
}
function renderAll() {
renderPatternSelector();
renderPatternGrid();
renderSequenceRow();
renderInstrumentSelect();
}
// --- Init
let rowIntervalMs = calcRowInterval(song.bpm, 4);
loadFromUrlHash();
renderAll();
</script>
</body>
</html>
This code is a minimal but solid foundation, and you can extend it with things like:
If you want me to help expand any part (e.g. chords, or true multi-note cells, or custom waveform editor UI), just ask!