html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Chiptune Sequencer</title>
<style>
body {
font-family: monospace, monospace;
background: #111;
color: #eee;
margin: 0;
display: flex;
flex-direction: column;
height: 100vh;
}
header {
background: #222;
padding: 0.5em 1em;
display: flex;
align-items: center;
gap: 1em;
}
header label {
font-weight: bold;
}
#container {
flex: 1;
display: flex;
overflow: hidden;
}
#sequencer {
flex: 1;
display: flex;
flex-direction: column;
overflow: auto;
user-select: none;
}
#patternGrid {
display: grid;
grid-template-columns: 50px repeat(16, 32px);
grid-auto-rows: 30px;
border-top: 1px solid #444;
border-left: 1px solid #444;
}
#patternGrid .label {
border-bottom: 1px solid #444;
border-right: 1px solid #444;
display: flex;
align-items: center;
justify-content: center;
background: #222;
}
#patternGrid .step {
border-bottom: 1px solid #444;
border-right: 1px solid #444;
background: #111;
cursor: pointer;
}
#patternGrid .step.active {
background: #2b8fd2;
}
#patternGrid .step.playing {
border-color: #f80 !important;
}
#sidebar {
flex-basis: 320px;
background: #222;
padding: 1em;
box-sizing: border-box;
display: flex;
flex-direction: column;
gap: 1em;
overflow-y: auto;
}
.section {
border: 1px solid #444;
padding: 0.5em;
}
.section h3 {
margin-top: 0;
margin-bottom: 0.5em;
font-weight: normal;
font-size: 1.1em;
border-bottom: 1px solid #444;
padding-bottom: 0.3em;
}
label {
display: block;
margin-bottom: 0.3em;
font-size: 0.9em;
}
input[type=number], select {
width: 100%;
font-family: monospace;
font-size: 1em;
margin-bottom: 0.6em;
background: #111;
border: 1px solid #555;
color: #eee;
padding: 0.2em 0.4em;
box-sizing: border-box;
}
input[type=range] {
width: 100%;
}
button {
background: #2b8fd2;
border: none;
color: white;
padding: 0.4em 0.8em;
margin-right: 0.5em;
cursor: pointer;
user-select: none;
font-size: 0.9em;
}
button:disabled {
background: #555;
cursor: default;
}
#patternControls button {
margin-bottom: 0.5em;
}
footer {
background: #222;
text-align: center;
color: #666;
font-size: 0.8em;
padding: 0.3em 0;
}
/* Scrollbar for sidebar */
#sidebar::-webkit-scrollbar {
width: 8px;
}
#sidebar::-webkit-scrollbar-thumb {
background-color: #444;
}
</style>
</head>
<body>
<header>
<label for="bpm">BPM:</label>
<input type="number" id="bpm" min="40" max="300" value="120" step="1" />
<button id="playBtn" title="Space: Play/Stop">► Play</button>
<button id="stopBtn" title="Stop">■ Stop</button>
<button id="shareBtn" title="Share song via URL">Share</button>
</header>
<div id="container">
<div id="sequencer" aria-label="Sequencer Grid" role="grid"></div>
<aside id="sidebar">
<div class="section" id="trackSection">
<h3>Tracks</h3>
<select id="trackSelect" size="4" aria-label="Select track" style="width:100%;"></select>
<button id="addTrackBtn" title="Add Track">+ Add Track</button>
<button id="removeTrackBtn" title="Remove Selected Track" disabled>− Remove Track</button>
</div>
<div class="section" id="patternControls">
<h3>Pattern Controls</h3>
<button id="duplicatePatternBtn" title="Duplicate Pattern">Duplicate</button>
<button id="deletePatternBtn" title="Delete Pattern">Delete</button>
<button id="copyPatternBtn" title="Copy Pattern">Copy</button>
<button id="pastePatternBtn" title="Paste Pattern" disabled>Paste</button>
</div>
<form class="section" id="synthSettings" aria-label="Synth Settings">
<h3>Synth Settings</h3>
<label for="waveform">Waveform</label>
<select id="waveform" name="waveform" aria-describedby="waveformDesc">
<option value="sine">Sine</option>
<option value="square">Square</option>
<option value="sawtooth">Sawtooth</option>
<option value="triangle">Triangle</option>
<option value="noise">Noise</option>
</select>
<small id="waveformDesc" style="color:#777;">Oscillator waveform</small>
<label for="volume">Volume</label>
<input type="range" id="volume" name="volume" min="0" max="1" step="0.01" value="0.5" />
<label for="detune">Detune (Cents)</label>
<input type="range" id="detune" name="detune" min="-100" max="100" step="1" value="0" />
<label>ADSR Envelope</label>
<label for="attack">Attack (s)</label>
<input type="number" id="attack" name="attack" min="0" max="2" value="0.01" step="0.01" />
<label for="decay">Decay (s)</label>
<input type="number" id="decay" name="decay" min="0" max="2" value="0.1" step="0.01" />
<label for="sustain">Sustain (0-1)</label>
<input type="number" id="sustain" name="sustain" min="0" max="1" step="0.01" value="0.3" />
<label for="release">Release (s)</label>
<input type="number" id="release" name="release" min="0" max="2" value="0.2" step="0.01" />
<label for="filterCutoff">Filter Cutoff (Hz)</label>
<input type="number" id="filterCutoff" name="filterCutoff" min="100" max="12000" step="1" value="8000" />
<label for="filterResonance">Filter Q (Resonance)</label>
<input type="number" id="filterResonance" name="filterResonance" min="0" max="20" step="0.1" value="1" />
</form>
</aside>
</div>
<footer>
Use Space to Play/Pause | Click grid to toggle notes | Add tracks and tweak synths | Share song with Share button
</footer>
<script>
(() => {
'use strict';
// Constants
const NOTES = [
'C5', 'A#4', 'A4', 'G#4', 'G4', 'F#4', 'F4', 'E4',
'D#4', 'D4', 'C#4', 'C4', 'B3', 'A#3', 'A3', 'G#3'
]; // 16 notes descending roughly one octave; can be tuned later
// Reverse notes to render from top C5 to bottom G#3
const NOTES_REVERSED = [...NOTES].reverse();
const DEFAULT_BPM = 120;
const STEPS = 16; // per bar
const DEFAULT_TRACKS = 3;
// Utility: Frequency lookup for notes
function noteToFrequency(note) {
// Simple hardcoded map, C4 = 261.63 Hz, use note names for 16 notes
// Using standard equal temperament formula for reference
const A4 = 440;
const SEMITONE = Math.pow(2, 1 / 12);
// Map note names to semitone offsets from A4
const noteMap = {
'C': -9,
'C#': -8,
'D': -7,
'D#': -6,
'E': -5,
'F': -4,
'F#': -3,
'G': -2,
'G#': -1,
'A': 0,
'A#': 1,
'B': 2,
};
// Parse note (e.g. C4, A#3)
let m = note.match(/^([A-G]#?)(\d)$/);
if (!m) return 440;
let [, pitch, octave] = m;
octave = +octave;
let semitonesFromA4 = noteMap[pitch] + (octave - 4) * 12;
return A4 * Math.pow(SEMITONE, semitonesFromA4);
}
// Audio Context Setup
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
const audioCtx = new AudioContextClass();
// Clean stop all oscillators and gain nodes
let activeNodes = [];
// Sequencer State
let bpm = DEFAULT_BPM;
let playing = false;
let songData = {
tracks: [] // Array of tracks -> { name, instrument with synth params, patterns }
};
// Each track has patterns with note steps: 16 steps * 16 notes grid for now (steps horizontally, notes vertically)
// Copied pattern buffer
let copiedPattern = null;
// Current selected track index
let curTrack = 0;
// Scheduler
let schedulerTimer;
let nextStepTime = 0;
let currentStep = 0;
const lookahead = 25; // ms
const scheduleAheadTime = 0.1; // seconds
// Elements
const bpmInput = document.getElementById('bpm');
const playBtn = document.getElementById('playBtn');
const stopBtn = document.getElementById('stopBtn');
const shareBtn = document.getElementById('shareBtn');
const sequencerDiv = document.getElementById('sequencer');
const patternGrid = document.createElement('div');
patternGrid.id = 'patternGrid';
sequencerDiv.appendChild(patternGrid);
const trackSelect = document.getElementById('trackSelect');
const addTrackBtn = document.getElementById('addTrackBtn');
const removeTrackBtn = document.getElementById('removeTrackBtn');
const duplicatePatternBtn = document.getElementById('duplicatePatternBtn');
const deletePatternBtn = document.getElementById('deletePatternBtn');
const copyPatternBtn = document.getElementById('copyPatternBtn');
const pastePatternBtn = document.getElementById('pastePatternBtn');
// Synth inputs
const waveformInput = document.getElementById('waveform');
const volumeInput = document.getElementById('volume');
const detuneInput = document.getElementById('detune');
const attackInput = document.getElementById('attack');
const decayInput = document.getElementById('decay');
const sustainInput = document.getElementById('sustain');
const releaseInput = document.getElementById('release');
const filterCutoffInput = document.getElementById('filterCutoff');
const filterResonanceInput = document.getElementById('filterResonance');
// Set initial BPM input value
bpmInput.value = bpm;
// Initialize default tracks
function createEmptyPattern() {
// 16 steps × 16 notes (false=off)
return Array(STEPS).fill(null).map(() => Array(NOTES.length).fill(false));
}
function createTrack(name = 'Track', instrument = null) {
if (!instrument) instrument = createDefaultInstrument();
return {
name,
instrument,
patterns: [createEmptyPattern()],
curPattern: 0,
};
}
function createDefaultInstrument() {
return {
waveform: 'square',
volume: 0.5,
detune: 0,
adsr: {
attack: 0.01,
decay: 0.1,
sustain: 0.3,
release: 0.2,
},
filter: {
cutoff: 8000,
resonance: 1,
}
};
}
function init() {
// If URL has hash - load song from it
if(window.location.hash && window.location.hash.length > 2) {
try {
const dataStr = decodeURIComponent(window.location.hash.slice(2));
const data = JSON.parse(atob(dataStr));
if (data && data.tracks) {
songData = data;
} else {
resetDefaults();
}
} catch(e) {
resetDefaults();
}
} else {
resetDefaults();
}
renderTracks();
selectTrack(0);
renderGrid();
bindEvents();
}
function resetDefaults(){
songData = {
tracks: []
};
for(let i=0;i<DEFAULT_TRACKS;i++) {
songData.tracks.push(createTrack(`Track ${i+1}`));
}
}
function renderTracks() {
// Clear tracks
trackSelect.innerHTML = '';
songData.tracks.forEach((t,i) => {
const opt = document.createElement('option');
opt.value = i;
opt.textContent = t.name;
trackSelect.appendChild(opt);
});
if(songData.tracks.length > 0) {
trackSelect.value = curTrack;
removeTrackBtn.disabled = songData.tracks.length === 1;
} else {
removeTrackBtn.disabled = true;
}
}
// Select a track to show/edit
function selectTrack(idx) {
if (idx < 0 || idx >= songData.tracks.length) return;
curTrack = idx;
trackSelect.value = idx;
updateSynthControls();
renderGrid();
removeTrackBtn.disabled = songData.tracks.length <= 1;
pastePatternBtn.disabled = !copiedPattern;
}
// Render pattern grid for selected track & pattern
function renderGrid() {
const track = songData.tracks[curTrack];
if (!track) return;
const pattern = track.patterns[track.curPattern];
// Clear grid
patternGrid.innerHTML = '';
// Grid template columns: first col for note labels, then 16 steps
patternGrid.style.gridTemplateColumns = `50px repeat(${STEPS}, 32px)`;
patternGrid.style.gridAutoRows = '30px';
// First row: empty top-left cell + steps header
// Add empty label (top-left)
const emptyLabel = document.createElement('div');
emptyLabel.classList.add('label');
patternGrid.appendChild(emptyLabel);
for (let step = 0; step < STEPS; step++) {
const stepLabel = document.createElement('div');
stepLabel.classList.add('label');
stepLabel.textContent = step + 1;
patternGrid.appendChild(stepLabel);
}
// Rows: notes + step cells
for (let noteIdx=0; noteIdx<NOTES.length; noteIdx++) {
// Note label column
const noteLabel = document.createElement('div');
noteLabel.classList.add('label');
noteLabel.textContent = NOTES_REVERSED[noteIdx];
patternGrid.appendChild(noteLabel);
// Each step cell
for (let step=0; step<STEPS; step++) {
const stepDiv = document.createElement('div');
stepDiv.classList.add('step');
const realNoteIdx = NOTES.length - 1 - noteIdx;
if(pattern[step][realNoteIdx]) stepDiv.classList.add('active');
stepDiv.dataset.step = step;
stepDiv.dataset.note = realNoteIdx;
stepDiv.tabIndex = 0; // make focusable
stepDiv.setAttribute('role', 'gridcell');
stepDiv.setAttribute('aria-checked', stepDiv.classList.contains('active') ? 'true' : 'false');
stepDiv.addEventListener('click', () => {
toggleNoteOnStep(step, realNoteIdx);
renderGrid(); // rerender to update UI immediately
});
stepDiv.addEventListener('keydown', (ev) => {
if(ev.key === ' ' || ev.key === 'Enter') {
ev.preventDefault();
toggleNoteOnStep(step, realNoteIdx);
renderGrid();
}
});
patternGrid.appendChild(stepDiv);
}
}
// Clear playing step highlight if not playing
if(!playing) clearPlayingHighlight();
}
function toggleNoteOnStep(step, noteIdx) {
let track = songData.tracks[curTrack];
let pattern = track.patterns[track.curPattern];
pattern[step][noteIdx] = !pattern[step][noteIdx];
}
// Playlist scheduling and playback
function schedule() {
if (!playing) return;
let secondsPerBeat = 60.0 / bpm;
const stepDuration = secondsPerBeat / 4; // Assuming 16th notes
while (nextStepTime < audioCtx.currentTime + scheduleAheadTime) {
// Schedule notes for currentStep
playStep(curTrack, currentStep, nextStepTime);
nextStepTime += stepDuration;
currentStep = (currentStep + 1) % STEPS;
// Highlight playing column
updatePlayingHighlight(currentStep);
}
schedulerTimer = setTimeout(schedule, lookahead);
}
function playStep(trackIndex, step, time) {
const track = songData.tracks[trackIndex];
const pattern = track.patterns[track.curPattern];
if (!pattern) return;
const instrument = track.instrument;
for (let noteIdx = 0; noteIdx < NOTES.length; noteIdx++) {
if (pattern[step][noteIdx]) {
playNote(NOTES[noteIdx], time, instrument);
}
}
}
function playNote(noteName, startTime, instrument) {
try {
const oscType = instrument.waveform;
const attack = Number(instrument.adsr.attack);
const decay = Number(instrument.adsr.decay);
const sustain = Number(instrument.adsr.sustain);
const release = Number(instrument.adsr.release);
const volume = Number(instrument.volume);
const detune = Number(instrument.detune);
const filterCutoff = Number(instrument.filter.cutoff);
const filterQ = Number(instrument.filter.resonance);
let osc, noiseSource;
const gainNode = audioCtx.createGain();
const filterNode = audioCtx.createBiquadFilter();
filterNode.type = 'lowpass';
filterNode.frequency.setValueAtTime(filterCutoff, startTime);
filterNode.Q.setValueAtTime(filterQ, startTime);
gainNode.gain.setValueAtTime(0, startTime);
filterNode.connect(gainNode).connect(audioCtx.destination);
if (oscType === 'noise') {
// Noise buffer source
const bufferSize = audioCtx.sampleRate * 0.2;
const noiseBuffer = audioCtx.createBuffer(1, bufferSize, audioCtx.sampleRate);
const output = noiseBuffer.getChannelData(0);
for (let i = 0; i < bufferSize; i++) {
output[i] = Math.random() * 2 - 1;
}
noiseSource = audioCtx.createBufferSource();
noiseSource.buffer = noiseBuffer;
noiseSource.loop = true;
noiseSource.connect(filterNode);
noiseSource.start(startTime);
} else {
osc = audioCtx.createOscillator();
osc.type = oscType;
osc.frequency.setValueAtTime(noteToFrequency(noteName), startTime);
osc.detune.setValueAtTime(detune, startTime);
osc.connect(filterNode);
osc.start(startTime);
}
// ADSR envelope
gainNode.gain.setValueAtTime(0, startTime);
gainNode.gain.linearRampToValueAtTime(volume, startTime + attack);
gainNode.gain.linearRampToValueAtTime(volume * sustain, startTime + attack + decay);
// Schedule release
const noteDuration = (60 / bpm) /4; // single step duration (16th note)
const releaseStart = startTime + noteDuration;
gainNode.gain.setValueAtTime(volume * sustain, releaseStart);
gainNode.gain.linearRampToValueAtTime(0, releaseStart + release);
// Stop nodes
if (noiseSource) {
noiseSource.stop(releaseStart + release);
}
if (osc) {
osc.stop(releaseStart + release);
}
// Keep references to allow stop all later
activeNodes.push({osc, noiseSource, gainNode, filterNode});
} catch(e) {
console.warn('Play note error:', e);
}
}
// Stop playback and clear all active sounds
function stopPlayback() {
clearTimeout(schedulerTimer);
playing = false;
playBtn.textContent = '► Play';
currentStep = 0;
clearPlayingHighlight();
activeNodes.forEach(node => {
try {
if (node.osc) node.osc.stop();
if (node.noiseSource) node.noiseSource.stop();
if (node.gainNode) node.gainNode.disconnect();
if (node.filterNode) node.filterNode.disconnect();
} catch (e) {}
});
activeNodes = [];
}
function startPlayback() {
if (audioCtx.state === 'suspended') {
audioCtx.resume();
}
playing = true;
currentStep = 0;
nextStepTime = audioCtx.currentTime + 0.05;
playBtn.textContent = '❚❚ Pause';
schedule();
}
// Highlight currently playing step cells
function updatePlayingHighlight(step) {
const stepCols = patternGrid.querySelectorAll('.step.playing');
stepCols.forEach(el => el.classList.remove('playing'));
// Add playing class to cells for current step column
const cells = patternGrid.querySelectorAll(`.step[data-step="${step}"]`);
cells.forEach(el => el.classList.add('playing'));
}
function clearPlayingHighlight() {
const stepCols = patternGrid.querySelectorAll('.step.playing');
stepCols.forEach(el => el.classList.remove('playing'));
}
// Bind UI events
function bindEvents() {
bpmInput.addEventListener('change', () => {
let val = Math.min(300, Math.max(40, +bpmInput.value));
bpm = val;
bpmInput.value = val;
});
playBtn.addEventListener('click', () => {
togglePlay();
});
stopBtn.addEventListener('click', () => {
stopPlayback();
});
shareBtn.addEventListener('click', shareSong);
// Tracks
trackSelect.addEventListener('change', (ev) => {
selectTrack(Number(ev.target.value));
});
addTrackBtn.addEventListener('click', () => {
if(songData.tracks.length >= 8) return alert('Max 8 tracks');
songData.tracks.push(createTrack(`Track ${songData.tracks.length +1}`));
renderTracks();
selectTrack(songData.tracks.length - 1);
renderGrid();
});
removeTrackBtn.addEventListener('click', () => {
if(songData.tracks.length <= 1) return;
songData.tracks.splice(curTrack, 1);
curTrack = Math.min(songData.tracks.length - 1, curTrack);
renderTracks();
selectTrack(curTrack);
renderGrid();
});
// Pattern controls
duplicatePatternBtn.addEventListener('click', () => {
duplicatePattern();
});
deletePatternBtn.addEventListener('click', () => {
deletePattern();
});
copyPatternBtn.addEventListener('click', () => {
copyPattern();
});
pastePatternBtn.addEventListener('click', () => {
pastePattern();
});
// Synth settings
waveformInput.addEventListener('change', updateInstrument);
volumeInput.addEventListener('input', updateInstrument);
detuneInput.addEventListener('input', updateInstrument);
attackInput.addEventListener('change', updateInstrument);
decayInput.addEventListener('change', updateInstrument);
sustainInput.addEventListener('change', updateInstrument);
releaseInput.addEventListener('change', updateInstrument);
filterCutoffInput.addEventListener('change', updateInstrument);
filterResonanceInput.addEventListener('change', updateInstrument);
// Keyboard shortcuts
window.addEventListener('keydown', (e) => {
if(e.target.tagName === 'INPUT' || e.target.tagName === 'SELECT') return; // ignore input
switch(e.key.toLowerCase()){
case ' ':
e.preventDefault();
togglePlay();
break;
case 'arrowright':
e.preventDefault();
if(playing) break;
// advance pattern step highlight (optional)
break;
case 'arrowleft':
e.preventDefault();
if(playing) break;
// rewind pattern
break;
case 'delete':
e.preventDefault();
deletePattern();
break;
case 'c':
if(e.ctrlKey || e.metaKey) {
e.preventDefault();
copyPattern();
}
break;
case 'v':
if(e.ctrlKey || e.metaKey) {
e.preventDefault();
pastePattern();
}
break;
case 'd':
if(e.ctrlKey || e.metaKey) {
e.preventDefault();
duplicatePattern();
}
break;
}
});
}
function togglePlay() {
if (playing) {
stopPlayback();
} else {
startPlayback();
}
}
// Update synth instrument parameters from controls
function updateInstrument() {
const track = songData.tracks[curTrack];
if (!track) return;
const inst = track.instrument;
inst.waveform = waveformInput.value;
inst.volume = parseFloat(volumeInput.value);
inst.detune = parseFloat(detuneInput.value);
inst.adsr.attack = parseFloat(attackInput.value);
inst.adsr.decay = parseFloat(decayInput.value);
inst.adsr.sustain = parseFloat(sustainInput.value);
inst.adsr.release = parseFloat(releaseInput.value);
inst.filter.cutoff = parseInt(filterCutoffInput.value);
inst.filter.resonance = parseFloat(filterResonanceInput.value);
}
// Update controls from current instrument
function updateSynthControls() {
const track = songData.tracks[curTrack];
if (!track) return;
const inst = track.instrument;
waveformInput.value = inst.waveform;
volumeInput.value = inst.volume;
detuneInput.value = inst.detune;
attackInput.value = inst.adsr.attack;
decayInput.value = inst.adsr.decay;
sustainInput.value = inst.adsr.sustain;
releaseInput.value = inst.adsr.release;
filterCutoffInput.value = inst.filter.cutoff;
filterResonanceInput.value = inst.filter.resonance;
}
// Pattern management
function duplicatePattern() {
const track = songData.tracks[curTrack];
if (!track) return;
if(track.patterns.length >= 8) {
alert('Max 8 patterns per track');
return;
}
const curP = track.patterns[track.curPattern];
const copy = curP.map(step => step.slice());
track.patterns.splice(track.curPattern + 1, 0, copy);
track.curPattern++;
renderGrid();
}
function deletePattern() {
const track = songData.tracks[curTrack];
if (!track) return;
if (track.patterns.length <= 1) {
alert('Cannot delete last pattern');
return;
}
track.patterns.splice(track.curPattern, 1);
track.curPattern = Math.max(0, track.curPattern - 1);
renderGrid();
}
function copyPattern() {
const track = songData.tracks[curTrack];
if (!track) return;
copiedPattern = track.patterns[track.curPattern].map(step => step.slice());
pastePatternBtn.disabled = false;
}
function pastePattern() {
if (!copiedPattern) return;
const track = songData.tracks[curTrack];
if (!track) return;
track.patterns[track.curPattern] = copiedPattern.map(step => step.slice());
renderGrid();
}
// Share song as JSON in URL hash
function shareSong() {
try {
const dataStr = btoa(JSON.stringify(songData));
// Use shorten base64 + encodeURIComponent to avoid issues
const url = location.origin + location.pathname + '#/' + encodeURIComponent(dataStr);
navigator.clipboard.writeText(url).then(() => {
alert('Song link copied to clipboard!');
}, () => {
prompt('Copy this link:', url);
});
} catch(e) {
alert('Error sharing song: ' + e.message);
}
}
// Initialization call
init();
})();
</script>
</body>
</html>
You can save this single HTML file and open in a modern browser (Chrome/Firefox/Edge). It requires no server or external libs.
Feel free to expand with additional UI improvements or pattern chaining as needed!