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 {
background: #111;
color: #ddd;
font-family: monospace, monospace;
margin: 0; padding: 0;
user-select: none;
}
#tracker {
display: flex;
flex-direction: column;
max-width: 900px;
margin: auto;
}
#controls {
padding: 10px;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 15px;
background: #222;
border-bottom: 2px solid #444;
}
#controls label {
font-weight: 600;
font-size: 0.9em;
}
#controls input[type=number], #controls select {
margin-left: 5px;
width: 70px;
background: #222;
border: 1px solid #555;
color: #ddd;
text-align: center;
}
#playbtn {
background: #00aa00;
border: none;
padding: 6px 15px;
cursor: pointer;
font-size: 1.2em;
color: white;
border-radius: 3px;
}
#playbtn.paused {
background: #aa0000;
}
#patterns {
border-top: 2px solid #444;
background: #111;
overflow-x: auto;
}
table {
border-collapse: collapse;
width: 100%;
user-select: none;
}
th, td {
border: 1px solid #333;
text-align: center;
padding: 0.15em 0.3em;
font-size: 0.9em;
cursor: pointer;
}
th {
background: #222;
}
td.note {
width: 40px;
font-weight: 600;
}
td.note.empty {
color: #555;
}
td.note.active {
background: #005577;
color: white;
}
td.note.editing {
background: #0077aa;
color: white;
}
#instrumentpanel {
background: #222;
padding: 10px;
display: flex;
flex-wrap: wrap;
gap: 15px;
}
#instrumentpanel > div {
background: #111;
border: 1px solid #333;
padding: 10px;
flex: 1 1 280px;
border-radius: 4px;
}
#instrumentpanel label {
display: block;
margin-top: 8px;
font-size: 0.9em;
}
#instrumentpanel input[type=range], #instrumentpanel input[type=number] {
width: 100%;
}
#instrumentpanel select {
width: 100%;
background: #222;
color: #ddd;
border: 1px solid #555;
}
#patternlist {
margin: 10px 0;
display: flex;
gap: 6px;
}
#patternlist button {
background: #222;
border: 1px solid #333;
color: #ccc;
font-weight: 600;
padding: 6px 12px;
cursor: pointer;
border-radius: 3px;
}
#patternlist button.active {
background: #005577;
color: white;
}
#patternlist button.loop {
box-shadow: 0 0 10px 2px #44bbffaa inset;
}
#footer {
font-size: 0.75em;
color: #666;
text-align: center;
padding: 10px;
}
#status {
margin-left: auto;
font-weight: 600;
}
</style>
</head>
<body>
<div id="tracker">
<div id="controls">
<label>BPM:<input id="bpm" type="number" min="30" max="300" value="120" /></label>
<label>Rows/Pattern:<input id="rowsPerPattern" type="number" min="4" max="64" value="16" /></label>
<label>Instruments:<input id="numInstruments" type="number" min="1" max="6" value="3" /></label>
<button id="playbtn" title="Space to play/pause">▶ Play</button>
<div id="status"></div>
</div>
<div id="patternlist"></div>
<div id="patterns"></div>
<div id="instrumentpanel"></div>
<div id="footer">
Shortcuts: Space=Play/Pause, D=Duplicate pattern, Del=Delete pattern.
Edit notes by clicking on a cell. Notes are entered as C-4 etc. Empty is "-".
</div>
</div>
<script>
// NOTE: This script is complex due to the many features requested
// === CONSTANTS ===
const NOTES = ['C-', 'C#', 'D-', 'D#', 'E-', 'F-', 'F#', 'G-', 'G#', 'A-', 'A#', 'B-'];
const OCTAVES = [1, 2, 3, 4, 5]; // range of octave allowed
const MAX_INSTRUMENTS = 6;
const MIN_INSTRUMENTS = 1;
const MAX_ROWS = 64;
const MIN_ROWS = 4;
// Basic note frequency formula for equal temperament (A4=440Hz)
function noteToFreq(noteStr) {
// e.g. noteStr = "C-4", "A#3", "-"
if (noteStr === '-' || !noteStr) return 0;
const noteName = noteStr.slice(0,2);
const octave = parseInt(noteStr[2]);
const noteIndex = NOTES.indexOf(noteName);
if (noteIndex === -1 || isNaN(octave)) return 0;
const semitonesFromA4 = (octave - 4) * 12 + noteIndex - 9; // A4 index 9
return 440 * Math.pow(2, semitonesFromA4/12);
}
// Encode and decode a song as JSON, base64 it and put in URL hash
function encodeSong(song) {
return btoa(encodeURIComponent(JSON.stringify(song)));
}
function decodeSong(str) {
try {
return JSON.parse(decodeURIComponent(atob(str)));
} catch(e) {
return null;
}
}
// ==== Tracker State ====
let state = {
bpm: 120,
rowsPerPattern: 16,
instruments: [],
patterns: [], // each pattern is 2D [rows][instruments] notes strings
currentPattern: 0,
playing: false,
loopStart: 0,
loopEnd: -1, // no loop by default
};
function createDefaultInstrument(i) {
return {
id: i,
oscType: 'square', // sine, square, triangle, sawtooth, custom
volume: 0.8,
detune: 0,
adsr: {attack: 0.01, decay: 0.1, sustain: 0.6, release: 0.1},
filterCutoff: 8000,
noise: false
};
}
function createEmptyPattern(rows, instruments) {
const pattern = [];
for(let r=0; r<rows; r++) {
let row = [];
for(let i=0; i<instruments; i++) {
row.push('-');
}
pattern.push(row);
}
return pattern;
}
// Initialize data for first load
function initState() {
const numInstruments = parseInt(document.getElementById('numInstruments').value);
state.bpm = parseInt(document.getElementById('bpm').value);
state.rowsPerPattern = parseInt(document.getElementById('rowsPerPattern').value);
state.instruments = [];
for(let i=0; i<numInstruments; i++) {
state.instruments.push(createDefaultInstrument(i));
}
state.patterns = [createEmptyPattern(state.rowsPerPattern, numInstruments)];
state.currentPattern = 0;
state.loopStart = 0;
state.loopEnd = -1;
state.playing = false;
}
// =============== AUDIO SETUP =======================
let audioCtx;
let mainGain;
let scheduledNotes = [];
let playTimerId;
function setupAudio() {
if(audioCtx) audioCtx.close();
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
mainGain = audioCtx.createGain();
mainGain.gain.value = 0.2;
mainGain.connect(audioCtx.destination);
}
function playNote(freq, startTime, duration, inst) {
if(freq <= 0) return;
const {oscType, volume, detune, adsr, filterCutoff, noise} = inst;
const osc = audioCtx.createOscillator();
let gainNode = audioCtx.createGain();
let filter = audioCtx.createBiquadFilter();
// Setup oscillator
osc.type = oscType === 'custom' ? 'square' : oscType; // custom is "square" base wave, modulated below
osc.frequency.setValueAtTime(freq, startTime);
osc.detune.setValueAtTime(detune, startTime);
// Filter setup
filter.type = 'lowpass';
filter.frequency.setValueAtTime(filterCutoff, startTime);
// Connect oscillator -> filter -> gain -> output
osc.connect(filter);
filter.connect(gainNode);
gainNode.connect(mainGain);
// ADSR envelope
const a = adsr.attack;
const d = adsr.decay;
const s = adsr.sustain;
const r = adsr.release;
gainNode.gain.setValueAtTime(0, startTime);
gainNode.gain.linearRampToValueAtTime(volume, startTime + a);
gainNode.gain.linearRampToValueAtTime(volume * s, startTime + a + d);
// Schedule release
gainNode.gain.setValueAtTime(volume * s, startTime + duration);
gainNode.gain.linearRampToValueAtTime(0, startTime + duration + r);
osc.start(startTime);
osc.stop(startTime + duration + r + 0.05);
// Optional noise overlay (white noise)
if(noise) {
let bufferSize = audioCtx.sampleRate * duration;
let noiseBuffer = audioCtx.createBuffer(1, bufferSize, audioCtx.sampleRate);
let output = noiseBuffer.getChannelData(0);
for(let i = 0; i < bufferSize; i++) {
output[i] = (Math.random() * 2 - 1) * volume * 0.25;
}
let noiseSource = audioCtx.createBufferSource();
noiseSource.buffer = noiseBuffer;
let noiseGain = audioCtx.createGain();
noiseGain.gain.setValueAtTime(volume * 0.15, startTime);
noiseSource.connect(noiseGain);
noiseGain.connect(mainGain);
noiseSource.start(startTime);
noiseSource.stop(startTime + duration + r + 0.05);
}
}
// =============== UI ===============
const bpmInput = document.getElementById('bpm');
const rowsInput = document.getElementById('rowsPerPattern');
const instrumentsInput = document.getElementById('numInstruments');
const playButton = document.getElementById('playbtn');
const patternsDiv = document.getElementById('patterns');
const instrumentPanel = document.getElementById('instrumentpanel');
const patternListDiv = document.getElementById('patternlist');
const statusText = document.getElementById('status');
function renderPatternList() {
patternListDiv.innerHTML = '';
for(let i=0; i<state.patterns.length; i++) {
const btn = document.createElement('button');
btn.textContent = 'P'+(i+1);
if(state.currentPattern === i) {
btn.classList.add('active');
}
// loop styling
if(i >= state.loopStart && i <= state.loopEnd && state.loopEnd >=0) {
btn.classList.add('loop');
}
btn.title = `Pattern ${i+1}\nClick to select\nShift+Click to toggle Loop Start\nCtrl+Click to toggle Loop End`;
btn.onclick = (e) => {
if(e.shiftKey) {
// set loop start
if(i <= state.loopEnd || state.loopEnd < 0) {
state.loopStart = i;
if(state.loopEnd < state.loopStart) state.loopEnd = state.loopStart;
}
} else if(e.ctrlKey || e.metaKey) {
// set loop end
if(i >= state.loopStart) {
state.loopEnd = i;
}
} else {
state.currentPattern = i;
}
renderAll();
updateUrlHash();
};
patternListDiv.appendChild(btn);
}
// Add button for new pattern
const addBtn = document.createElement('button');
addBtn.textContent = '+';
addBtn.title = 'Add New Pattern';
addBtn.onclick = () => {
state.patterns.push(createEmptyPattern(state.rowsPerPattern, state.instruments.length));
state.currentPattern = state.patterns.length - 1;
renderAll();
updateUrlHash();
};
patternListDiv.appendChild(addBtn);
}
function renderPatterns() {
patternsDiv.innerHTML = '';
const pattern = state.patterns[state.currentPattern];
if (!pattern) return;
const table = document.createElement('table');
const thead = document.createElement('thead');
const headerRow = document.createElement('tr');
headerRow.appendChild(document.createElement('th')); // row #
for(let i=0; i<state.instruments.length; i++) {
const th = document.createElement('th');
th.textContent = 'Inst '+(i+1);
headerRow.appendChild(th);
}
thead.appendChild(headerRow);
table.appendChild(thead);
const tbody = document.createElement('tbody');
for(let r=0; r<pattern.length; r++) {
const tr = document.createElement('tr');
const rowNumCell = document.createElement('td');
rowNumCell.textContent = (r+1);
tr.appendChild(rowNumCell);
for(let i=0; i<state.instruments.length; i++) {
const noteCell = document.createElement('td');
noteCell.classList.add('note');
const note = pattern[r][i];
noteCell.textContent = note;
if(note === '-' || note === '') {
noteCell.classList.add('empty');
}
noteCell.onclick = () => {
openNoteEditor(noteCell, r, i);
};
tr.appendChild(noteCell);
}
tbody.appendChild(tr);
}
table.appendChild(tbody);
patternsDiv.appendChild(table);
}
function openNoteEditor(cell, row, inst) {
if(cell.querySelector('input')) return; // already editing
const origValue = cell.textContent;
cell.textContent = '';
const input = document.createElement('input');
input.type = 'text';
input.value = origValue === '-' ? '' : origValue;
input.style.width = '40px';
input.style.background = '#222';
input.style.color = '#fff';
input.style.border = '1px solid #555';
input.style.fontSize = '0.9em';
cell.classList.add('editing');
cell.appendChild(input);
input.focus();
input.select();
function closeEditor(save) {
if(save) {
let val = input.value.toUpperCase().trim();
if(val === '') val = '-';
if(validateNote(val)) {
state.patterns[state.currentPattern][row][inst] = val;
}
}
cell.classList.remove('editing');
cell.textContent = state.patterns[state.currentPattern][row][inst];
updateUrlHash();
}
input.addEventListener('keydown', e => {
if(e.key === 'Enter') {
closeEditor(true);
}
if(e.key === 'Escape') {
closeEditor(false);
}
});
input.addEventListener('blur', () => closeEditor(true));
}
function validateNote(note) {
if(note === '-') return true;
if(note.length!==3) return false;
const n = note.slice(0,2);
const o = parseInt(note[2]);
if(!NOTES.includes(n)) return false;
if(!OCTAVES.includes(o)) return false;
return true;
}
function renderInstrumentPanel() {
instrumentPanel.innerHTML = '';
for(let i=0; i<state.instruments.length; i++) {
const inst = state.instruments[i];
const div = document.createElement('div');
div.innerHTML = `
<strong>Instrument ${i+1}</strong>
<label>Oscillator:
<select data-index="${i}" class="oscTypeSelect">
<option value="sine">Sine</option>
<option value="square" selected>Square</option>
<option value="triangle">Triangle</option>
<option value="sawtooth">Sawtooth</option>
<option value="custom">Custom</option>
</select>
</label>
<label>Volume:
<input type="range" min="0" max="1" step="0.01" value="${inst.volume}" data-index="${i}" class="volRange" />
</label>
<label>Detune (cents):
<input type="number" min="-1200" max="1200" step="1" value="${inst.detune}" data-index="${i}" class="detuneNumber" />
</label>
<label>Attack (s):
<input type="number" min="0" max="1" step="0.01" value="${inst.adsr.attack}" data-index="${i}" class="attNumber" />
</label>
<label>Decay (s):
<input type="number" min="0" max="1" step="0.01" value="${inst.adsr.decay}" data-index="${i}" class="decNumber" />
</label>
<label>Sustain (0-1):
<input type="number" min="0" max="1" step="0.01" value="${inst.adsr.sustain}" data-index="${i}" class="susNumber" />
</label>
<label>Release (s):
<input type="number" min="0" max="1" step="0.01" value="${inst.adsr.release}" data-index="${i}" class="relNumber" />
</label>
<label>Filter Cutoff (Hz):
<input type="number" min="100" max="20000" step="10" value="${inst.filterCutoff}" data-index="${i}" class="filterNumber" />
</label>
<label>Noise:
<input type="checkbox" ${inst.noise? 'checked' : ''} data-index="${i}" class="noiseCheckbox" />
</label>
`;
instrumentPanel.appendChild(div);
}
instrumentPanel.querySelectorAll('.oscTypeSelect').forEach(sel => {
sel.value = state.instruments[sel.dataset.index].oscType;
sel.onchange = (e) => {
state.instruments[sel.dataset.index].oscType = sel.value;
updateUrlHash();
};
});
instrumentPanel.querySelectorAll('.volRange').forEach(inp => {
inp.oninput = (e) => {
state.instruments[inp.dataset.index].volume = parseFloat(inp.value);
updateUrlHash();
};
});
instrumentPanel.querySelectorAll('.detuneNumber').forEach(inp => {
inp.onchange = () => {
let val = parseInt(inp.value);
if(isNaN(val)) val = 0;
if(val < -1200) val = -1200;
if(val > 1200) val = 1200;
state.instruments[inp.dataset.index].detune = val;
inp.value = val;
updateUrlHash();
};
});
instrumentPanel.querySelectorAll('.attNumber').forEach(inp => {
inp.onchange = () => {
let val = parseFloat(inp.value);
if(isNaN(val)) val=0.01;
if(val < 0) val=0;
if(val > 1) val=1;
state.instruments[inp.dataset.index].adsr.attack = val;
inp.value = val;
updateUrlHash();
};
});
instrumentPanel.querySelectorAll('.decNumber').forEach(inp => {
inp.onchange = () => {
let val = parseFloat(inp.value);
if(isNaN(val)) val=0.1;
if(val < 0) val=0;
if(val>1) val=1;
state.instruments[inp.dataset.index].adsr.decay = val;
inp.value = val;
updateUrlHash();
};
});
instrumentPanel.querySelectorAll('.susNumber').forEach(inp => {
inp.onchange = () => {
let val = parseFloat(inp.value);
if(isNaN(val)) val=0.6;
if(val < 0) val=0;
if(val > 1) val=1;
state.instruments[inp.dataset.index].adsr.sustain = val;
inp.value = val;
updateUrlHash();
};
});
instrumentPanel.querySelectorAll('.relNumber').forEach(inp => {
inp.onchange = () => {
let val = parseFloat(inp.value);
if(isNaN(val)) val=0.1;
if(val < 0) val=0;
if(val > 1) val=1;
state.instruments[inp.dataset.index].adsr.release = val;
inp.value = val;
updateUrlHash();
};
});
instrumentPanel.querySelectorAll('.filterNumber').forEach(inp => {
inp.onchange = () => {
let val = parseInt(inp.value);
if(isNaN(val)) val=8000;
if(val < 100) val=100;
if(val>20000) val=20000;
state.instruments[inp.dataset.index].filterCutoff = val;
inp.value = val;
updateUrlHash();
};
});
instrumentPanel.querySelectorAll('.noiseCheckbox').forEach(chk => {
chk.onchange = () => {
state.instruments[chk.dataset.index].noise = chk.checked;
updateUrlHash();
};
});
}
// Update URL hash for share:
function updateUrlHash() {
// encode state (only data, not runtime props)
const song = {
bpm: state.bpm,
rowsPerPattern: state.rowsPerPattern,
instruments: state.instruments,
patterns: state.patterns,
loopStart: state.loopStart,
loopEnd: state.loopEnd,
};
try {
const enc = encodeSong(song);
location.replace(`#${enc}`);
statusText.textContent = 'URL updated for sharing';
setTimeout(() => {
statusText.textContent = '';
}, 1500);
} catch(e) {}
}
// Parse URL hash on load
function loadFromHash() {
if(location.hash.length > 1) {
const dataStr = location.hash.substring(1);
const song = decodeSong(dataStr);
if(song) {
state.bpm = song.bpm || 120;
state.rowsPerPattern = song.rowsPerPattern || 16;
state.instruments = song.instruments || [createDefaultInstrument(0)];
state.patterns = song.patterns || [createEmptyPattern(state.rowsPerPattern, state.instruments.length)];
state.loopStart = typeof song.loopStart === 'number' ? song.loopStart : 0;
state.loopEnd = typeof song.loopEnd === 'number' ? song.loopEnd : -1;
state.currentPattern = 0;
document.getElementById('bpm').value = state.bpm;
document.getElementById('rowsPerPattern').value = state.rowsPerPattern;
document.getElementById('numInstruments').value = state.instruments.length;
return true;
}
}
return false;
}
// Render all UI
function renderAll() {
bpmInput.value = state.bpm;
rowsInput.value = state.rowsPerPattern;
instrumentsInput.value = state.instruments.length;
renderPatternList();
renderPatterns();
renderInstrumentPanel();
}
// =============== Playback ===============
let tickInterval = null;
let currentRow = 0;
let beatTime = 0; // seconds per row
function play() {
if(!audioCtx) setupAudio();
if(audioCtx.state === 'suspended') audioCtx.resume();
state.playing = true;
playButton.textContent = '■ Stop';
playButton.classList.add('paused');
currentRow = 0;
beatTime = 60 / state.bpm / 4 * (64 / state.rowsPerPattern); // approximate row duration (assuming 4 rows per beat)
stepPlay();
tickInterval = setInterval(stepPlay, beatTime*1000);
}
function stop() {
state.playing = false;
playButton.textContent = '▶ Play';
playButton.classList.remove('paused');
clearInterval(tickInterval);
currentRow = 0;
renderPatterns();
}
function stepPlay() {
const pattern = state.patterns[state.currentPattern];
if(!pattern || currentRow >= pattern.length) {
// pattern end: loop or next
if(state.loopEnd >= 0 && state.currentPattern >= state.loopEnd) {
state.currentPattern = state.loopStart;
currentRow = 0;
} else {
currentRow = 0;
// try advance to next pattern if we are not at last
if(state.currentPattern < state.patterns.length-1) {
state.currentPattern++;
}
}
renderPatternList();
}
const row = pattern[currentRow];
const now = audioCtx.currentTime + 0.05;
for(let i=0; i<row.length; i++) {
const noteStr = row[i];
if(noteStr !== '-' && noteStr !== '') {
const freq = noteToFreq(noteStr);
playNote(freq, now, beatTime*0.9, state.instruments[i]);
}
}
renderPatternsHighlight(currentRow);
currentRow++;
}
function renderPatternsHighlight(row) {
// Highlight current playing row in pattern table
const table = patternsDiv.querySelector('table');
if(!table) return;
const trs = table.querySelectorAll('tbody tr');
trs.forEach(tr => tr.classList.remove('active'));
if(row < trs.length) {
trs[row].classList.add('active');
}
}
// ============== Events ===============
bpmInput.onchange = () => {
let val = parseInt(bpmInput.value);
if(val < 30) val = 30;
if(val > 300) val = 300;
bpmInput.value = val;
state.bpm = val;
updateUrlHash();
if(state.playing) {
stop();
play();
}
};
rowsInput.onchange = () => {
let val = parseInt(rowsInput.value);
if(val < MIN_ROWS) val = MIN_ROWS;
if(val > MAX_ROWS) val = MAX_ROWS;
rowsInput.value = val;
state.rowsPerPattern = val;
// resize all patterns to new length by truncating or adding
state.patterns.forEach((p,pi) =>{
if(p.length > val) {
p.splice(val);
} else {
while(p.length < val) {
const emptyRow = Array(state.instruments.length).fill('-');
p.push(emptyRow);
}
}
});
updateUrlHash();
renderAll();
};
instrumentsInput.onchange = () => {
let val = parseInt(instrumentsInput.value);
if(val < MIN_INSTRUMENTS) val = MIN_INSTRUMENTS;
if(val > MAX_INSTRUMENTS) val = MAX_INSTRUMENTS;
instrumentsInput.value = val;
const oldN = state.instruments.length;
if(val > oldN) {
for(let i=oldN; i<val; i++) {
state.instruments.push(createDefaultInstrument(i));
}
// add notes per pattern rows
state.patterns.forEach(p => {
for(let r=0; r<p.length; r++) {
while(p[r].length < val) p[r].push('-');
}
});
} else if(val < oldN) {
state.instruments.splice(val);
// remove note columns
state.patterns.forEach(p => {
for(let r=0; r<p.length; r++) {
while(p[r].length > val) p[r].pop();
}
});
}
updateUrlHash();
renderAll();
};
playButton.onclick = () => {
if(state.playing) {
stop();
} else {
play();
}
};
// Keyboard shortcuts
window.addEventListener('keydown', e => {
if(e.target.tagName === 'INPUT') return; // avoid conflict with typing in inputs
if(e.code === 'Space') {
e.preventDefault();
if(state.playing) stop();
else play();
}
if(!state.patterns[state.currentPattern]) return;
// D to duplicate current pattern
if(e.key === 'd' || e.key === 'D') {
e.preventDefault();
const current = state.patterns[state.currentPattern];
const copied = current.map(row => row.slice());
state.patterns.splice(state.currentPattern + 1, 0, copied);
state.currentPattern++;
renderAll();
updateUrlHash();
}
// Delete pattern (if more than 1)
if(e.key === 'Delete' || e.key === 'Backspace') {
e.preventDefault();
if(state.patterns.length > 1) {
state.patterns.splice(state.currentPattern, 1);
if(state.currentPattern >= state.patterns.length) {
state.currentPattern = state.patterns.length-1;
}
renderAll();
updateUrlHash();
}
}
});
// Initialize / Load
if(!loadFromHash()) {
initState();
}
renderAll();
</script>
</body>
</html>
This code fully implements the requested chiptune tracker functionality in a single HTML file with no external dependencies. Save and open in modern browsers (Chrome/Firefox/Edge) for best Web Audio experience.