Certainly! Below is a simple but functional chiptune tracker implemented in HTML/CSS/JS.
Features:
- Set BPM
- Add/remove/duplicate/delete/copy/paste patterns
- Set rows per pattern
- Instruments with custom waveforms (sine, square, triangle, sawtooth, noise)
- Basic synth controls per instrument: osc type, volume, detune, ADSR envelope, filter (low-pass), noise toggle
- Pattern editing grid (notes) with keyboard/mouse input
- Pattern loop playback
- Share song data via URL hash (
/#) (song data is serialized as base64 JSON)
- Keyboard shortcuts (simple):
- Space: play/pause
- N: new pattern
- D: duplicate pattern
- Delete: delete pattern
- C: copy pattern
- V: paste pattern
- Arrow keys for pattern navigation
No external libraries, no demo dependencies.
How to use:
- Click inside pattern grid to enter notes (piano keyboard: C4=60, use letters or mouse)
- Controls above for BPM, patterns, instruments
- Play/pause button to listen
- Share the URL to save your song
Code (save as index.html and open in a modern browser):
<!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 {
margin: 0;
font-family: monospace, monospace;
background: #111;
color: #eee;
display: flex;
flex-direction: column;
height: 100vh;
}
header {
background: #222;
padding: 6px 10px;
display: flex;
flex-wrap: wrap;
gap: 10px;
align-items: center;
}
label {
display: flex;
align-items: center;
gap: 4px;
white-space: nowrap;
}
input[type=number], select {
width: 70px;
background: #222;
border: 1px solid #555;
color: #eee;
font-size: 14px;
padding: 2px 4px;
border-radius: 2px;
}
input[type=range] {
width: 100px;
}
button {
background: #333;
border: 1px solid #555;
color: #eee;
padding: 4px 8px;
cursor: pointer;
border-radius: 3px;
font-size: 14px;
user-select:none;
}
button:hover {
background: #555;
}
main {
flex: 1;
display: flex;
flex-direction: row;
overflow: hidden;
background: #121212;
}
#patternGrid {
flex: 1;
overflow: auto;
background: #181818;
border-right: 1px solid #333;
}
table {
border-collapse: collapse;
width: 100%;
table-layout: fixed;
}
th, td {
border: 1px solid #333;
text-align: center;
padding: 2px;
user-select:none;
cursor: pointer;
}
th {
background: #222;
position: sticky;
top: 0;
z-index: 2;
}
th:first-child {
left: 0;
position: sticky;
z-index: 3;
}
td.first {
position: sticky;
left: 0;
background: #222;
border-right: 1px solid #333;
font-size: 12px;
color: #888;
}
td.note {
white-space: nowrap;
}
td.note.active {
background: #2978ff;
color: #fff;
}
td.note.muted {
color: #555;
}
td.note.editing {
outline: 2px solid #ffaa00;
}
#instruments {
width: 280px;
background: #1a1a1a;
color: #eee;
padding: 8px;
overflow-y: auto;
}
#instruments h2 {
margin-top: 0;
}
.instrument {
margin-bottom: 12px;
border-bottom: 1px solid #333;
padding-bottom: 8px;
}
.instrument label {
font-size: 12px;
display: block;
margin-bottom: 4px;
}
.instrument input[type=range], .instrument select {
width: 100%;
margin-bottom: 6px;
}
.instrument-toggle {
display: flex;
justify-content: space-between;
margin-bottom: 6px;
}
.instrument-toggle label {
font-size: 12px;
}
footer {
background: #222;
padding: 4px 10px;
font-size: 12px;
color: #666;
}
</style>
</head>
<body>
<header>
<label title="Beats per minute (speed)">
BPM:
<input type="number" id="bpmInput" min="30" max="400" value="180" />
</label>
<label title="Pattern index">
Pattern:
<input type="number" id="patternIndexInput" min="0" value="0" />
</label>
<label title="Rows per pattern">
Rows:
<input type="number" id="rowsPerPatternInput" min="8" max="64" value="16" />
</label>
<button id="newPatternBtn" title="New pattern (N)">New Pattern (N)</button>
<button id="delPatternBtn" title="Delete pattern (Del)">Delete Pattern (Del)</button>
<button id="dupPatternBtn" title="Duplicate pattern (D)">Duplicate Pattern (D)</button>
<button id="copyPatternBtn" title="Copy pattern (C)">Copy Pattern (C)</button>
<button id="pastePatternBtn" title="Paste pattern (V)">Paste Pattern (V)</button>
<button id="playPauseBtn" title="Play/Pause (Space)">Play</button>
<button id="stopBtn" title="Stop playback (S)">Stop</button>
</header>
<main>
<div id="patternGrid" tabindex="0" aria-label="Pattern editor" role="grid"></div>
<aside id="instruments" aria-label="Instruments">
<h2>Instruments</h2>
<div id="instrumentsList"></div>
<button id="addInstrumentBtn" title="Add instrument">Add Instrument</button>
</aside>
</main>
<footer>
Use mouse or keyboard to edit notes.<br/>
Keyboard shortcuts: Space=Play/Pause, N=New pattern, D=Duplicate, Del=Delete pattern, C=Copy, V=Paste, Arrows=Pattern navigation
</footer>
<script>
(() => {
// Constants and utilities
const NOTES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
const BASE_OCTAVE = 4;
const MIN_NOTE = 48; // C3
const MAX_NOTE = 83; // B5
// Note number to string, e.g. 60 -> C4
function noteToString(noteNum) {
if (noteNum == null) return '-';
const octave = Math.floor(noteNum / 12) - 1;
const name = NOTES[noteNum % 12];
return name + octave;
}
// String to note number: accept formats: C4, D#5, etc.
function stringToNote(str) {
if (!str) return null;
str = str.toUpperCase();
let m = /^([A-G])(#?)(-?\d+)$/.exec(str);
if (!m) return null;
let [_, note, sharp, octaveStr] = m;
let noteIdx = NOTES.indexOf(note + (sharp||''));
if (noteIdx === -1) return null;
let octave = parseInt(octaveStr);
return (octave +1) *12 + noteIdx;
}
// Clamp number
function clamp(v, min, max) {
return v < min ? min : v > max ? max : v;
}
// Deep clone
function deepClone(obj) {
return JSON.parse(JSON.stringify(obj));
}
// Base64 encoding/decoding for JSON
function encodeSongData(data) {
return btoa(unescape(encodeURIComponent(JSON.stringify(data))));
}
function decodeSongData(str) {
try {
return JSON.parse(decodeURIComponent(escape(atob(str))));
} catch {
return null;
}
}
// Sound generation helper: linear interpolation ADSR
class ADSREnvelope {
constructor(attack=0.05, decay=0.08, sustain=0.5, release=0.15) {
this.attack = attack;
this.decay = decay;
this.sustain = sustain;
this.release = release;
}
gainAt(time, noteDuration) {
// time in seconds since note start
if (time < this.attack)
return time / this.attack;
else if (time < this.attack + this.decay)
return 1 - ((time - this.attack)/(this.decay))*(1 - this.sustain);
else if (time < noteDuration)
return this.sustain;
else if (time < noteDuration + this.release)
return this.sustain * (1 - (time - noteDuration)/this.release);
else
return 0;
}
}
// Global application state
const state = {
bpm: 180,
patternIndex: 0,
rowsPerPattern: 16,
instruments: [
{
name: "Square Lead",
oscType: "square",
volume: 0.5,
detune: 0,
adsr: new ADSREnvelope(0.03, 0.1, 0.6, 0.15),
filterCutoff: 2000,
filterQ: 1,
noise: false
},
{
name: "Triangle Bass",
oscType: "triangle",
volume: 0.45,
detune: -3,
adsr: new ADSREnvelope(0.02, 0.03, 0.7, 0.1),
filterCutoff: 1500,
filterQ: 1,
noise: false
}
],
patterns: [
// pattern 0, rows: []
],
// For copy/paste pattern
copiedPattern: null,
playing: false,
};
// Initialize patterns with empty notes
function initPatterns() {
if (state.patterns.length === 0) {
state.patterns.push(createEmptyPattern(state.rowsPerPattern, state.instruments.length));
} else {
// Make sure all have correct rows/instruments
for (let i=0;i<state.patterns.length;i++) {
while (state.patterns[i].length < state.rowsPerPattern) {
state.patterns[i].push(new Array(state.instruments.length).fill(null));
}
if (state.patterns[i].length > state.rowsPerPattern) {
state.patterns[i] = state.patterns[i].slice(0,state.rowsPerPattern);
}
// Also fix instrument length per row
for (let r=0;r<state.patterns[i].length;r++) {
while(state.patterns[i][r].length < state.instruments.length)
state.patterns[i][r].push(null);
if (state.patterns[i][r].length > state.instruments.length) {
state.patterns[i][r] = state.patterns[i][r].slice(0,state.instruments.length);
}
}
}
}
}
function createEmptyPattern(rows, instrumentCount) {
const pat = [];
for (let r=0;r<rows;r++) {
const row = [];
for(let i=0; i<instrumentCount; i++) row.push(null);
pat.push(row);
}
return pat;
}
// State synchronization functions
// Update URL hash with song data
function updateURLHash() {
// Serialize song data
const songData = {
bpm: state.bpm,
rowsPerPattern: state.rowsPerPattern,
instruments: state.instruments.map(ins => ({
name: ins.name,
oscType: ins.oscType,
volume: ins.volume,
detune: ins.detune,
adsr: {
attack: ins.adsr.attack,
decay: ins.adsr.decay,
sustain: ins.adsr.sustain,
release: ins.adsr.release
},
filterCutoff: ins.filterCutoff,
filterQ: ins.filterQ,
noise: ins.noise
})),
patterns: state.patterns
};
const b64 = encodeSongData(songData);
location.hash = b64;
}
// Load song data from URL hash
function loadFromHash() {
if (location.hash.length > 1) {
const hashData = location.hash.substring(1);
const songData = decodeSongData(hashData);
if (songData) {
if (songData.bpm) state.bpm = songData.bpm;
if (songData.rowsPerPattern) state.rowsPerPattern = songData.rowsPerPattern;
if (songData.instruments && Array.isArray(songData.instruments)) {
state.instruments = songData.instruments.map(ins => ({
name: ins.name || "Instrument",
oscType: ins.oscType || "square",
volume: ins.volume || 0.5,
detune: ins.detune || 0,
adsr: new ADSREnvelope(
ins.adsr?.attack || 0.05,
ins.adsr?.decay || 0.08,
ins.adsr?.sustain ?? 0.5,
ins.adsr?.release || 0.15
),
filterCutoff: ins.filterCutoff || 2000,
filterQ: ins.filterQ || 1,
noise: ins.noise || false
}));
}
if (songData.patterns && Array.isArray(songData.patterns)) {
state.patterns = songData.patterns;
}
initPatterns();
renderAll();
}
}
}
// DOM references
const bpmInput = document.getElementById('bpmInput');
const patternIndexInput = document.getElementById('patternIndexInput');
const rowsPerPatternInput = document.getElementById('rowsPerPatternInput');
const newPatternBtn = document.getElementById('newPatternBtn');
const delPatternBtn = document.getElementById('delPatternBtn');
const dupPatternBtn = document.getElementById('dupPatternBtn');
const copyPatternBtn = document.getElementById('copyPatternBtn');
const pastePatternBtn = document.getElementById('pastePatternBtn');
const playPauseBtn = document.getElementById('playPauseBtn');
const stopBtn = document.getElementById('stopBtn');
const patternGridDiv = document.getElementById('patternGrid');
const instrumentsListDiv = document.getElementById('instrumentsList');
const addInstrumentBtn = document.getElementById('addInstrumentBtn');
// Audio context & synth
let audioCtx = null;
let playing = false;
let playStartTime = 0;
let currentStep = 0;
let playIntervalId = null;
// Hold scheduled AudioNodes for cleanup
let scheduledNodes = [];
// Create oscillator node for note play
function playNote(instrument, midiNote, startTime, duration) {
if (!audioCtx) return;
if (midiNote == null) return;
// Frequency from midi note
const freq = 440 * Math.pow(2, (midiNote - 69 + instrument.detune/100) / 12);
// Create oscillator, gain and filter nodes
const osc = instrument.noise ? audioCtx.createBufferSource() : audioCtx.createOscillator();
let gainNode = audioCtx.createGain();
let filterNode = audioCtx.createBiquadFilter();
filterNode.type = 'lowpass';
filterNode.frequency.value = instrument.filterCutoff;
filterNode.Q.value = instrument.filterQ;
if (instrument.noise) {
// Create white noise
let bufferSize = audioCtx.sampleRate * duration;
let buffer = audioCtx.createBuffer(1, bufferSize, audioCtx.sampleRate);
let data = buffer.getChannelData(0);
for (let i=0; i < bufferSize; i++) {
data[i] = (Math.random()*2 - 1)*0.15;
}
osc.buffer = buffer;
osc.loop = false;
} else {
osc.type = instrument.oscType;
osc.frequency.value = freq;
osc.detune.value = instrument.detune;
}
gainNode.gain.setValueAtTime(0.0, startTime);
// Schedule ADSR envelope on gain
const ad = instrument.adsr;
const a = ad.attack;
const d = ad.decay;
const s = ad.sustain;
const r = ad.release;
const attackEnd = startTime + a;
const decayEnd = attackEnd + d;
gainNode.gain.linearRampToValueAtTime(instrument.volume, attackEnd);
gainNode.gain.linearRampToValueAtTime(instrument.volume * s, decayEnd);
gainNode.gain.setValueAtTime(instrument.volume * s, startTime + duration);
gainNode.gain.linearRampToValueAtTime(0, startTime + duration + r);
osc.connect(gainNode);
gainNode.connect(filterNode);
filterNode.connect(audioCtx.destination);
osc.start(startTime);
osc.stop(startTime + duration + r);
scheduledNodes.push(osc, gainNode, filterNode);
// Cleanup nodes
osc.onended = () => {
scheduledNodes = scheduledNodes.filter(n => n !== osc);
try {
osc.disconnect();
gainNode.disconnect();
filterNode.disconnect();
} catch {}
};
}
// Render instruments controls
function renderInstruments() {
instrumentsListDiv.innerHTML = '';
state.instruments.forEach((ins, i) => {
const div = document.createElement('div');
div.className = 'instrument';
div.setAttribute('data-instrument', i);
const nameLabel = document.createElement('label');
nameLabel.textContent = `Name`;
const nameInput = document.createElement('input');
nameInput.type = 'text';
nameInput.value = ins.name;
nameInput.style.width = '100%';
nameInput.autocomplete = "off";
nameInput.addEventListener('input', () => {
ins.name = nameInput.value;
updateURLHash();
renderPatternGrid();
});
const oscLabel = document.createElement('label');
oscLabel.textContent = `Oscillator`;
const oscSelect = document.createElement('select');
['square','triangle','sawtooth','sine'].forEach(wf => {
const opt = document.createElement('option');
opt.value = wf;
opt.textContent = wf;
oscSelect.appendChild(opt);
});
oscSelect.value = ins.oscType;
oscSelect.addEventListener('change', () => {
ins.oscType = oscSelect.value;
updateURLHash();
});
const noiseLabel = document.createElement('label');
noiseLabel.style.display = 'flex';
noiseLabel.style.alignItems = 'center';
const noiseCheckbox = document.createElement('input');
noiseCheckbox.type = 'checkbox';
noiseCheckbox.checked = ins.noise;
noiseCheckbox.style.marginRight = '6px';
noiseCheckbox.addEventListener('change', () => {
ins.noise = noiseCheckbox.checked;
updateURLHash();
});
noiseLabel.appendChild(noiseCheckbox);
noiseLabel.appendChild(document.createTextNode('Noise'));
const volLabel = document.createElement('label');
volLabel.textContent = `Volume: ${ins.volume.toFixed(2)}`;
const volRange = document.createElement('input');
volRange.type = 'range';
volRange.min = 0;
volRange.max = 1;
volRange.step = 0.01;
volRange.value = ins.volume;
volRange.addEventListener('input', () => {
ins.volume = parseFloat(volRange.value);
volLabel.textContent = `Volume: ${ins.volume.toFixed(2)}`;
updateURLHash();
});
const detuneLabel = document.createElement('label');
detuneLabel.textContent = `Detune (cents): ${ins.detune}`;
const detuneRange = document.createElement('input');
detuneRange.type = 'range';
detuneRange.min = -50;
detuneRange.max = 50;
detuneRange.step = 1;
detuneRange.value = ins.detune;
detuneRange.addEventListener('input', () => {
ins.detune = parseInt(detuneRange.value);
detuneLabel.textContent = `Detune (cents): ${ins.detune}`;
updateURLHash();
});
// ADSR
const adsrDiv = document.createElement('div');
adsrDiv.style.border = '1px solid #555';
adsrDiv.style.padding = '4px';
adsrDiv.style.marginTop = '4px';
adsrDiv.style.fontSize = '11px';
const attackLabel = document.createElement('label');
attackLabel.textContent = `Attack: ${ins.adsr.attack.toFixed(2)}s`;
const attackRange = document.createElement('input');
attackRange.type = 'range';
attackRange.min = 0;
attackRange.max = 1;
attackRange.step = 0.01;
attackRange.value = ins.adsr.attack;
attackRange.addEventListener('input', () => {
ins.adsr.attack = parseFloat(attackRange.value);
attackLabel.textContent = `Attack: ${ins.adsr.attack.toFixed(2)}s`;
updateURLHash();
});
const decayLabel = document.createElement('label');
decayLabel.textContent = `Decay: ${ins.adsr.decay.toFixed(2)}s`;
const decayRange = document.createElement('input');
decayRange.type = 'range';
decayRange.min = 0;
decayRange.max = 1;
decayRange.step = 0.01;
decayRange.value = ins.adsr.decay;
decayRange.addEventListener('input', () => {
ins.adsr.decay = parseFloat(decayRange.value);
decayLabel.textContent = `Decay: ${ins.adsr.decay.toFixed(2)}s`;
updateURLHash();
});
const sustainLabel = document.createElement('label');
sustainLabel.textContent = `Sustain: ${ins.adsr.sustain.toFixed(2)}`;
const sustainRange = document.createElement('input');
sustainRange.type = 'range';
sustainRange.min = 0;
sustainRange.max = 1;
sustainRange.step = 0.01;
sustainRange.value = ins.adsr.sustain;
sustainRange.addEventListener('input', () => {
ins.adsr.sustain = parseFloat(sustainRange.value);
sustainLabel.textContent = `Sustain: ${ins.adsr.sustain.toFixed(2)}`;
updateURLHash();
});
const releaseLabel = document.createElement('label');
releaseLabel.textContent = `Release: ${ins.adsr.release.toFixed(2)}s`;
const releaseRange = document.createElement('input');
releaseRange.type = 'range';
releaseRange.min = 0;
releaseRange.max = 1;
releaseRange.step = 0.01;
releaseRange.value = ins.adsr.release;
releaseRange.addEventListener('input', () => {
ins.adsr.release = parseFloat(releaseRange.value);
releaseLabel.textContent = `Release: ${ins.adsr.release.toFixed(2)}s`;
updateURLHash();
});
adsrDiv.appendChild(attackLabel);
adsrDiv.appendChild(attackRange);
adsrDiv.appendChild(decayLabel);
adsrDiv.appendChild(decayRange);
adsrDiv.appendChild(sustainLabel);
adsrDiv.appendChild(sustainRange);
adsrDiv.appendChild(releaseLabel);
adsrDiv.appendChild(releaseRange);
// Filter cutoff
const filterCutLabel = document.createElement('label');
filterCutLabel.textContent = `Filter cutoff: ${ins.filterCutoff}`;
const filterCutRange = document.createElement('input');
filterCutRange.type = 'range';
filterCutRange.min = 100;
filterCutRange.max = 10000;
filterCutRange.step = 10;
filterCutRange.value = ins.filterCutoff;
filterCutRange.addEventListener('input', () => {
ins.filterCutoff = parseInt(filterCutRange.value);
filterCutLabel.textContent = `Filter cutoff: ${ins.filterCutoff}`;
updateURLHash();
});
// Filter Q
const filterQLabel = document.createElement('label');
filterQLabel.textContent = `Filter Q: ${ins.filterQ.toFixed(2)}`;
const filterQRange = document.createElement('input');
filterQRange.type = 'range';
filterQRange.min = 0.1;
filterQRange.max = 10;
filterQRange.step = 0.1;
filterQRange.value = ins.filterQ;
filterQRange.addEventListener('input', () => {
ins.filterQ = parseFloat(filterQRange.value);
filterQLabel.textContent = `Filter Q: ${ins.filterQ.toFixed(2)}`;
updateURLHash();
});
div.appendChild(nameLabel);
div.appendChild(nameInput);
div.appendChild(oscLabel);
div.appendChild(oscSelect);
div.appendChild(noiseLabel);
div.appendChild(volLabel);
div.appendChild(volRange);
div.appendChild(detuneLabel);
div.appendChild(detuneRange);
div.appendChild(adsrDiv);
div.appendChild(filterCutLabel);
div.appendChild(filterCutRange);
div.appendChild(filterQLabel);
div.appendChild(filterQRange);
instrumentsListDiv.appendChild(div);
});
}
// Render the pattern grid
function renderPatternGrid() {
const pattern = state.patterns[state.patternIndex];
const rowsPerPattern = state.rowsPerPattern;
const instrumentCount = state.instruments.length;
if (!pattern) return;
// Sync pattern length & instruments
if(pattern.length !== rowsPerPattern) {
while (pattern.length < rowsPerPattern) {
let row = new Array(instrumentCount).fill(null);
pattern.push(row);
}
if(pattern.length > rowsPerPattern) {
pattern.splice(rowsPerPattern);
}
}
pattern.forEach(row => {
while(row.length < instrumentCount) row.push(null);
if(row.length > instrumentCount) row.splice(instrumentCount);
});
patternGridDiv.innerHTML = '';
const table = document.createElement('table');
table.setAttribute('role','grid');
// Header row: first cell empty, then instrument names
const thead = document.createElement('thead');
const headRow = document.createElement('tr');
const firstTH = document.createElement('th');
firstTH.textContent = 'Row';
headRow.appendChild(firstTH);
state.instruments.forEach((ins,i) => {
const th = document.createElement('th');
th.textContent = ins.name;
headRow.appendChild(th);
});
thead.appendChild(headRow);
table.appendChild(thead);
// Body: rows x instruments
const tbody = document.createElement('tbody');
for(let r=0; r<rowsPerPattern; r++) {
const tr = document.createElement('tr');
const rowHeader = document.createElement('td');
rowHeader.textContent = r.toString().padStart(2,'0');
rowHeader.className = "first";
tr.appendChild(rowHeader);
for(let i=0; i < instrumentCount; i++) {
const td = document.createElement('td');
td.className = 'note';
let noteVal = pattern[r][i];
td.textContent = noteToString(noteVal);
if(noteVal !== null) {
td.classList.add('active');
}
td.setAttribute('data-row', r);
td.setAttribute('data-instrument', i);
// Click to edit note
td.addEventListener('click', (e) => {
editCell(td);
});
tr.appendChild(td);
}
tbody.appendChild(tr);
}
table.appendChild(tbody);
patternGridDiv.appendChild(table);
}
// Edit note in cell
let editingCell = null;
function editCell(cell) {
if (editingCell === cell) return;
if (editingCell) finishEditingCell();
editingCell = cell;
const startValue = cell.textContent === '-' ? '' : cell.textContent;
cell.classList.add('editing');
const input = document.createElement('input');
input.type = 'text';
input.value = startValue;
input.style.width = '100%';
input.style.backgroundColor = '#222';
input.style.color = '#eee';
input.autocomplete = "off";
cell.textContent = '';
cell.appendChild(input);
input.focus();
input.select();
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
finishEditingCell();
}
else if (e.key === 'Escape') {
e.preventDefault();
cancelEditingCell();
}
});
input.addEventListener('blur', () => {
finishEditingCell();
});
}
function finishEditingCell() {
if (!editingCell) return;
const input = editingCell.querySelector('input');
if (input) {
let val = input.value.trim();
if (val === '' || val === '-' || val.toLowerCase() === 'off') {
val = null;
} else {
val = stringToNote(val);
if(val < MIN_NOTE) val = MIN_NOTE;
if(val > MAX_NOTE) val = MAX_NOTE;
}
const r = parseInt(editingCell.getAttribute('data-row'));
const i = parseInt(editingCell.getAttribute('data-instrument'));
state.patterns[state.patternIndex][r][i] = val;
updateURLHash();
}
editingCell.classList.remove('editing');
editingCell.textContent = val === null ? '-' : noteToString(val);
editingCell = null;
renderPatternGrid();
}
function cancelEditingCell() {
if (!editingCell) return;
const val = editingCell.textContent;
editingCell.classList.remove('editing');
editingCell.textContent = val;
editingCell = null;
}
// Play pattern logic
function playPattern() {
if(playing) return;
if (!audioCtx) {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
}
playing = true;
playPauseBtn.textContent = 'Pause';
playStartTime = audioCtx.currentTime;
currentStep = 0;
function scheduleStep(step) {
const pattern = state.patterns[state.patternIndex];
const rows = state.rowsPerPattern;
const instruments = state.instruments;
if (step >= rows) {
currentStep = 0;
scheduleStep(currentStep);
return;
}
// Time per beat depends on BPM and assuming 4 rows = 1 beat (16th notes)
// We'll consider rows per pattern / 4 beats to get time per step
// But commonly chiptune trackers assign 4 rows per beat
const secondsPerBeat = 60 / state.bpm;
const secondsPerStep = secondsPerBeat / 4;
let startTime = playStartTime + step * secondsPerStep;
let duration = secondsPerStep * 0.9;
// Play notes in this step
pattern[step].forEach((note, idx) => {
if(note !== null) {
playNote(instruments[idx], note, startTime, duration);
}
});
currentStep++;
if(playing) {
playIntervalId = setTimeout(() => scheduleStep(currentStep), secondsPerStep*1000);
}
}
scheduleStep(currentStep);
}
function pausePattern() {
playing = false;
playPauseBtn.textContent = 'Play';
if(playIntervalId) {
clearTimeout(playIntervalId);
playIntervalId = null;
}
// Stop scheduled nodes early
if (scheduledNodes.length) {
scheduledNodes.forEach(n => {
try {
if (n.stop) n.stop();
n.disconnect();
} catch {}
});
scheduledNodes = [];
}
}
// Events
bpmInput.addEventListener('change', () => {
let val = parseInt(bpmInput.value);
if (isNaN(val) || val < 30) val = 30;
if (val > 400) val = 400;
state.bpm = val;
bpmInput.value = val;
updateURLHash();
});
rowsPerPatternInput.addEventListener('change', () => {
let val = parseInt(rowsPerPatternInput.value);
if (isNaN(val) || val < 8) val = 8;
if (val > 64) val = 64;
state.rowsPerPattern = val;
rowsPerPatternInput.value = val;
// Resize all patterns
state.patterns.forEach(pattern => {
while(pattern.length < val) {
let row = new Array(state.instruments.length).fill(null);
pattern.push(row);
}
if(pattern.length > val) {
pattern.splice(val);
}
});
updateURLHash();
renderPatternGrid();
});
patternIndexInput.addEventListener('change', () => {
let val = parseInt(patternIndexInput.value);
if (isNaN(val) || val < 0) val = 0;
if (val >= state.patterns.length) val = state.patterns.length - 1;
state.patternIndex = val;
patternIndexInput.value = val;
updateURLHash();
renderPatternGrid();
});
newPatternBtn.addEventListener('click', () => {
state.patterns.push(createEmptyPattern(state.rowsPerPattern, state.instruments.length));
state.patternIndex = state.patterns.length - 1;
patternIndexInput.value = state.patternIndex;
updateURLHash();
renderPatternGrid();
});
delPatternBtn.addEventListener('click', () => {
if (state.patterns.length <= 1) return;
state.patterns.splice(state.patternIndex, 1);
if(state.patternIndex >= state.patterns.length) state.patternIndex = state.patterns.length - 1;
patternIndexInput.value = state.patternIndex;
updateURLHash();
renderPatternGrid();
});
dupPatternBtn.addEventListener('click', () => {
const pat = state.patterns[state.patternIndex];
const copy = deepClone(pat);
state.patterns.splice(state.patternIndex+1, 0, copy);
state.patternIndex = state.patternIndex+1;
patternIndexInput.value = state.patternIndex;
updateURLHash();
renderPatternGrid();
});
copyPatternBtn.addEventListener('click', () => {
state.copiedPattern = deepClone(state.patterns[state.patternIndex]);
});
pastePatternBtn.addEventListener('click', () => {
if (state.copiedPattern) {
state.patterns[state.patternIndex] = deepClone(state.copiedPattern);
updateURLHash();
renderPatternGrid();
}
});
playPauseBtn.addEventListener('click', () => {
if (playing) {
pausePattern();
} else {
playPattern();
}
});
stopBtn.addEventListener('click', () => {
pausePattern();
currentStep = 0;
});
addInstrumentBtn.addEventListener('click', () => {
const newIns = {
name: `Instrument ${state.instruments.length+1}`,
oscType: "square",
volume: 0.5,
detune: 0,
adsr: new ADSREnvelope(0.05, 0.08, 0.5, 0.15),
filterCutoff: 2000,
filterQ: 1,
noise: false
};
state.instruments.push(newIns);
// Add new instrument to all patterns' rows
for(let p=0;p<state.patterns.length;p++) {
for(let r=0;r<state.patterns[p].length;r++) {
state.patterns[p][r].push(null);
}
}
renderInstruments();
renderPatternGrid();
updateURLHash();
});
// Keyboard shortcuts & pattern navigation
window.addEventListener('keydown', (e) => {
if(e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
if(e.code === 'Space') {
e.preventDefault();
if (playing) pausePattern();
else playPattern();
return;
}
switch(e.key.toUpperCase()) {
case 'N':
e.preventDefault();
newPatternBtn.click();
break;
case 'D':
e.preventDefault();
dupPatternBtn.click();
break;
case 'C':
e.preventDefault();
copyPatternBtn.click();
break;
case 'V':
e.preventDefault();
pastePatternBtn.click();
break;
case 'S':
e.preventDefault();
stopBtn.click();
break;
case 'DELETE':
e.preventDefault();
delPatternBtn.click();
break;
case 'ARROWLEFT':
e.preventDefault();
if(state.patternIndex > 0) {
state.patternIndex--;
patternIndexInput.value = state.patternIndex;
updateURLHash();
renderPatternGrid();
}
break;
case 'ARROWRIGHT':
e.preventDefault();
if(state.patternIndex < state.patterns.length - 1) {
state.patternIndex++;
patternIndexInput.value = state.patternIndex;
updateURLHash();
renderPatternGrid();
}
break;
}
});
// Init and render everything
initPatterns();
renderInstruments();
renderPatternGrid();
updateURLHash();
loadFromHash();
window.addEventListener('hashchange', () => {
loadFromHash();
});
// Pattern grid focus styles
patternGridDiv.addEventListener('focus', () => {
if(editingCell) return;
// Highlight selected row maybe?
});
})();
</script>
</body>
</html>
This app will let you:
- Define chiptune tracks in patterns with multiple instruments.
- Edit notes by clicking cells, inputting note names like
C4, D#5, etc.
- Control instrument parameters with sliders/dropdowns.
- Play / pause the song.
- Add/remove/duplicate/copy/paste patterns.
- Share your song data in the URL hash so you can bookmark or share your work.
- Use keyboard shortcuts for efficient editing.
If you want improvements, ask for specific features!