Certainly! Here's a minimal HTML+JavaScript chiptune tracker concept that supports:
- BPM (tempo)
- Patterns with rows per pattern
- Multiple instruments, each with:
- Custom oscillator type (sine, square, sawtooth, triangle)
- Volume
- Detune
- ADSR envelope
- Simple filter (lowpass)
- Noise toggle per instrument
- Basic pattern playback with looping
- URL hash sharing of song data (
/# style)
- Keyboard shortcuts for playback (space to play/pause, arrows to navigate patterns)
- No demo audio autoplay (user initiated)
Below is a very basic implementation outline. You can expand with UI enhancements.
<!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; }
#tracker { display: flex; gap: 10px; margin-top: 10px; }
.pattern {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 2px;
}
input, select { background: #333; border: none; color: #eee; width: 100%; }
button { cursor: pointer; }
.row {
display: contents;
}
.cell {
padding: 2px 3px;
text-align: center;
border: 1px solid #444;
background: #111;
}
.cell.editing {
border-color: #0fc;
background: #222;
}
</style>
</head>
<body>
<h1>HTML Chiptune Tracker</h1>
Controls:<br/>
BPM: <input id="bpm" type="number" value="120" min="30" max="300" style="width:60px" />
Rows per pattern: <input id="rowsPerPattern" type="number" value="16" min="4" max="64" style="width:60px" />
<button id="addPatternBtn">Add Pattern</button>
<button id="playPauseBtn">Play</button>
<button id="loopBtn">Loop: ON</button>
<br/>
<div id="tracker"></div>
<h2>Instruments</h2>
<div id="instruments"></div>
<button id="addInstrumentBtn">Add Instrument</button>
<script>
// BASIC SETTINGS
let bpm = 120;
let rowsPerPattern = 16;
let isPlaying = false;
let loop = true;
let currentPattern = 0;
let currentRow = 0;
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
let timerId;
const notesMap = [
"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"
];
function noteToFreq(note) {
// note format: NoteOctave, e.g. C4, F#3
let notePart = note.slice(0, -1);
let octave = parseInt(note.slice(-1));
let n = notesMap.indexOf(notePart);
if (n < 0 || isNaN(octave)) return 0;
let keyNumber = n + (octave + 1) * 12;
return 440 * Math.pow(2, (keyNumber - 69) / 12);
}
function createInstrument(id) {
return {
id,
oscType: 'square',
volume: 0.5,
detune: 0,
adsr: {attack:0.01, decay:0.1, sustain:0.5, release:0.5},
filterFreq: 1000,
noise: false
};
}
let instruments = [];
let patterns = [];
// Pattern structure: array of rows; each row array is instruments +
// For each instrument row: note string or null, e.g. "C4" or "-"
function initPattern() {
let pattern = [];
for (let r=0; r<rowsPerPattern; r++) {
let row = [];
for (let i=0; i<instruments.length; i++) {
row.push("-"); // dash means no note
}
pattern.push(row);
}
return pattern;
}
function addInstrumentUI(inst) {
const container = document.getElementById('instruments');
let div = document.createElement('div');
div.dataset.id = inst.id;
div.innerHTML = `
<b>Instrument ${inst.id}</b>
Osc: <select class="oscType">
<option ${inst.oscType==='sine'?'selected':''}>sine</option>
<option ${inst.oscType==='square'?'selected':''}>square</option>
<option ${inst.oscType==='sawtooth'?'selected':''}>sawtooth</option>
<option ${inst.oscType==='triangle'?'selected':''}>triangle</option>
</select>
Volume: <input type="range" min="0" max="1" step="0.01" class="volume" value="${inst.volume}" style="width:100px">
Detune: <input type="range" min="-100" max="100" step="1" class="detune" value="${inst.detune}" style="width:100px">
Filter Freq: <input type="range" min="200" max="5000" step="10" class="filterFreq" value="${inst.filterFreq}" style="width:100px">
Noise: <input type="checkbox" class="noise" ${inst.noise ? 'checked' : ''}>
`;
container.appendChild(div);
div.querySelector('.oscType').addEventListener('change', e => {
inst.oscType = e.target.value;
});
div.querySelector('.volume').addEventListener('input', e => {
inst.volume = parseFloat(e.target.value);
});
div.querySelector('.detune').addEventListener('input', e => {
inst.detune = parseFloat(e.target.value);
});
div.querySelector('.filterFreq').addEventListener('input', e => {
inst.filterFreq = parseInt(e.target.value);
});
div.querySelector('.noise').addEventListener('change', e => {
inst.noise = e.target.checked;
});
}
function saveStateToHash() {
let state = {
bpm,
rowsPerPattern,
instruments,
patterns
};
let json = JSON.stringify(state);
location.hash = encodeURIComponent(json);
}
function loadStateFromHash() {
if (!location.hash) return false;
try {
let json = decodeURIComponent(location.hash.slice(1));
let state = JSON.parse(json);
bpm = state.bpm || 120;
rowsPerPattern = state.rowsPerPattern || 16;
instruments = state.instruments || [];
patterns = state.patterns || [];
document.getElementById("bpm").value = bpm;
document.getElementById("rowsPerPattern").value = rowsPerPattern;
const container = document.getElementById('instruments');
container.innerHTML = '';
instruments.forEach(i => addInstrumentUI(i));
rebuildTrackerGrid();
return true;
} catch(e) {
console.warn('Invalid hash');
return false;
}
}
function rebuildTrackerGrid() {
const tracker = document.getElementById('tracker');
tracker.innerHTML = '';
if (instruments.length === 0) {
tracker.textContent = "Add at least one instrument";
return;
}
if (patterns.length === 0) {
patterns.push(initPattern());
}
let pattern = patterns[currentPattern];
const patternDiv = document.createElement('div');
patternDiv.classList.add('pattern');
patternDiv.style.gridTemplateColumns = `repeat(${instruments.length+1}, 40px)`;
// header:
patternDiv.appendChild(document.createElement('div')); //empty corner
for (let i=0; i<instruments.length; i++) {
let hdr = document.createElement('div');
hdr.textContent = 'I' + instruments[i].id;
hdr.classList.add('cell');
patternDiv.appendChild(hdr);
}
for (let r=0; r<rowsPerPattern; r++) {
let rowMarker = document.createElement('div');
rowMarker.textContent = r.toString().padStart(2, '0');
rowMarker.classList.add('cell');
patternDiv.appendChild(rowMarker);
for (let i=0; i<instruments.length; i++) {
let cell = document.createElement('input');
cell.type = "text";
cell.maxLength = 3;
cell.size = 3;
cell.value = pattern[r][i] || "-";
cell.classList.add('cell');
cell.dataset.row = r;
cell.dataset.inst = i;
cell.addEventListener('focus', () => cell.classList.add('editing'));
cell.addEventListener('blur', () => {
cell.classList.remove('editing');
// validate note or dash
let val = cell.value.toUpperCase();
if ((val === '-') || /^[A-G]#?\d$/.test(val)) {
pattern[r][i] = val;
} else {
cell.value = pattern[r][i];
}
saveStateToHash();
});
patternDiv.appendChild(cell);
}
}
tracker.appendChild(patternDiv);
}
function playNote(inst, note, startTime) {
if (note === '-' || !note) return;
const freq = noteToFreq(note);
if (freq <= 0) return;
const ctx = audioCtx;
const oscType = inst.oscType;
const volume = inst.volume;
const detune = inst.detune;
const adsr = inst.adsr;
const filterFreq = inst.filterFreq;
const noise = inst.noise;
const now = startTime;
if (noise) {
// create noise source
const bufferSize = 2 * ctx.sampleRate;
const noiseBuffer = ctx.createBuffer(1, bufferSize, ctx.sampleRate);
let output = noiseBuffer.getChannelData(0);
for (let i = 0; i < bufferSize; i++) {
output[i] = Math.random()*2 -1;
}
const whiteNoise = ctx.createBufferSource();
whiteNoise.buffer = noiseBuffer;
const noiseFilter = ctx.createBiquadFilter();
noiseFilter.type = "lowpass";
noiseFilter.frequency.setValueAtTime(filterFreq, now);
const noiseGain = ctx.createGain();
noiseGain.gain.setValueAtTime(volume * 0.3, now);
whiteNoise.connect(noiseFilter);
noiseFilter.connect(noiseGain);
noiseGain.connect(ctx.destination);
whiteNoise.start(now);
whiteNoise.stop(now + adsr.attack + adsr.decay + adsr.release + 0.1);
return;
}
const osc = ctx.createOscillator();
osc.type = oscType;
osc.frequency.setValueAtTime(freq, now);
osc.detune.setValueAtTime(detune, now);
const gainNode = ctx.createGain();
const filter = ctx.createBiquadFilter();
filter.type = 'lowpass';
filter.frequency.setValueAtTime(filterFreq, now);
osc.connect(filter);
filter.connect(gainNode);
gainNode.connect(ctx.destination);
// ADSR envelope
gainNode.gain.setValueAtTime(0.0, now);
gainNode.gain.linearRampToValueAtTime(volume, now + adsr.attack);
gainNode.gain.linearRampToValueAtTime(volume * adsr.sustain, now + adsr.attack + adsr.decay);
// note length is determined externally - here simulate short note length = row duration
const noteLength = 60/bpm/4; // quarter of a beat ~ simple - could be adjusted
gainNode.gain.setValueAtTime(volume * adsr.sustain, now + noteLength);
gainNode.gain.linearRampToValueAtTime(0.0, now + noteLength + adsr.release);
osc.start(now);
osc.stop(now + noteLength + adsr.release + 0.1);
}
// Playback engine
function playStep() {
if (!isPlaying) return;
let pattern = patterns[currentPattern];
if (!pattern) return;
let row = pattern[currentRow];
let now = audioCtx.currentTime;
for (let i=0; i<instruments.length; i++) {
let note = row[i];
playNote(instruments[i], note, now);
}
currentRow++;
if (currentRow >= rowsPerPattern) {
if (loop) {
currentRow = 0;
} else {
stopPlayback();
return;
}
}
highlightRow(currentRow);
// schedule next step
let interval = (60/bpm)/4*1000;
timerId = setTimeout(playStep, interval);
}
function highlightRow(row) {
const tracker = document.getElementById('tracker');
const inputs = tracker.querySelectorAll('input.cell');
inputs.forEach(inp => {
inp.style.backgroundColor = '';
});
const patternDiv = tracker.querySelector('.pattern');
if (!patternDiv) return;
// skip header row (instruments + row numbers)
// first row has (instruments.length+1) columns
let base = (instruments.length + 1);
// rows start after first row (header)
// row 0 in pattern div starts at index = base (row 0 cells)
for(let c=0; c<instruments.length; c++) {
let idx = base * (row + 1) + 1 + c; // +1 for row number column
let cell = patternDiv.children[idx];
if (cell) cell.style.backgroundColor = "#0a5";
}
}
// Playback controls
function startPlayback() {
if (audioCtx.state === 'suspended') audioCtx.resume();
if (!patterns.length) return;
isPlaying = true;
document.getElementById('playPauseBtn').textContent = 'Pause';
currentRow = 0;
highlightRow(currentRow);
playStep();
}
function stopPlayback() {
isPlaying = false;
document.getElementById('playPauseBtn').textContent = 'Play';
currentRow = 0;
highlightRow(-1);
if (timerId) clearTimeout(timerId);
}
document.getElementById('playPauseBtn').addEventListener('click', () => {
if (isPlaying) stopPlayback();
else startPlayback();
});
document.getElementById('addInstrumentBtn').addEventListener('click', () => {
const id = instruments.length + 1;
let inst = createInstrument(id);
instruments.push(inst);
addInstrumentUI(inst);
// Update all existing patterns with new instrument slot ("-")
patterns.forEach(pattern => {
for (let r=0; r<rowsPerPattern; r++) {
pattern[r].push("-");
}
});
rebuildTrackerGrid();
saveStateToHash();
});
document.getElementById('addPatternBtn').addEventListener('click', () => {
patterns.push(initPattern());
currentPattern = patterns.length-1;
rebuildTrackerGrid();
saveStateToHash();
});
document.getElementById('bpm').addEventListener('change', e => {
bpm = parseInt(e.target.value) || 120;
saveStateToHash();
});
document.getElementById('rowsPerPattern').addEventListener('change', e => {
let val = parseInt(e.target.value) || 16;
if (val < 4) val = 4;
if (val > 64) val = 64;
rowsPerPattern = val;
// resize existing patterns
patterns.forEach(pattern => {
if (pattern.length > val) pattern.splice(val);
else while (pattern.length < val) {
let newRow = [];
for(let i=0; i<instruments.length; i++) newRow.push("-");
pattern.push(newRow);
}
});
rebuildTrackerGrid();
saveStateToHash();
});
document.getElementById('loopBtn').addEventListener('click', e => {
loop = !loop;
e.target.textContent = "Loop: " + (loop ? "ON" : "OFF");
saveStateToHash();
});
// Keyboard shortcuts
document.body.addEventListener('keydown', e => {
if (e.target.tagName === 'INPUT') return; // ignore if typing in inputs
if (e.code === 'Space') {
if (isPlaying) stopPlayback();
else startPlayback();
e.preventDefault();
} else if (e.code === 'ArrowRight') {
currentPattern++;
if (currentPattern >= patterns.length) currentPattern = 0;
rebuildTrackerGrid();
e.preventDefault();
} else if (e.code === 'ArrowLeft') {
currentPattern--;
if (currentPattern < 0) currentPattern = patterns.length-1;
rebuildTrackerGrid();
e.preventDefault();
} else if (e.code === 'ArrowDown') {
currentRow++;
if (currentRow >= rowsPerPattern) currentRow = 0;
highlightRow(currentRow);
e.preventDefault();
} else if (e.code === 'ArrowUp') {
currentRow--;
if (currentRow < 0) currentRow = rowsPerPattern-1;
highlightRow(currentRow);
e.preventDefault();
}
});
// On load - try to load state
if (!loadStateFromHash()) {
// no saved state, initialize one instrument and one pattern
let inst = createInstrument(1);
instruments.push(inst);
addInstrumentUI(inst);
patterns.push(initPattern());
rebuildTrackerGrid();
saveStateToHash();
}
</script>
</body>
</html>
How to use:
- Add instruments with "Add Instrument" button.
- Set oscillator type, volume, detune, filter frequency, and noise toggle per instrument.
- Add new patterns.
- Edit notes in the pattern grid by typing e.g.:
C4, D#4, A3 or - (dash) for no note.
- Use Space to play/pause.
- Arrows Left/Right to switch patterns.
- Arrows Up/Down to move current row highlight.
- Loop can be toggled.
- The entire song state is saved in the URL hash for sharing.
This is a foundation. Further improvements can be:
- More advanced envelope and timing.
- Better UI for patterns and instruments.
- Export WAV/OGG.
- Sample support or more oscillators per instrument.
- Effects like echo.
Let me know if you want me to expand!