html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>HTML Chiptune Tracker</title>
<style>
body { font-family: monospace; background:#222; color:#eee; margin:0; padding:10px; }
#tracker { display: flex; flex-direction: row; gap: 10px; }
#pattern, #instrument { background: #333; padding: 10px; border-radius: 5px; }
table { border-collapse: collapse; }
td, th { border: 1px solid #444; padding: 2px 5px; text-align: center; }
td.note { cursor: pointer; user-select:none; }
td.note.active { background: #4caf50; }
label { display: block; margin-top: 10px; }
input[type=range] { width: 100%; }
button { margin-top:10px; }
</style>
</head>
<body>
<h1>HTML Chiptune Tracker</h1>
<div>
<label>BPM: <input id="bpm" type="number" min="30" max="300" value="120" /></label>
<label>Rows per Pattern: <input id="rows" type="number" min="4" max="64" value="16" /></label>
<button id="playPause">Play</button>
<button id="loopToggle">Loop: ON</button>
<button id="shareBtn">Share Song (copy URL)</button>
</div>
<div id="tracker">
<div id="pattern">
<h2>Pattern</h2>
<table id="patternTable"></table>
</div>
<div id="instrument">
<h2>Instrument</h2>
<label>Oscillator:
<select id="oscType">
<option value="square">Square</option>
<option value="sawtooth">Sawtooth</option>
<option value="triangle">Triangle</option>
<option value="sine">Sine</option>
<option value="custom">Custom Noise</option>
</select>
</label>
<label>Volume: <input id="instVolume" type="range" min="0" max="1" step="0.01" value="0.5" /></label>
<label>Detune (cents): <input id="instDetune" type="range" min="-1200" max="1200" step="1" value="0" /></label>
<label>ADSR (ms):</label>
<label>Attack: <input id="attack" type="number" min="0" max="1000" value="10" /></label>
<label>Decay: <input id="decay" type="number" min="0" max="1000" value="50" /></label>
<label>Sustain (0-1): <input id="sustain" type="number" min="0" max="1" step="0.01" value="0.7" /></label>
<label>Release: <input id="release" type="number" min="0" max="1000" value="200" /></label>
<label>Filter Cutoff (Hz): <input id="filterCutoff" type="number" min="20" max="20000" value="8000" /></label>
<label>Noise Level: <input id="noiseLevel" type="range" min="0" max="1" step="0.01" value="0" /></label>
</div>
</div>
<script>
(() => {
const ctx = new(window.AudioContext || window.webkitAudioContext)();
// Constants
const NOTES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
const BASE_OCTAVE = 4;
const MAX_PATTERNS = 8;
const MAX_INSTRUMENTS = 4;
// State
let bpm = 120;
let rowsPerPattern = 16;
let currentPattern = 0;
let currentInstrument = 0;
let patterns = []; // pattern[patternIndex] = array of rows, each row = array of note nums or null
let instruments = [];
let playing = false;
let loop = true;
let playPos = 0; // current row
// Setup initial patterns and instruments
function createEmptyPattern() {
const pattern = [];
for (let i = 0; i < rowsPerPattern; i++) {
pattern.push(new Array(MAX_INSTRUMENTS).fill(null));
}
return pattern;
}
function createDefaultInstrument() {
return {
oscType: 'square',
volume: 0.5,
detune: 0,
adsr: { attack: 10, decay: 50, sustain: 0.7, release: 200 },
filterCutoff: 8000,
noiseLevel: 0,
};
}
for(let i=0; i < MAX_PATTERNS; i++) {
patterns.push(createEmptyPattern());
}
for(let i=0; i < MAX_INSTRUMENTS; i++) {
instruments.push(createDefaultInstrument());
}
// UI Elements
const bpmInput = document.getElementById('bpm');
const rowsInput = document.getElementById('rows');
const playPauseBtn = document.getElementById('playPause');
const loopToggleBtn = document.getElementById('loopToggle');
const patternTable = document.getElementById('patternTable');
const shareBtn = document.getElementById('shareBtn');
const oscTypeSel = document.getElementById('oscType');
const instVolume = document.getElementById('instVolume');
const instDetune = document.getElementById('instDetune');
const attackIn = document.getElementById('attack');
const decayIn = document.getElementById('decay');
const sustainIn = document.getElementById('sustain');
const releaseIn = document.getElementById('release');
const filterCutoffIn = document.getElementById('filterCutoff');
const noiseLevelIn = document.getElementById('noiseLevel');
// Helper to freq from note number (e.g. MIDI)
function noteNumToFreq(num) {
return 440 * Math.pow(2, (num - 69) / 12);
}
// Draw pattern UI
function drawPattern() {
patternTable.innerHTML = '';
// header
const thead = document.createElement('thead');
const headerRow = document.createElement('tr');
headerRow.appendChild(document.createElement('th')); // empty corner
for (let inst=0; inst < MAX_INSTRUMENTS; inst++) {
const th = document.createElement('th');
th.textContent = `Inst ${inst+1}`;
headerRow.appendChild(th);
}
thead.appendChild(headerRow);
patternTable.appendChild(thead);
// rows
const tbody = document.createElement('tbody');
for (let row=0; row < rowsPerPattern; row++) {
const tr = document.createElement('tr');
const th = document.createElement('th');
th.textContent = row+1;
tr.appendChild(th);
for (let inst=0; inst < MAX_INSTRUMENTS; inst++) {
const td = document.createElement('td');
td.classList.add('note');
const n = patterns[currentPattern][row][inst];
td.textContent = n === null ? '-' : noteNumToName(n);
if (n !== null) td.classList.add('active');
td.dataset.row = row;
td.dataset.inst = inst;
td.addEventListener('click', onNoteClick);
tr.appendChild(td);
}
tbody.appendChild(tr);
}
patternTable.appendChild(tbody);
}
// Translate MIDI note number to note name with octave (e.g. 60 -> C4)
function noteNumToName(num) {
if(num === null) return '-';
let octave = Math.floor(num / 12) - 1;
let note = NOTES[num % 12];
return note + octave;
}
// Reverse: parse note name (e.g., C4, A#3) to MIDI number
function nameToNoteNum(name) {
const regex = /^([A-G])(#|b)?(\d)$/;
const m = regex.exec(name);
if (!m) return null;
let [, letter, accidental, octave] = m;
let note = NOTES.findIndex(n => n[0] === letter && (accidental ? n.includes(accidental) : true));
if (note === -1) return null;
// correction needed for flats and sharps
if (accidental === 'b') note = (note + 11) % 12; // flatten note
octave = parseInt(octave);
return 12 * (octave + 1) + note;
}
// On note cell click: cycle note C4-C5 or clear
function onNoteClick(e) {
const r = +e.target.dataset.row;
const i = +e.target.dataset.inst;
let val = patterns[currentPattern][r][i];
// cycle notes for demo: C4(60) -> D4(62) -> E4(64) -> (null)
// better: open a picker later - for now cycle among 60,62,64, null
const cycle = [60,62,64,null];
let idx = cycle.indexOf(val);
idx = (idx + 1) % cycle.length;
patterns[currentPattern][r][i] = cycle[idx];
drawPattern();
}
// Update instrument UI from selected instrument
function updateInstUI() {
const inst = instruments[currentInstrument];
oscTypeSel.value = inst.oscType;
instVolume.value = inst.volume;
instDetune.value = inst.detune;
attackIn.value = inst.adsr.attack;
decayIn.value = inst.adsr.decay;
sustainIn.value = inst.adsr.sustain;
releaseIn.value = inst.adsr.release;
filterCutoffIn.value = inst.filterCutoff;
noiseLevelIn.value = inst.noiseLevel;
}
// Update instrument data from UI inputs
function updateInstData() {
let inst = instruments[currentInstrument];
inst.oscType = oscTypeSel.value;
inst.volume = parseFloat(instVolume.value);
inst.detune = parseFloat(instDetune.value);
inst.adsr.attack = parseInt(attackIn.value);
inst.adsr.decay = parseInt(decayIn.value);
inst.adsr.sustain = parseFloat(sustainIn.value);
inst.adsr.release = parseInt(releaseIn.value);
inst.filterCutoff = parseInt(filterCutoffIn.value);
inst.noiseLevel = parseFloat(noiseLevelIn.value);
}
// Audio play note helper with ADSR and filter & noise
function playNote(noteNum, inst) {
if(noteNum === null) return;
const now = ctx.currentTime;
// oscillator
let osc;
if (inst.oscType === 'custom') {
// noise source
osc = createNoiseNode();
} else {
osc = ctx.createOscillator();
osc.type = inst.oscType;
osc.frequency.value = noteNumToFreq(noteNum);
osc.detune.value = inst.detune;
}
// gain for volume and ADSR envelope
const gainNode = ctx.createGain();
gainNode.gain.setValueAtTime(0, now);
// filter
const filter = ctx.createBiquadFilter();
filter.type = 'lowpass';
filter.frequency.setValueAtTime(inst.filterCutoff, now);
// Connect nodes
osc.connect(filter);
// Add noise mixer if noiseLevel > 0
if (inst.noiseLevel > 0 && inst.oscType !== 'custom') {
const noise = createNoiseNode();
const noiseGain = ctx.createGain();
noiseGain.gain.value = inst.noiseLevel;
noise.connect(noiseGain);
noiseGain.connect(filter);
noise.start(now);
// Stop noise after release
noise.stop(now + (inst.adsr.attack + inst.adsr.decay + inst.adsr.release)/1000 + 1);
}
filter.connect(gainNode);
gainNode.connect(ctx.destination);
// Start oscillator/noise
osc.start(now);
// ADSR Envelope
const attackSec = inst.adsr.attack/1000;
const decaySec = inst.adsr.decay/1000;
const releaseSec = inst.adsr.release/1000;
gainNode.gain.cancelScheduledValues(now);
gainNode.gain.setValueAtTime(0, now);
gainNode.gain.linearRampToValueAtTime(inst.volume, now + attackSec);
gainNode.gain.linearRampToValueAtTime(inst.volume * inst.adsr.sustain, now + attackSec + decaySec);
// Hold note till release (here play one row duration)
let dur = 60 / bpm * (4 / rowsPerPattern); // rough calculation:
setTimeout(() => {
const t1 = ctx.currentTime;
gainNode.gain.cancelScheduledValues(t1);
gainNode.gain.setValueAtTime(gainNode.gain.value, t1);
gainNode.gain.linearRampToValueAtTime(0, t1 + releaseSec);
osc.stop(t1 + releaseSec + 0.1);
}, dur * 1000);
}
// Noise node generator for custom waveform
function createNoiseNode() {
const bufferSize = 2 * ctx.sampleRate;
const noiseBuffer = ctx.createBuffer(1, bufferSize, ctx.sampleRate);
const output = noiseBuffer.getChannelData(0);
for (let i = 0; i < bufferSize; i++) {
output[i] = Math.random() * 2 - 1;
}
const whiteNoise = ctx.createBufferSource();
whiteNoise.buffer = noiseBuffer;
whiteNoise.loop = true;
return whiteNoise;
}
// Playback loop with step sequencer
let schedulerId = null;
function startPlayback() {
if (ctx.state === 'suspended') ctx.resume();
playing = true;
playPauseBtn.textContent = 'Stop';
playPos = 0;
scheduleStep();
}
function stopPlayback() {
playing = false;
playPauseBtn.textContent = 'Play';
if(schedulerId) {
clearTimeout(schedulerId);
schedulerId = null;
}
}
function scheduleStep() {
if (!playing) return;
// Play notes for current step
const rowNotes = patterns[currentPattern][playPos];
for(let i =0; i < MAX_INSTRUMENTS; i++) {
if(rowNotes[i] !== null) {
playNote(rowNotes[i], instruments[i]);
}
}
playPos++;
if(playPos >= rowsPerPattern) {
if(loop) playPos = 0;
else {
stopPlayback();
return;
}
}
// Schedule next step
const msPerBeat = 60000 / bpm;
const msPerRow = msPerBeat * (4 / rowsPerPattern); // assuming 4/4 time
schedulerId = setTimeout(scheduleStep, msPerRow);
}
// Update from inputs
bpmInput.addEventListener('change', () => {
bpm = Math.max(30, Math.min(300, +bpmInput.value));
if (playing) stopPlayback();
});
rowsInput.addEventListener('change', () => {
const newRows = Math.max(4, Math.min(64, +rowsInput.value));
if(newRows !== rowsPerPattern) {
rowsPerPattern = newRows;
// recreate patterns with new length
for(let p=0; p<patterns.length; p++) {
let pat = patterns[p];
if(pat.length > rowsPerPattern) {
patterns[p] = pat.slice(0, rowsPerPattern);
} else if (pat.length < rowsPerPattern) {
for(let r=pat.length; r < rowsPerPattern; r++) {
pat.push(new Array(MAX_INSTRUMENTS).fill(null));
}
}
}
drawPattern();
if (playing) stopPlayback();
}
});
playPauseBtn.addEventListener('click', () => {
if(playing) stopPlayback();
else startPlayback();
});
loopToggleBtn.addEventListener('click', () => {
loop = !loop;
loopToggleBtn.textContent = 'Loop: ' + (loop ? 'ON' : 'OFF');
});
oscTypeSel.addEventListener('change', () => {
updateInstData();
});
instVolume.addEventListener('input', () => {
updateInstData();
});
instDetune.addEventListener('input', () => {
updateInstData();
});
attackIn.addEventListener('input', () => {
updateInstData();
});
decayIn.addEventListener('input', () => {
updateInstData();
});
sustainIn.addEventListener('input', () => {
updateInstData();
});
releaseIn.addEventListener('input', () => {
updateInstData();
});
filterCutoffIn.addEventListener('input', () => {
updateInstData();
});
noiseLevelIn.addEventListener('input', () => {
updateInstData();
});
// Share song via URL encoding patterns and instruments
function encodeData() {
// simple base64 encode JSON - for demo only
const data = { patterns, instruments, bpm, rowsPerPattern };
return btoa(JSON.stringify(data));
}
function decodeData(encoded) {
try {
const json = atob(encoded);
const data = JSON.parse(json);
// Validate minimally
if(data.patterns && data.instruments) {
patterns = data.patterns;
instruments = data.instruments;
bpm = data.bpm || 120;
rowsPerPattern = data.rowsPerPattern || 16;
}
} catch(e) {
alert('Invalid song data');
}
}
shareBtn.addEventListener('click', () => {
updateInstData();
const encoded = encodeData();
const url = `${location.origin}${location.pathname}#/song=${encoded}`;
navigator.clipboard.writeText(url).then(() => {
alert('Song URL copied to clipboard');
});
});
// Load song from URL on start
function loadFromURL() {
const hash = location.hash;
if(hash.startsWith('#/song=')) {
const encoded = hash.substr(7);
decodeData(encoded);
}
}
// Keyboard shortcuts
window.addEventListener('keydown', (e) => {
if(e.target.tagName === 'INPUT' || e.target.tagName === 'SELECT') return;
if(e.code === 'Space') {
e.preventDefault();
if(playing) stopPlayback();
else startPlayback();
} else if(e.code === 'ArrowDown') {
e.preventDefault();
currentPattern = (currentPattern + 1) % MAX_PATTERNS;
drawPattern();
} else if(e.code === 'ArrowUp') {
e.preventDefault();
currentPattern = (currentPattern - 1 + MAX_PATTERNS) % MAX_PATTERNS;
drawPattern();
} else if(e.code === "ArrowRight") {
e.preventDefault();
currentInstrument = (currentInstrument + 1) % MAX_INSTRUMENTS;
updateInstUI();
} else if(e.code === "ArrowLeft") {
e.preventDefault();
currentInstrument = (currentInstrument -1 + MAX_INSTRUMENTS) % MAX_INSTRUMENTS;
updateInstUI();
}
});
// Initial
loadFromURL();
updateInstUI();
drawPattern();
})();
</script>
</body>
</html>