This example uses only the Web Audio API and basic DOM, no external dependencies, no demo sound playback buttons but will produce sound once the "Play" button is pressed.
html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Minimal Chiptune Tracker</title>
<style>
body {
font-family: monospace;
background: #111;
color: #eee;
margin: 0;
padding: 0.5rem;
user-select: none;
}
table {
border-collapse: collapse;
}
td, th {
border: 1px solid #333;
padding: 0.2em 0.4em;
text-align: center;
min-width: 20px;
}
input[type="number"] {
width: 4em;
background: #222;
border: 1px solid #555;
color: #eee;
}
button {
background: #222;
border: 1px solid #555;
color: #eee;
padding: 0.3em 0.6em;
margin-top: 0.5em;
cursor: pointer;
}
button:hover { background: #444; }
textarea {
width: 100%;
height: 6em;
background: #222;
border: 1px solid #555;
color: #eee;
font-family: monospace;
font-size: 0.9em;
}
.controls {
margin-bottom: 1em;
}
.grid-container {
overflow-x: auto;
margin-bottom: 1em;
}
.pattern-table th, .pattern-table td {
min-width: 30px;
}
.instrument-controls {
display: grid;
grid-template-columns: repeat(8, 1fr);
gap: 0.5em;
font-size: 0.8em;
margin-bottom: 1em;
}
.instrument-controls > div {
display: flex;
flex-direction: column;
background: #222;
padding: 0.4em;
border-radius: 3px;
}
label {
font-size: 0.75em;
margin-bottom: 0.2em;
}
</style>
</head>
<body>
<h1>Minimal Chiptune Tracker</h1>
<div class="controls">
<label for="bpm">BPM: <input type="number" id="bpm" min="30" max="300" value="120" /></label>
<label for="tracks">Tracks: <input type="number" id="tracks" min="1" max="4" value="2" /></label>
<label for="rowsPerTrack">Rows per track (instruments): <input type="number" id="rowsPerTrack" min="1" max="4" value="2" /></label>
<label for="rowsPerPattern">Rows per pattern: <input type="number" id="rowsPerPattern" min="4" max="64" value="16" step="4"/></label>
<button id="applySettings">Apply settings</button>
<button id="playBtn">Play</button>
<button id="stopBtn" disabled>Stop</button>
</div>
<div id="instrumentsArea"></div>
<div class="grid-container">
<table class="pattern-table" id="patternTable"></table>
</div>
<h3>Pattern data sharing</h3>
<textarea id="patternData" placeholder="Pattern data string"></textarea>
<br />
<button id="copyPattern">Copy Pattern Data</button>
<button id="loadPattern">Load Pattern Data</button>
<script>
(() => {
const notes = [
"C-0", "C#0","D-0", "D#0","E-0","F-0","F#0","G-0","G#0","A-0","A#0","B-0",
"C-1", "C#1","D-1", "D#1","E-1","F-1","F#1","G-1","G#1","A-1","A#1","B-1",
"C-2",
];
// Map note name -> freq (A4=440 tuned, C0 = 16.35 Hz base)
const noteToFreq = {};
(function buildNoteFreqMap(){
// A4 = 440Hz is note number 69 (MIDI)
// We'll compute freq for each note name e.g. C-0 = MIDI 12
const baseMidi = 12; // C0 midi
const baseFreq = 16.3516; // C0 freq
for(let i=0; i<notes.length; i++){
// formula freq = 440 * 2^( (midi - 69)/12)
const midiNum = baseMidi + i;
const f = 440 * Math.pow(2, (midiNum - 69)/12);
noteToFreq[notes[i]] = f;
}
})();
// Synth configuration
let tracks = 2;
let rowsPerTrack = 2; // instruments per track
let rowsPerPattern = 16; // pattern length
let bpm = 120;
// Pattern data format:
// pattern[track][row][step] = {note, instrumentIndex, volume}
// For simplicity instrumentIndex = row in track
// Pattern data storage
let pattern = [];
// Synth instrument params
// instrumentParams[track][instrumentRow]
// {attack, decay, sustain, release, fmAmount, detuneCents, filterCutoffHz}
let instrumentParams = [];
// UI elements
const bpmInput = document.getElementById("bpm");
const tracksInput = document.getElementById("tracks");
const rowsPerTrackInput = document.getElementById("rowsPerTrack");
const rowsPerPatternInput = document.getElementById("rowsPerPattern");
const applySettingsBtn = document.getElementById("applySettings");
const patternTable = document.getElementById("patternTable");
const instrumentsArea = document.getElementById("instrumentsArea");
const playBtn = document.getElementById("playBtn");
const stopBtn = document.getElementById("stopBtn");
const patternDataArea = document.getElementById("patternData");
const copyPatternBtn = document.getElementById("copyPattern");
const loadPatternBtn = document.getElementById("loadPattern");
// Audio context
let AudioContextClass = window.AudioContext || window.webkitAudioContext;
let audioCtx = null;
// Playback management
let playbackTimer = null;
let currentStep = 0;
// Helper: clamp
const clamp = (v,min,max) => Math.min(max, Math.max(min,v));
// Default instrument params
function defaultInstrument(){
return {
attack: 0.01,
decay: 0.1,
sustain: 0.5,
release: 0.1,
fmAmount: 0,
detuneCents: 0,
filterCutoff: 1000
};
}
// Initialize or reset pattern and params
function initData(){
pattern = [];
instrumentParams = [];
for(let t=0; t<tracks; t++){
pattern[t] = [];
instrumentParams[t] = [];
for(let r=0; r<rowsPerTrack; r++){
instrumentParams[t][r] = defaultInstrument();
}
for(let step=0; step<rowsPerPattern; step++){
pattern[t][step] = [];
for(let r=0; r<rowsPerTrack; r++){
// default note, instrument index, vol
pattern[t][step][r] = {note:"---", volume:1};
}
}
}
}
// Build pattern input table UI
function buildPatternTable(){
patternTable.innerHTML = "";
// Table headers
const thead = document.createElement("thead");
let headRow = document.createElement("tr");
headRow.appendChild(document.createElement("th")); // empty corner cell
for(let t=0; t<tracks; t++){
let th = document.createElement("th");
th.colSpan = rowsPerTrack;
th.style.border = "2px solid #666";
th.textContent = "Track " + (t+1);
headRow.appendChild(th);
}
thead.appendChild(headRow);
// Subheader: instrument rows per track
let subHeadRow = document.createElement("tr");
subHeadRow.appendChild(document.createElement("th")); // left corner
for(let t=0; t<tracks; t++){
for(let r=0; r<rowsPerTrack; r++){
let th = document.createElement("th");
th.textContent = "Inst "+(r+1);
th.title = `Track ${t+1} instrument ${r+1}`;
th.style.borderTop = "none";
subHeadRow.appendChild(th);
}
}
thead.appendChild(subHeadRow);
patternTable.appendChild(thead);
// Build table body
const tbody = document.createElement("tbody");
for(let step=0; step<rowsPerPattern; step++){
const tr = document.createElement("tr");
let stepCell = document.createElement("td");
stepCell.textContent = (step+1);
stepCell.style.borderRight = "2px solid #666";
tr.appendChild(stepCell);
for(let t=0; t<tracks; t++){
for(let r=0; r<rowsPerTrack; r++){
let td = document.createElement("td");
td.title = `Track ${t+1} Inst ${r+1} Step ${step+1}`;
td.contentEditable = "true";
td.spellcheck = false;
td.style.background = "#222";
td.style.color = "#eee";
// Init note text
td.textContent = pattern[t][step][r].note;
td.dataset.track = t;
td.dataset.step = step;
td.dataset.row = r;
td.addEventListener("input", e=>{
let val = td.textContent.toUpperCase().trim();
// Validate note
if(val === "---" || notes.includes(val)){
pattern[t][step][r].note = val;
td.style.color = "#eee";
} else {
td.style.color = "#e55";
}
});
tr.appendChild(td);
}
}
tbody.appendChild(tr);
}
patternTable.appendChild(tbody);
}
// Build instrument controls UI
function buildInstrumentControls(){
instrumentsArea.innerHTML = "";
// We'll create controls per track per instrument
// Display in grid
const container = document.createElement("div");
container.className = "instrument-controls";
for(let t=0; t<tracks; t++){
for(let r=0; r<rowsPerTrack; r++){
const instDiv = document.createElement("div");
instDiv.style.border = "1px solid #444";
instDiv.style.borderRadius = "4px";
instDiv.style.padding = "4px";
const title = document.createElement("strong");
title.textContent = `T${t+1} Inst${r+1}`;
title.style.marginBottom = "0.3em";
instDiv.appendChild(title);
// Attack
const attackL = document.createElement("label");
attackL.textContent = "Attack s";
const attackI = document.createElement("input");
attackI.type = "number";
attackI.step = "0.01";
attackI.min = 0;
attackI.max = 2;
attackI.value = instrumentParams[t][r].attack;
attackI.addEventListener("change", e=>{
const v = clamp(parseFloat(attackI.value), 0, 2);
attackI.value = v;
instrumentParams[t][r].attack = v;
});
attackL.appendChild(attackI);
instDiv.appendChild(attackL);
// Decay
const decayL = document.createElement("label");
decayL.textContent = "Decay s";
const decayI = document.createElement("input");
decayI.type = "number";
decayI.step = "0.01";
decayI.min = 0;
decayI.max = 2;
decayI.value = instrumentParams[t][r].decay;
decayI.addEventListener("change", e=>{
const v = clamp(parseFloat(decayI.value), 0, 2);
decayI.value = v;
instrumentParams[t][r].decay = v;
});
decayL.appendChild(decayI);
instDiv.appendChild(decayL);
// Sustain
const sustainL = document.createElement("label");
sustainL.textContent = "Sustain (0-1)";
const sustainI = document.createElement("input");
sustainI.type = "number";
sustainI.step = "0.05";
sustainI.min = 0;
sustainI.max = 1;
sustainI.value = instrumentParams[t][r].sustain;
sustainI.addEventListener("change", e=>{
const v = clamp(parseFloat(sustainI.value), 0, 1);
sustainI.value = v;
instrumentParams[t][r].sustain = v;
});
sustainL.appendChild(sustainI);
instDiv.appendChild(sustainL);
// Release
const releaseL = document.createElement("label");
releaseL.textContent = "Release s";
const releaseI = document.createElement("input");
releaseI.type = "number";
releaseI.step = "0.01";
releaseI.min = 0;
releaseI.max = 2;
releaseI.value = instrumentParams[t][r].release;
releaseI.addEventListener("change", e=>{
const v = clamp(parseFloat(releaseI.value), 0, 2);
releaseI.value = v;
instrumentParams[t][r].release = v;
});
releaseL.appendChild(releaseI);
instDiv.appendChild(releaseL);
// FM Amount
const fmL = document.createElement("label");
fmL.textContent = "FM Amount (Hz)";
const fmI = document.createElement("input");
fmI.type = "number";
fmI.step = "0.5";
fmI.min = 0;
fmI.max = 1000;
fmI.value = instrumentParams[t][r].fmAmount;
fmI.addEventListener("change", e=>{
const v = clamp(parseFloat(fmI.value), 0, 1000);
fmI.value = v;
instrumentParams[t][r].fmAmount = v;
});
fmL.appendChild(fmI);
instDiv.appendChild(fmL);
// Detune cents
const detuneL = document.createElement("label");
detuneL.textContent = "Detune (cents)";
const detuneI = document.createElement("input");
detuneI.type = "number";
detuneI.step = "1";
detuneI.min = -100;
detuneI.max = 100;
detuneI.value = instrumentParams[t][r].detuneCents;
detuneI.addEventListener("change", e=>{
const v = clamp(parseFloat(detuneI.value), -100, 100);
detuneI.value = v;
instrumentParams[t][r].detuneCents = v;
});
detuneL.appendChild(detuneI);
instDiv.appendChild(detuneL);
// Filter cutoff Hz
const filterL = document.createElement("label");
filterL.textContent = "Filter cutoff Hz";
const filterI = document.createElement("input");
filterI.type = "number";
filterI.step = "10";
filterI.min = 200;
filterI.max = 8000;
filterI.value = instrumentParams[t][r].filterCutoff;
filterI.addEventListener("change", e=>{
const v = clamp(parseFloat(filterI.value), 200, 8000);
filterI.value = v;
instrumentParams[t][r].filterCutoff = v;
});
filterL.appendChild(filterI);
instDiv.appendChild(filterL);
container.appendChild(instDiv);
}
}
instrumentsArea.appendChild(container);
}
// Update pattern text table with current pattern values
function updatePatternTableFromData(){
const cells = patternTable.querySelectorAll("td[contenteditable='true']");
cells.forEach(td => {
let t = parseInt(td.dataset.track);
let step = parseInt(td.dataset.step);
let r = parseInt(td.dataset.row);
td.textContent = pattern[t][step][r].note;
});
}
// Serialize pattern and instrument params into string
// We will encode:
// bpm|tracks|rowsPerTrack|rowsPerPattern|
// pattern data as track-step-row:note
// instrument params as track-row:param=value,...
function serializeData(){
let res = [];
res.push(bpm);
res.push(tracks);
res.push(rowsPerTrack);
res.push(rowsPerPattern);
// pattern notes: flattened as t,s,r=note or '---'
// format: t-s-r=note
// joined by ,
let patternParts = [];
for(let t=0; t<tracks; t++){
for(let s=0; s<rowsPerPattern; s++){
for(let r=0; r<rowsPerTrack; r++){
patternParts.push(`${t}-${s}-${r}=${pattern[t][s][r].note}`);
}
}
}
res.push(patternParts.join(","));
// instrument params:
// format t-r=attack;decay;sustain;release;fm;detune;filter
let instrParts = [];
for(let t=0; t<tracks; t++){
for(let r=0; r<rowsPerTrack; r++){
const p = instrumentParams[t][r];
let str = `${t}-${r}=${p.attack.toFixed(3)};${p.decay.toFixed(3)};${p.sustain.toFixed(3)};${p.release.toFixed(3)};${p.fmAmount.toFixed(1)};${p.detuneCents.toFixed(1)};${p.filterCutoff.toFixed(0)}`;
instrParts.push(str);
}
}
res.push(instrParts.join(","));
return res.join("|");
}
// Deserialize and load pattern data string
function deserializeData(str){
try {
let parts = str.trim().split("|");
if(parts.length !== 6) return false;
bpm = parseInt(parts[0]);
tracks = parseInt(parts[1]);
rowsPerTrack = parseInt(parts[2]);
rowsPerPattern = parseInt(parts[3]);
if(isNaN(bpm) || isNaN(tracks) || isNaN(rowsPerTrack)|| isNaN(rowsPerPattern)) return false;
bpmInput.value = bpm;
tracksInput.value = tracks;
rowsPerTrackInput.value = rowsPerTrack;
rowsPerPatternInput.value = rowsPerPattern;
// init arrays
pattern = [];
instrumentParams = [];
for(let t=0; t<tracks; t++){
instrumentParams[t] = [];
pattern[t] = [];
for(let r=0; r<rowsPerTrack; r++){
instrumentParams[t][r] = defaultInstrument();
}
for(let s=0; s<rowsPerPattern; s++){
pattern[t][s] = [];
for(let r=0; r<rowsPerTrack; r++){
pattern[t][s][r] = {note:"---", volume:1};
}
}
}
// parse pattern data
const patternsStr = parts[4];
const patPairs = patternsStr.split(",");
for(let pair of patPairs){
let [key,val] = pair.split("=");
let [t,s,r] = key.split("-").map(x=>parseInt(x));
if(t < tracks && s < rowsPerPattern && r < rowsPerTrack && notes.includes(val) || val==="---"){
pattern[t][s][r].note = val;
}
}
// parse instrument params
const instrStr = parts[5];
const instrPairs = instrStr.split(",");
for(let pair of instrPairs){
let [key,val] = pair.split("=");
let [t,r] = key.split("-").map(x=>parseInt(x));
if(t < tracks && r < rowsPerTrack){
let p = val.split(";");
if(p.length === 7){
instrumentParams[t][r] = {
attack: parseFloat(p[0]),
decay: parseFloat(p[1]),
sustain: parseFloat(p[2]),
release: parseFloat(p[3]),
fmAmount: parseFloat(p[4]),
detuneCents: parseFloat(p[5]),
filterCutoff: parseInt(p[6])
};
}
}
}
buildInstrumentControls();
buildPatternTable();
updatePatternTableFromData();
bpmInput.value = bpm;
return true;
} catch(e){
return false;
}
}
// Play one step of the pattern
function playStep(step){
if(!audioCtx) return;
// Play notes in each track and instrument row for current step
for(let t=0; t<tracks; t++){
for(let r=0; r<rowsPerTrack; r++){
const note = pattern[t][step][r].note;
if(note === "---") continue;
if(!noteToFreq[note]) continue;
const freq = noteToFreq[note];
playNote(freq, instrumentParams[t][r]);
}
}
}
// Play a note using Web Audio API with given params
function playNote(freq, params){
const attack = params.attack;
const decay = params.decay;
const sustain = params.sustain;
const release = params.release;
const fmAmount = params.fmAmount;
const detuneCents = params.detuneCents;
const filterCutoff = params.filterCutoff;
const now = audioCtx.currentTime;
// Carrier oscillator (square wave)
const osc = audioCtx.createOscillator();
osc.type = "square";
osc.frequency.value = freq;
osc.detune.value = detuneCents;
// FM oscillator modulates carrier frequency
let fmOsc = null;
if(fmAmount > 0){
fmOsc = audioCtx.createOscillator();
fmOsc.type = "square";
fmOsc.frequency.value = freq * 2; // simple harmonic
const fmGain = audioCtx.createGain();
fmGain.gain.value = fmAmount;
fmOsc.connect(fmGain);
fmGain.connect(osc.frequency);
fmOsc.start(now);
fmOsc.stop(now + attack + decay + 0.3 + release);
}
// Filter
const filter = audioCtx.createBiquadFilter();
filter.type = "lowpass";
filter.frequency.setValueAtTime(filterCutoff, now);
// Gain envelope
const gainNode = audioCtx.createGain();
gainNode.gain.setValueAtTime(0.0001, now);
gainNode.gain.linearRampToValueAtTime(1.0, now + attack);
gainNode.gain.linearRampToValueAtTime(sustain, now + attack + decay);
// Keep sustain level until note off (simplified as fixed length)
// We'll schedule release after about 0.3s + release
gainNode.gain.setTargetAtTime(0.0001, now + attack + decay + 0.3, release);
// Connect graph: osc -> filter -> gain -> destination
osc.connect(filter);
filter.connect(gainNode);
gainNode.connect(audioCtx.destination);
osc.start(now);
osc.stop(now + attack + decay + 0.4 + release);
}
// Start playback loop
function startPlayback(){
if(!audioCtx){
audioCtx = new AudioContextClass();
}
if(audioCtx.state === 'suspended'){
audioCtx.resume();
}
currentStep = 0;
const intervalMs = (60 / bpm / 4) * 1000; // 16th note interval at bpm
playStep(currentStep);
currentStep++;
playbackTimer = setInterval(() => {
playStep(currentStep);
currentStep++;
if(currentStep >= rowsPerPattern) currentStep = 0;
}, intervalMs);
playBtn.disabled = true;
stopBtn.disabled = false;
}
// Stop playback loop
function stopPlayback(){
if(playbackTimer){
clearInterval(playbackTimer);
playbackTimer = null;
}
playBtn.disabled = false;
stopBtn.disabled = true;
}
// Apply settings button handler
applySettingsBtn.addEventListener("click", () => {
bpm = parseInt(bpmInput.value);
tracks = clamp(parseInt(tracksInput.value), 1, 4);
rowsPerTrack = clamp(parseInt(rowsPerTrackInput.value), 1, 4);
rowsPerPattern = clamp(parseInt(rowsPerPatternInput.value), 4, 64);
initData();
buildInstrumentControls();
buildPatternTable();
});
playBtn.addEventListener("click", () => {
bpm = clamp(parseInt(bpmInput.value), 30, 300);
startPlayback();
});
stopBtn.addEventListener("click", () => {
stopPlayback();
});
// Copy pattern data
copyPatternBtn.addEventListener("click", () => {
patternDataArea.value = serializeData();
patternDataArea.select();
document.execCommand('copy');
copyPatternBtn.textContent = "Copied!";
setTimeout(() => copyPatternBtn.textContent = "Copy Pattern Data", 1000);
});
// Load pattern data
loadPatternBtn.addEventListener("click", () => {
const loadStr = patternDataArea.value.trim();
if(deserializeData(loadStr)){
alert("Pattern loaded.");
} else {
alert("Invalid pattern data.");
}
});
// Initialize first time
initData();
buildInstrumentControls();
buildPatternTable();
})();
</script>
</body>
</html>
Open this file in a modern browser with Web Audio API support (Chrome, Firefox, Edge) and use the controls to compose very basic chiptune patterns.