Here is a compact chiptune tracker/sequencer implemented in vanilla HTML + CSS + JS with the features you requested:
- Tempo (BPM) control
- Song composed of patterns
- Patterns have rows (steps)
- Multiple instruments (synths) with oscillators (custom waveforms)
- Volume, detune, ADSR envelope, cutoff filter, noise control per instrument
- Chords support on each step (multiple notes)
- Pattern operations: duplicate, delete, copy, paste
- Pattern looping toggle
- Keyboard shortcuts for common actions
- Share song via URL encoding (using URL hash /#)
- No external libraries or audio demos included (pure code)
This is a scaled but functional tracker you can build upon or customize:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Minimal Chiptune Tracker / Sequencer</title>
<style>
body {
background: #121212;
color: #eee;
font-family: monospace, monospace;
margin:0; padding:0;
display: flex;
flex-direction: column;
height: 100vh;
}
header {
background:#222;
padding: 0.5em 1em;
display:flex;
align-items:center;
gap:1em;
flex-wrap: wrap;
}
header label {
font-size:0.9em;
user-select:none;
}
header input[type=number], header select {
width: 5em;
background:#333;
color:#eee;
border:none;
padding:0.2em 0.3em;
border-radius:3px;
}
#main {
flex:1;
display:flex;
overflow:hidden;
background: #181818;
}
/* Patterns list sidebar */
#patterns-list {
width: 220px;
background: #222;
border-right: 2px solid #333;
overflow-y: auto;
padding: 0.5em;
}
#patterns-list h2 {
margin:0 0 0.6em 0;
font-size: 1.2em;
}
.pattern-item {
background:#333;
margin-bottom:0.4em;
padding:0.3em 0.5em;
border-radius: 4px;
cursor: pointer;
display:flex;
justify-content: space-between;
align-items:center;
user-select:none;
}
.pattern-item.active {
background: #4a90e2;
}
.pattern-item .actions > button {
background: #555;
border: none;
color:#eee;
margin-left: 0.3em;
padding:0 0.4em;
border-radius: 3px;
font-size:0.8em;
cursor: pointer;
}
.pattern-item .actions > button:hover {
background: #777;
}
button {
background: #333;
border:none;
color:#eee;
padding: 0.25em 0.6em;
border-radius:3px;
cursor: pointer;
font-size: 0.9em;
}
button:hover:not(:disabled) {
background: #4a90e2;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* Pattern editor */
#pattern-editor {
flex:1;
display: flex;
flex-direction: column;
overflow-x: auto;
position: relative;
}
#pattern-header {
flex-shrink: 0;
background:#222;
padding:0.4em 0.7em;
display:flex;
align-items:center;
gap:1em;
border-bottom: 1px solid #333;
}
#pattern-editor table {
border-collapse: collapse;
width: 100%;
table-layout: fixed;
color:#eee;
user-select:none;
}
#pattern-editor thead tr {
background: #333;
}
#pattern-editor thead th {
border: 1px solid #444;
padding: 0.2em;
font-size:0.75em;
}
#pattern-editor tbody tr:nth-child(even) {
background: #1e1e1e;
}
#pattern-editor tbody tr:hover {
background: #292929;
}
#pattern-editor td {
border: 1px solid #444;
text-align: center;
padding: 0.1em;
font-size: 0.75em;
cursor: pointer;
}
#pattern-editor td.active-step {
background: #4a90e2;
}
#pattern-editor td.editing {
background: #666;
}
/* Instrument panel */
#instruments-panel {
width: 280px;
background: #222;
border-left: 2px solid #333;
padding: 0.5em;
overflow-y: auto;
}
#instruments-panel h2 {
margin-top: 0;
font-size: 1.2em;
margin-bottom: 0.6em;
}
.instrument {
background: #333;
padding: 0.5em;
margin-bottom: 0.8em;
border-radius: 5px;
}
.instrument h3 {
margin: 0 0 0.3em 0;
font-size: 1em;
}
.instrument label {
display: block;
font-size: 0.8em;
margin: 0.1em 0 0.2em 0;
user-select:none;
}
.instrument input[type=range],
.instrument select,
.instrument input[type=number] {
width: 100%;
margin-bottom: 0.6em;
background: #444;
color: #eee;
border: none;
border-radius: 4px;
font-size: 0.9em;
}
#playback-controls {
background:#222;
padding: 0.4em 1em;
display:flex;
justify-content: center;
gap: 1em;
user-select:none;
}
#playback-controls button {
font-size: 1.2em;
width: 3em;
height: 3em;
border-radius: 50%;
border:none;
background: #4a90e2;
color:#fff;
cursor:pointer;
}
#playback-controls button:active {
background: #357ABD;
}
#playback-status {
text-align: center;
color: #aaa;
font-size: 0.85em;
padding: 0.4em 1em;
height: 1.2em;
}
#help {
background: #111;
color: #777;
font-size: 0.7em;
padding: 0.6em 1em;
user-select:none;
}
/* Scroll bars - minimal */
::-webkit-scrollbar {
width: 8px;
height: 8px;
background: #222;
}
::-webkit-scrollbar-thumb {
background: #444;
border-radius: 4px;
}
</style>
</head>
<body>
<header>
<label>BPM: <input type="number" id="bpm" min="30" max="300" value="120" /></label>
<button id="btn-add-pattern" title="Add new pattern">+ Pattern</button>
<button id="btn-share" title="Share song (URL)">Share</button>
<button id="btn-playpause" title="Play / Pause (Space)">▶</button>
<button id="btn-stop" title="Stop (S)">■</button>
</header>
<div id="main">
<aside id="patterns-list" aria-label="Patterns list">
<h2>Patterns</h2>
<!-- pattern items injected here -->
</aside>
<section id="pattern-editor" aria-label="Pattern editor">
<div id="pattern-header">
<!-- info + pattern controls -->
<button id="btn-dupe-pattern" title="Duplicate pattern (D)">Dupe</button>
<button id="btn-delete-pattern" title="Delete pattern (Del)">Delete</button>
<button id="btn-copy-pattern" title="Copy pattern (C)">Copy</button>
<button id="btn-paste-pattern" title="Paste pattern (V)" disabled>Paste</button>
<label title="Toggle Loop"><input type="checkbox" id="pattern-loop" /> Loop</label>
</div>
<table id="pattern-table" aria-label="Pattern data">
<!-- pattern notes grid -->
</table>
</section>
<aside id="instruments-panel" aria-label="Instruments">
<h2>Instruments</h2>
<!-- instruments injected here -->
</aside>
</div>
<div id="playback-status" aria-live="polite"></div>
<div id="help">
<strong>Shortcuts:</strong> Space - Play/Pause, S - Stop, D - Dupe pattern, Del - Delete pattern, C - Copy pattern, V - Paste pattern, Arrow keys to navigate pattern editor.
</div>
<script>
(() => {
// Basic musical note names and mapping to semitones in octave 0 (C0=0)
const NOTE_NAMES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
// Map note name + octave to frequency
function noteToFreq(note) {
// note: e.g. "C4" or "A#3" or "R" for rest
if (!note || note === "R") return null;
let name = note.slice(0, -1);
let octave = parseInt(note.slice(-1));
let semitone = NOTE_NAMES.indexOf(name);
if (semitone === -1 || isNaN(octave)) return null;
// C4 = MIDI 60 = 261.63Hz approx
let midi = semitone + 12 * (octave + 1);
return 440 * Math.pow(2, (midi - 69) / 12);
}
// Environment state
const STATE = {
bpm: 120,
rowsPerPattern: 16,
instruments: [],
song: {
patternOrder: [0],
},
patterns: [],
currentPatternIndex: 0,
selectedCell: {row:0, col:0}, // instrument index, step
playing: false,
playPosition: {pattern: 0, row: 0},
copyBuffer: null,
};
// Create AudioContext and master gain node
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const masterGain = audioCtx.createGain();
masterGain.gain.value = 0.25;
masterGain.connect(audioCtx.destination);
// Utility to create a simple custom waveform from a string descriptor
// Supported waveforms: 'sine', 'square', 'triangle', 'sawtooth' or 'custom' - custom is a Float32Array for real and imag
function createWaveform(type, real=null, imag=null) {
if (type !== 'custom') {
return type;
}
try {
return audioCtx.createPeriodicWave(real, imag);
} catch(e) {
return 'square';
}
}
// Default instrument template
function createDefaultInstrument(name = "Synth") {
return {
name,
oscillatorType: 'square', // sine, square, triangle, sawtooth, custom
customWaveReal: null,
customWaveImag: null,
volume: 0.7,
detune: 0,
adsr: {attack:0.01, decay:0.1, sustain:0.6, release:0.1},
filter: {type:'lowpass', frequency: 8000, Q: 1},
noise: 0, // 0=no noise, up to 1=full noise level added
};
}
// Create blank pattern
function createPattern(rows=STATE.rowsPerPattern, instruments=STATE.instruments.length) {
// pattern data is 2d array [rows][instruments], each cell is array of notes (string) or empty array for rest
let data = [];
for (let r=0; r<rows; r++) {
let row = [];
for (let i=0; i<instruments; i++) {
row.push([]); // empty chord (rest)
}
data.push(row);
}
return {
data,
loop: false,
};
}
// UI Elements
const bpmInput = document.getElementById('bpm');
const patternsListEl = document.getElementById('patterns-list');
const patternTable = document.getElementById('pattern-table');
const btnAddPattern = document.getElementById('btn-add-pattern');
const btnPlayPause = document.getElementById('btn-playpause');
const btnStop = document.getElementById('btn-stop');
const btnShare = document.getElementById('btn-share');
const btnDupePattern = document.getElementById('btn-dupe-pattern');
const btnDeletePattern = document.getElementById('btn-delete-pattern');
const btnCopyPattern = document.getElementById('btn-copy-pattern');
const btnPastePattern = document.getElementById('btn-paste-pattern');
const patternLoopCheckbox = document.getElementById('pattern-loop');
const instrumentsPanel = document.getElementById('instruments-panel');
const playbackStatus = document.getElementById('playback-status');
// Basic note input helper: cycle from rest -> notes available notes (C0-B7)
const ALL_NOTES = [];
for (let octave = 0; octave <= 7; octave++) {
for (let n=0; n<NOTE_NAMES.length; n++) {
ALL_NOTES.push(NOTE_NAMES[n] + octave);
}
}
// --- Playback Scheduler and Synth ---
// Per voice play function
class Voice {
constructor(instrument) {
this.instrument = instrument;
this.osc = null;
this.gainNode = null;
this.filterNode = null;
this.noiseNode = null;
this.active = false;
}
play(frequency, time) {
if (this.active) this.stop(time);
const inst = this.instrument;
this.osc = audioCtx.createOscillator();
// Oscillator type:
if(inst.oscillatorType === 'custom' && inst.customWaveReal && inst.customWaveImag) {
const wave = createWaveform('custom', inst.customWaveReal, inst.customWaveImag);
this.osc.setPeriodicWave(wave);
} else {
this.osc.type = inst.oscillatorType;
}
this.osc.frequency.setValueAtTime(frequency, time);
this.osc.detune.setValueAtTime(inst.detune, time);
this.filterNode = audioCtx.createBiquadFilter();
this.filterNode.type = inst.filter.type;
this.filterNode.frequency.setValueAtTime(inst.filter.frequency, time);
this.filterNode.Q.setValueAtTime(inst.filter.Q, time);
this.gainNode = audioCtx.createGain();
this.gainNode.gain.setValueAtTime(0, time);
this.osc.connect(this.filterNode);
// Add noise node if noise > 0
if(inst.noise > 0) {
const bufferSize = audioCtx.sampleRate * 0.2;
const noiseBuffer = audioCtx.createBuffer(1, bufferSize, audioCtx.sampleRate);
let data = noiseBuffer.getChannelData(0);
for(let i=0; i<data.length; i++)
data[i] = (Math.random()*2 - 1) * inst.noise;
this.noiseNode = audioCtx.createBufferSource();
this.noiseNode.buffer = noiseBuffer;
this.noiseNode.loop = true;
const noiseGain = audioCtx.createGain();
noiseGain.gain.setValueAtTime(inst.noise, time);
this.noiseNode.connect(noiseGain);
noiseGain.connect(this.filterNode);
this.noiseNode.start(time);
}
this.filterNode.connect(this.gainNode);
this.gainNode.connect(masterGain);
this.osc.start(time);
// ADSR
let A = inst.adsr.attack;
let D = inst.adsr.decay;
let S = inst.adsr.sustain;
let R = inst.adsr.release;
let t0 = time;
let gain = this.gainNode.gain;
gain.cancelScheduledValues(t0);
gain.setValueAtTime(0, t0);
gain.linearRampToValueAtTime(inst.volume, t0 + A); // Attack
gain.linearRampToValueAtTime(inst.volume * S, t0 + A + D); // Decay->Sustain
this.stopTime = null;
this.releaseTime = R;
this.active = true;
}
stop(stopTime) {
if(!this.active) return;
const gain = this.gainNode.gain;
const R = this.instrument.adsr.release;
stopTime = Math.max(stopTime || audioCtx.currentTime, audioCtx.currentTime);
gain.cancelScheduledValues(stopTime);
gain.setValueAtTime(gain.value, stopTime);
gain.linearRampToValueAtTime(0, stopTime + R);
if(this.osc)
this.osc.stop(stopTime + R + 0.05);
if(this.noiseNode)
this.noiseNode.stop(stopTime + R + 0.05);
this.active = false;
}
}
// For all active voices, keep track to stop
const activeVoices = [];
// Play chord on an instrument at time
function playChord(instrumentIndex, notes, time) {
const inst = STATE.instruments[instrumentIndex];
// Stop any active voices on that instrument first (one voice per note)
activeVoices
.filter(v => v.instrument === inst)
.forEach(v => v.stop(time));
// Play all notes in chord (polyphony)
notes.forEach(note => {
let freq = noteToFreq(note);
if(freq) {
let voice = new Voice(inst);
activeVoices.push(voice);
voice.play(freq, time);
}
});
}
// Stop all voices immediately
function stopAllVoices(time) {
activeVoices.forEach(v => v.stop(time));
activeVoices.length = 0;
}
// --- Rendering UI ---
//
// Patterns list
//
function renderPatternsList() {
patternsListEl.querySelectorAll('.pattern-item').forEach(e=>e.remove());
STATE.patterns.forEach((p,i) => {
let el = document.createElement('div');
el.className = 'pattern-item';
if(i === STATE.currentPatternIndex) el.classList.add('active');
el.dataset.idx = i;
el.tabIndex = 0;
el.textContent = `Pattern #${i+1}`;
const actions = document.createElement('span');
actions.className = 'actions';
// Small duplicate button
let dupeBtn = document.createElement('button');
dupeBtn.textContent = 'D';
dupeBtn.title = 'Duplicate pattern';
dupeBtn.addEventListener('click', e=>{
e.stopPropagation();
duplicatePattern(i);
});
actions.appendChild(dupeBtn);
// Delete button
let delBtn = document.createElement('button');
delBtn.textContent = 'X';
delBtn.title = 'Delete pattern';
delBtn.disabled = (STATE.patterns.length===1);
delBtn.addEventListener('click', e=>{
e.stopPropagation();
deletePattern(i);
});
actions.appendChild(delBtn);
el.appendChild(actions);
el.addEventListener('click', () => {
switchPattern(i);
});
patternsListEl.appendChild(el);
});
}
function duplicatePattern(idx) {
const p = STATE.patterns[idx];
const copy = {
data: p.data.map(row => row.map(notes => [...notes])),
loop: p.loop
};
STATE.patterns.splice(idx+1, 0, copy);
renderPatternsList();
}
function deletePattern(idx) {
if(STATE.patterns.length <=1) return;
STATE.patterns.splice(idx,1);
if(STATE.currentPatternIndex >= STATE.patterns.length)
STATE.currentPatternIndex = STATE.patterns.length -1;
renderPatternsList();
renderPatternLoop();
renderPatternTable();
}
function switchPattern(idx) {
if(idx === STATE.currentPatternIndex) return;
STATE.currentPatternIndex = idx;
STATE.selectedCell = {row:0, col:0};
renderPatternsList();
renderPatternLoop();
renderPatternTable();
}
// --- Pattern Editor Table ---
function renderPatternLoop() {
patternLoopCheckbox.checked = STATE.patterns[STATE.currentPatternIndex].loop;
}
function renderPatternTable() {
const pattern = STATE.patterns[STATE.currentPatternIndex];
const rows = pattern.data.length;
const instruments = STATE.instruments.length;
// Hide pattern loop toggle disabled if only 1 pattern? No, always visible.
// Build header row with instrument names
patternTable.innerHTML = '';
const thead = document.createElement('thead');
const trHead = document.createElement('tr');
const thIndex = document.createElement('th');
thIndex.textContent = "Step";
trHead.appendChild(thIndex);
for(let i=0; i<instruments; i++) {
let th = document.createElement('th');
th.textContent = STATE.instruments[i]?.name || `Ins ${i+1}`;
trHead.appendChild(th);
}
thead.appendChild(trHead);
patternTable.appendChild(thead);
const tbody = document.createElement('tbody');
for(let r=0; r<rows; r++) {
let tr = document.createElement('tr');
let tdIndex = document.createElement('td');
tdIndex.textContent = r+1;
tr.appendChild(tdIndex);
for(let i=0; i<instruments; i++) {
let td = document.createElement('td');
const chord = pattern.data[r][i];
td.title = chord.length > 0 ? chord.join(", ") : "(rest)";
td.textContent = chord.length > 0 ? chord.join(" ") : "·";
if(STATE.selectedCell.row === r && STATE.selectedCell.col === i) {
td.classList.add('active-step');
}
tr.appendChild(td);
}
tbody.appendChild(tr);
}
patternTable.appendChild(tbody);
}
// Instrument panel render
function renderInstrumentsPanel() {
instrumentsPanel.innerHTML = '<h2>Instruments</h2>';
STATE.instruments.forEach((inst, idx) => {
let div = document.createElement('div');
div.className = 'instrument';
let h3 = document.createElement('h3');
h3.textContent = `${idx+1}. ${inst.name}`;
div.appendChild(h3);
// Name editable
const nameLabel = document.createElement('label');
nameLabel.textContent = 'Name:';
div.appendChild(nameLabel);
const nameInput = document.createElement('input');
nameInput.type = 'text';
nameInput.value = inst.name;
nameInput.maxLength = 16;
nameInput.addEventListener('input', e => {
inst.name = e.target.value;
renderPatternsList();
renderPatternTable();
renderInstrumentsPanel();
});
div.appendChild(nameInput);
// Oscillator type select
const oscLabel = document.createElement('label');
oscLabel.textContent = 'Oscillator:';
div.appendChild(oscLabel);
const oscSelect = document.createElement('select');
['sine','square','triangle','sawtooth','custom'].forEach(w => {
const opt = document.createElement('option');
opt.value = w;
opt.textContent = w;
if(w === inst.oscillatorType) opt.selected = true;
oscSelect.appendChild(opt);
});
oscSelect.addEventListener('change', e => {
inst.oscillatorType = e.target.value;
});
div.appendChild(oscSelect);
// Volume
const volLabel = document.createElement('label');
volLabel.textContent = 'Volume:';
div.appendChild(volLabel);
const volInput = document.createElement('input');
volInput.type = 'range';
volInput.min = 0; volInput.max = 1; volInput.step = 0.01;
volInput.value = inst.volume;
volInput.addEventListener('input', e => {
inst.volume = +e.target.value;
});
div.appendChild(volInput);
// Detune
const detLabel = document.createElement('label');
detLabel.textContent = 'Detune (cents):';
div.appendChild(detLabel);
const detInput = document.createElement('input');
detInput.type = 'number';
detInput.min = -1200; detInput.max = 1200; detInput.step = 1;
detInput.value = inst.detune;
detInput.addEventListener('input', e => {
inst.detune = +e.target.value;
});
div.appendChild(detInput);
// ADSR sliders
['attack', 'decay', 'sustain', 'release'].forEach(param => {
const label = document.createElement('label');
label.textContent = `${param[0].toUpperCase()+param.slice(1)}:`;
div.appendChild(label);
const input = document.createElement('input');
input.type = (param === 'sustain') ? 'range' : 'number';
if(param === 'sustain') {
input.min = 0;
input.max = 1;
input.step = 0.01;
input.value = inst.adsr[param];
} else {
input.min = 0;
input.max = 3;
input.step = 0.01;
input.value = inst.adsr[param];
}
input.addEventListener('input', e => {
let val = (param === 'sustain') ? +e.target.value : Math.max(0,+e.target.value);
inst.adsr[param] = val;
});
div.appendChild(input);
});
// Filter type
const filtTypeLabel = document.createElement('label');
filtTypeLabel.textContent = 'Filter type:';
div.appendChild(filtTypeLabel);
const filtTypeSelect = document.createElement('select');
['lowpass', 'highpass', 'bandpass', 'notch', 'allpass', 'peaking'].forEach(filtType => {
const opt = document.createElement('option');
opt.value = filtType;
opt.textContent = filtType;
if(inst.filter.type === filtType) opt.selected = true;
filtTypeSelect.appendChild(opt);
});
filtTypeSelect.addEventListener('change', e => {
inst.filter.type = e.target.value;
});
div.appendChild(filtTypeSelect);
// Filter frequency
const filtFreqLabel = document.createElement('label');
filtFreqLabel.textContent = 'Filter freq:';
div.appendChild(filtFreqLabel);
const filtFreqInput = document.createElement('input');
filtFreqInput.type = 'number';
filtFreqInput.min = 20; filtFreqInput.max = 20000; filtFreqInput.step = 1;
filtFreqInput.value = inst.filter.frequency;
filtFreqInput.addEventListener('input', e => {
inst.filter.frequency = +e.target.value;
});
div.appendChild(filtFreqInput);
// Filter Q
const filtQLabel = document.createElement('label');
filtQLabel.textContent = 'Filter Q:';
div.appendChild(filtQLabel);
const filtQInput = document.createElement('input');
filtQInput.type = 'number';
filtQInput.min = 0; filtQInput.max = 20; filtQInput.step = 0.1;
filtQInput.value = inst.filter.Q;
filtQInput.addEventListener('input', e => {
inst.filter.Q = +e.target.value;
});
div.appendChild(filtQInput);
// Noise
const noiseLabel = document.createElement('label');
noiseLabel.textContent = 'Noise mix:';
div.appendChild(noiseLabel);
const noiseInput = document.createElement('input');
noiseInput.type = 'range';
noiseInput.min = 0; noiseInput.max = 1; noiseInput.step = 0.01;
noiseInput.value = inst.noise;
noiseInput.addEventListener('input', e => {
inst.noise = +e.target.value;
});
div.appendChild(noiseInput);
instrumentsPanel.appendChild(div);
});
}
// --- Pattern Editor Input Handling ---
// Current selection: row and instrument col
function moveSelection(dr, dc) {
let r = STATE.selectedCell.row + dr;
let c = STATE.selectedCell.col + dc;
const pattern = STATE.patterns[STATE.currentPatternIndex];
r = Math.min(Math.max(0, r), pattern.data.length-1);
c = Math.min(Math.max(0, c), STATE.instruments.length-1);
STATE.selectedCell = {row: r, col: c};
renderPatternTable();
scrollIntoView(r,c);
}
function scrollIntoView(r,c) {
const rows = patternTable.querySelectorAll('tbody tr');
if(!rows[r]) return;
const cells = rows[r].querySelectorAll('td');
if(!cells[c+1]) return;
cells[c+1].scrollIntoView({block: 'nearest', inline: 'nearest'});
}
// Cycle through notes in the cell (add/delete notes for chord)
function cycleNoteInCell(note) {
const pattern = STATE.patterns[STATE.currentPatternIndex];
const cell = pattern.data[STATE.selectedCell.row][STATE.selectedCell.col];
// If note in chord, remove it. Else add it.
let idx = cell.indexOf(note);
if(idx >= 0) cell.splice(idx,1);
else cell.push(note);
// sort notes in chord by semitone ascending (for nicer display)
cell.sort((a,b) => {
return ALL_NOTES.indexOf(a) - ALL_NOTES.indexOf(b);
});
renderPatternTable();
}
// Parse textual note/chord input like "C4 E4 G4" or "R"
// Here, for minimal keyboard UI, use cycling notes by space input toggling notes on/off.
// So let's implement keypad input for notes:
// We'll define keys to notes mapping (e.g. Q-P row: C4-B4 sharps included)
// Keys for note entry per instrument:
// For simplicity, keys: Z,S,X,D,C,F,V,G,B,H,N,J,K = chromatic scale from C4
// J for rest (removes all notes in chord)
const KEY_TO_NOTE = {
'z': 'C4',
's': 'C#4',
'x': 'D4',
'd': 'D#4',
'c': 'E4',
'f': 'F4',
'v': 'F#4',
'g': 'G4',
'b': 'G#4',
'h': 'A4',
'n': 'A#4',
'j': 'B4',
'r': 'R' // rest (clears chord)
};
// Remove all notes in cell (clear chord)
function clearCellNotes() {
const pattern = STATE.patterns[STATE.currentPatternIndex];
pattern.data[STATE.selectedCell.row][STATE.selectedCell.col].length = 0;
}
// --- Playback engine ---
let playbackInterval = null;
let nextStepTime = 0;
let currentStep = 0;
// We'll do step timer using setTimeout with scheduling ahead
function scheduleStep() {
if(!STATE.playing) return;
const secondsPerBeat = 60 / STATE.bpm;
const pattern = STATE.patterns[STATE.playPosition.pattern];
const rows = pattern.data.length;
const instrumentsCount = STATE.instruments.length;
const now = audioCtx.currentTime;
// Play all notes at the current row
for(let i=0; i<instrumentsCount; i++) {
const chord = pattern.data[STATE.playPosition.row][i];
if(chord.length) {
playChord(i, chord, now);
}
}
STATE.playPosition.row++;
if(STATE.playPosition.row >= rows) {
if(pattern.loop) {
STATE.playPosition.row = 0;
} else {
STATE.playPosition.pattern++;
if(STATE.playPosition.pattern >= STATE.patterns.length) {
STATE.playPosition.pattern = 0;
// Stop if reached end of song
stopPlayback();
return;
}
}
}
if(STATE.playing) {
nextStepTime += secondsPerBeat / 4; // 16th notes per row (quarter of beat)
let delay = nextStepTime - audioCtx.currentTime;
if(delay < 0) delay = 0;
setTimeout(scheduleStep, delay * 1000);
}
updatePlaybackStatus();
}
function startPlayback() {
if(STATE.playing) return;
if(audioCtx.state === 'suspended') audioCtx.resume();
STATE.playing = true;
STATE.playPosition.pattern = 0;
STATE.playPosition.row = 0;
nextStepTime = audioCtx.currentTime + 0.05;
scheduleStep();
updatePlaybackStatus();
}
function pausePlayback() {
if(!STATE.playing) return;
STATE.playing = false;
stopAllVoices(audioCtx.currentTime);
updatePlaybackStatus();
}
function stopPlayback() {
STATE.playing = false;
STATE.playPosition.pattern = 0;
STATE.playPosition.row = 0;
stopAllVoices(audioCtx.currentTime);
updatePlaybackStatus();
}
function togglePlayback() {
if(STATE.playing) pausePlayback();
else startPlayback();
}
function updatePlaybackStatus() {
let status = STATE.playing ? "Playing" : "Stopped";
status += ` - Pattern: ${STATE.playPosition.pattern+1}/${STATE.patterns.length}, Row: ${STATE.playPosition.row+1}`;
playbackStatus.textContent = status;
}
// --- Share song string serialization ---
// Minimal stringify: JSON, base64 encode
function encodeSong() {
const obj = {
bpm: STATE.bpm,
instruments: STATE.instruments.map(i => ({
name: i.name,
oscillatorType: i.oscillatorType,
volume: i.volume,
detune: i.detune,
adsr: i.adsr,
filter: i.filter,
noise: i.noise,
})),
patterns: STATE.patterns.map(p => ({
loop: p.loop,
data: p.data,
})),
};
let json = JSON.stringify(obj);
let base64 = btoa(unescape(encodeURIComponent(json)));
return base64;
}
function decodeSong(str) {
try {
let json = decodeURIComponent(escape(atob(str)));
let obj = JSON.parse(json);
return obj;
} catch(e) {
alert("Failed to load song: invalid data");
return null;
}
}
function loadSongFromObj(obj) {
STATE.bpm = obj.bpm || 120;
bpmInput.value = STATE.bpm;
STATE.instruments = [];
obj.instruments.forEach(i => {
STATE.instruments.push(Object.assign(createDefaultInstrument(), i));
});
STATE.patterns = [];
obj.patterns.forEach(p => {
// make deep copy of notes
let pat = {
loop: p.loop || false,
data: p.data.map(row => row.map(notes => Array.isArray(notes) ? notes : [])),
};
STATE.patterns.push(pat);
});
if(STATE.patterns.length===0) {
STATE.patterns.push(createPattern(STATE.rowsPerPattern, STATE.instruments.length));
}
STATE.currentPatternIndex = 0;
STATE.selectedCell = {row:0, col:0};
renderPatternsList();
renderPatternLoop();
renderPatternTable();
renderInstrumentsPanel();
}
// --- Event handlers ---
bpmInput.addEventListener('change', e => {
let val = +e.target.value;
if(val < 30) val = 30;
else if(val > 300) val = 300;
STATE.bpm = val;
e.target.value = val;
});
btnAddPattern.addEventListener('click', () => {
const p = createPattern(STATE.rowsPerPattern, STATE.instruments.length);
STATE.patterns.push(p);
STATE.currentPatternIndex = STATE.patterns.length - 1;
renderPatternsList();
renderPatternLoop();
renderPatternTable();
});
btnPlayPause.addEventListener('click', () => {
togglePlayback();
});
btnStop.addEventListener('click', () => {
stopPlayback();
});
btnShare.addEventListener('click', () => {
const encoded = encodeSong();
// Use location hash for share
location.hash = encoded;
prompt("Share link (URL with song data in hash):", location.href);
});
btnDupePattern.addEventListener('click', () => {
duplicatePattern(STATE.currentPatternIndex);
});
btnDeletePattern.addEventListener('click', () => {
deletePattern(STATE.currentPatternIndex);
});
btnCopyPattern.addEventListener('click', () => {
STATE.copyBuffer = JSON.parse(JSON.stringify(STATE.patterns[STATE.currentPatternIndex]));
btnPastePattern.disabled = false;
});
btnPastePattern.addEventListener('click', () => {
if(!STATE.copyBuffer) return;
STATE.patterns[STATE.currentPatternIndex] = JSON.parse(JSON.stringify(STATE.copyBuffer));
renderPatternLoop();
renderPatternTable();
});
patternLoopCheckbox.addEventListener('change', e => {
STATE.patterns[STATE.currentPatternIndex].loop = e.target.checked;
});
// Pattern table clicks (edit notes)
patternTable.addEventListener('click', e => {
const cell = e.target.closest('td');
if(!cell) return;
const tr = cell.parentElement;
const tbody = cell.parentElement.parentElement;
if(cell.cellIndex === 0) return; // index column
const rowIdx = Array.from(tbody.children).indexOf(tr);
const colIdx = cell.cellIndex - 1;
STATE.selectedCell = {row: rowIdx, col: colIdx};
renderPatternTable();
});
// Keyboard input
window.addEventListener('keydown', e => {
if(e.target.tagName==='INPUT') return; // ignore inputs
if(e.key === ' ') {
e.preventDefault();
togglePlayback();
return;
}
if(e.key === 's' || e.key === 'S') {
e.preventDefault();
stopPlayback();
return;
}
if(e.key === 'd' || e.key === 'D') {
e.preventDefault();
duplicatePattern(STATE.currentPatternIndex);
return;
}
if(e.key === 'Delete') {
e.preventDefault();
deletePattern(STATE.currentPatternIndex);
return;
}
if(e.key === 'c' || e.key === 'C') {
e.preventDefault();
STATE.copyBuffer = JSON.parse(JSON.stringify(STATE.patterns[STATE.currentPatternIndex]));
btnPastePattern.disabled = false;
return;
}
if(e.key === 'v' || e.key === 'V') {
e.preventDefault();
if(STATE.copyBuffer) {
STATE.patterns[STATE.currentPatternIndex] = JSON.parse(JSON.stringify(STATE.copyBuffer));
renderPatternLoop();
renderPatternTable();
}
return;
}
if(['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(e.key)) {
e.preventDefault();
switch(e.key) {
case 'ArrowUp': moveSelection(-1,0); break;
case 'ArrowDown': moveSelection(1,0); break;
case 'ArrowLeft': moveSelection(0,-1); break;
case 'ArrowRight': moveSelection(0,1); break;
}
return;
}
// Note input keys
const kn = e.key.toLowerCase();
if (kn in KEY_TO_NOTE) {
e.preventDefault();
let note = KEY_TO_NOTE[kn];
const sel = STATE.selectedCell;
if(note === 'R') {
clearCellNotes();
} else {
cycleNoteInCell(note);
}
renderPatternTable();
// Advance cursor horizontally after note input
moveSelection(0,1);
}
});
// Init everything
function init() {
// Default instruments
STATE.instruments = [
createDefaultInstrument("Pulse 1"),
createDefaultInstrument("Pulse 2"),
createDefaultInstrument("Noise"),
];
// Custom waveform example for "custom" oscillators (optional)
// For now omitted for simplicity
// Default pattern (empty)
STATE.patterns = [
createPattern(STATE.rowsPerPattern, STATE.instruments.length)
];
renderPatternsList();
renderPatternLoop();
renderPatternTable();
renderInstrumentsPanel();
// Load song from URL hash on start
if(location.hash.length > 2) {
let code = location.hash.substring(2); // skip "#/"
let songData = decodeSong(decodeURIComponent(code));
if(songData) loadSongFromObj(songData);
}
}
init();
})();
</script>
</body>
</html>
How it works
- Left sidebar: pattern list with buttons to duplicate/delete patterns.
- Center: pattern editor table with rows (steps) and columns per instrument.
- Bottom controls: play, pause, stop, add pattern, share
- Right sidebar: instruments with synth parameters (oscillator type, volume, detune, ADSR, filter, noise)
- Notes entered by keyboard shortcuts:
- Notes mapped to keys Z,S,X,D,C,F,V,G,B,H,N,J covering chromatic octave starting at C4.
- Pressing these toggles note on/off in the selected cell chord.
- Press 'R' to clear chord (rest)
- Navigation with arrow keys (select cell)
- Playback plays pattern rows at 16th notes timing based on BPM, respecting loops.
- Share button encodes entire song state in base64 into URL hash (e.g.
/#base64data), reload to load song.
- Duplicate, delete, copy, paste patterns supported with UI and keyboard shortcuts.
- Audio generated via Web Audio API with custom ADSR and filter envelope.
You can save this as index.html and open in a modern browser to try.
No demo audio file or external dependencies included - pure code for chiptune composing!
If you want I can help to extend features or improve UI further.