html
<!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 {
font-family: monospace, monospace;
background: #222;
color: #eee;
margin: 0;
padding: 0;
user-select: none;
}
#app {
display: flex;
flex-direction: column;
height: 100vh;
}
header {
background: #111;
padding: 0.5em 1em;
display: flex;
align-items: center;
}
header > * {
margin-right: 1em;
}
button {
background: #333;
color: #eee;
border: none;
padding: 0.3em 0.7em;
cursor: pointer;
}
button:hover {
background: #444;
}
input[type=number], input[type=text], select {
background: #222;
border: 1px solid #444;
color: #eee;
padding: 0.2em 0.4em;
width: 5em;
user-select: text;
}
main {
flex: 1;
display: flex;
overflow: hidden;
}
#sequencer {
flex: 1;
overflow: auto;
background: #222;
}
table {
border-collapse: collapse;
width: 100%;
font-size: 0.9rem;
}
th, td {
border: 1px solid #444;
text-align: center;
padding: 0.1em 0.3em;
min-width: 2em;
}
th {
background: #333;
position: sticky;
top: 0;
z-index: 2;
}
td.pattern-cell {
cursor: pointer;
}
td.pattern-cell.selected {
background: #5577cc;
}
#instrument-panel {
width: 300px;
background: #111;
padding: 0.5em;
overflow-y: auto;
}
.instrument {
border: 1px solid #444;
margin-bottom: 1em;
padding: 0.5em;
background: #222;
}
.instrument h3 {
margin: 0 0 0.3em;
font-size: 1.1em;
}
label {
display: block;
margin: 0.2em 0 0.1em;
font-size: 0.9em;
}
input[type=range] {
width: 100%;
}
#share-link {
width: 100%;
background: #222;
border: 1px solid #444;
color: #eee;
margin-top: 0.5em;
padding: 0.2em;
font-family: monospace, monospace;
font-size: 0.9em;
}
#status {
flex-grow: 1;
text-align: right;
color: #aaa;
}
</style>
</head>
<body>
<div id="app">
<header>
<button id="playBtn">Play</button>
<button id="stopBtn">Stop</button>
<label>
BPM:
<input type="number" id="bpmInput" min="30" max="300" value="120" />
</label>
<button id="loopBtn">Loop</button>
<button id="copyPatternBtn" title="Copy Pattern">Copy</button>
<button id="pastePatternBtn" title="Paste Pattern">Paste</button>
<button id="dupPatternBtn" title="Duplicate Pattern">Duplicate</button>
<button id="delPatternBtn" title="Delete Pattern">Delete</button>
<button id="shareBtn" title="Generate Share URL">Share</button>
<div id="status"></div>
</header>
<main>
<div id="sequencer"></div>
<div id="instrument-panel"></div>
</main>
</div>
<script>
(() => {
// Basic tracker/sequencer data structures:
const NOTES = ['C-4', 'C#4', 'D-4', 'D#4', 'E-4', 'F-4', 'F#4', 'G-4', 'G#4', 'A-4', 'A#4', 'B-4',
'C-5', 'C#5', 'D-5', 'D#5', 'E-5', 'F-5', 'F#5', 'G-5', 'G#5', 'A-5', 'A#5', 'B-5'];
// Using 24 notes in 2 octaves for example.
// --- Settings ---
const PATTERNS_COUNT = 8;
const ROWS_PER_PATTERN = 16;
const INSTRUMENTS_COUNT = 3;
// State:
let song = {
bpm: 120,
loop: false,
patterns: [], // each: { rows: [ {note, instrument, volume, ...}, ... ]}
sequence: [], // pattern order. length 16 for example
instruments: [], // Instrument objects
};
// Temporary buffer for copy/paste:
let copiedPattern = null;
// Audio context & synth
const AudioCtx = window.AudioContext || window.webkitAudioContext;
let audioCtx = null;
// Scheduling variables
let playing = false;
let currentStep = 0;
let currentSeqPos = 0;
let timerID = null;
let nextNoteTime = 0;
// Instruments definition
// For each instrument: oscillator type (custom waveform) + ADSR + volume + detune + filter + noise
class Instrument {
constructor(index) {
this.id = index;
this.name = 'Instr ' + (index + 1);
this.oscType = 'square'; // 'sine', 'square', 'sawtooth', 'triangle', 'custom'
this.volume = 0.4;
this.detune = 0; // cents
this.adsr = {attack: 0.01, decay: 0.05, sustain: 0.3, release: 0.1};
this.filter = {type: 'lowpass', frequency: 1200, Q:1};
this.noise = false;
// For custom waveform, can be added later
}
}
// Pattern structure:
// Array of ROWS_PER_PATTERN rows
// Each row: Array of channels with note data:
// data example per channel: {noteIndex, instrumentIndex, volume}
// For simplicity: 1 channel = 1 instrument note per row
// Let's fix channels == instruments count (one channel per instrument)
// Initialize song data:
function initSong() {
song.bpm = 120;
song.loop = false;
song.patterns = [];
song.sequence = new Array(16).fill(0);
song.instruments = [];
for(let i=0;i<INSTRUMENTS_COUNT;++i){
song.instruments.push(new Instrument(i));
}
// create empty patterns
for(let p=0; p<PATTERNS_COUNT; ++p){
let pattern = [];
for(let r=0; r<ROWS_PER_PATTERN; ++r){
// row = array of length INSTRUMENTS_COUNT for each channel
let row = [];
for(let c=0; c<INSTRUMENTS_COUNT; ++c){
row.push({note: null, volume: 0});
}
pattern.push(row);
}
song.patterns.push(pattern);
}
}
// UI elements:
const playBtn = document.getElementById('playBtn');
const stopBtn = document.getElementById('stopBtn');
const bpmInput = document.getElementById('bpmInput');
const loopBtn = document.getElementById('loopBtn');
const sequencerDiv = document.getElementById('sequencer');
const instrumentPanel = document.getElementById('instrument-panel');
const copyPatternBtn = document.getElementById('copyPatternBtn');
const pastePatternBtn = document.getElementById('pastePatternBtn');
const dupPatternBtn = document.getElementById('dupPatternBtn');
const delPatternBtn = document.getElementById('delPatternBtn');
const shareBtn = document.getElementById('shareBtn');
const statusDiv = document.getElementById('status');
// Current editing state:
let editingPatternIndex = 0;
let editingRow = 0;
let selection = {pattern: 0};
// Helpers:
function noteToFreq(noteIndex){
// Assuming A4=440Hz at note index for C-4 = note 0 (C4)
// Let's base on C4 = 261.63Hz at index 0
if(noteIndex === null) return 0;
let baseFreq = 261.63;
let freq = baseFreq * Math.pow(2, noteIndex / 12);
return freq;
}
// --- Audio synth ---
function playNote(instrument, freq, startTime, duration){
if(freq === 0) return;
let oscType = instrument.oscType;
if(!audioCtx) audioCtx = new AudioCtx();
// create gain for ADSR
let gainNode = audioCtx.createGain();
gainNode.gain.setValueAtTime(0, startTime);
// create oscillator or noise node
let source;
let isNoise = instrument.noise;
if(isNoise){
// Create noise buffer source
let bufferSize = audioCtx.sampleRate * duration;
let buffer = audioCtx.createBuffer(1, bufferSize, audioCtx.sampleRate);
let data = buffer.getChannelData(0);
for(let i=0; i<data.length; ++i){
data[i] = Math.random() * 2 -1;
}
source = audioCtx.createBufferSource();
source.buffer = buffer;
source.loop = true;
source.start(startTime);
} else {
source = audioCtx.createOscillator();
if(oscType === 'custom'){
// You can create custom wave here (sine + harmonics)
let real = new Float32Array([0, 1, 0.5, 0.3]);
let imag = new Float32Array(real.length);
let wave = audioCtx.createPeriodicWave(real, imag);
source.setPeriodicWave(wave);
} else {
source.type = oscType;
}
source.frequency.setValueAtTime(freq, startTime);
source.detune.setValueAtTime(instrument.detune, startTime);
source.start(startTime);
}
// Filter
let filter = audioCtx.createBiquadFilter();
filter.type = instrument.filter.type;
filter.frequency.setValueAtTime(instrument.filter.frequency, startTime);
filter.Q.setValueAtTime(instrument.filter.Q, startTime);
// Connect nodes
source.connect(filter);
filter.connect(gainNode);
gainNode.connect(audioCtx.destination);
// ADSR envelope
let a = instrument.adsr.attack;
let d = instrument.adsr.decay;
let s = instrument.adsr.sustain;
let r = instrument.adsr.release;
gainNode.gain.linearRampToValueAtTime(0, startTime);
gainNode.gain.linearRampToValueAtTime(instrument.volume, startTime + a);
gainNode.gain.linearRampToValueAtTime(instrument.volume * s, startTime + a + d);
let releaseStart = startTime + duration;
gainNode.gain.linearRampToValueAtTime(0, releaseStart + r);
// Stop source after envelope ends
source.stop(releaseStart + r + 0.02);
}
// --- Sequencer UI and logic ---
// Draw sequence grid: sequence order & patterns grid
function drawSequence(){
// Clear sequencer div
sequencerDiv.innerHTML = '';
// Draw pattern selector line (sequence order)
const seqCount = song.sequence.length;
// Container for sequence row and pattern grid below
let container = document.createElement('div');
container.style.display = 'flex';
container.style.flexDirection = 'column';
// Append
// Sequence row
let seqRow = document.createElement('div');
seqRow.style.display = 'flex';
seqRow.style.marginBottom = '0.4em';
for(let i=0; i<seqCount; ++i){
let btn = document.createElement('button');
btn.textContent = 'P' + song.sequence[i];
btn.style.flex = '1 1 0';
btn.style.fontSize = '0.8em';
btn.style.padding = '0.3em 0.5em';
if(i === currentSeqPos){
btn.style.background = '#5577cc';
btn.style.color = '#fff';
}
btn.addEventListener('click', () => {
if(!playing) {
currentSeqPos = i;
editingPatternIndex = song.sequence[i];
drawSequence();
}
});
seqRow.appendChild(btn);
}
container.appendChild(seqRow);
// Pattern grid - show current editing pattern rows & instruments (channels)
let tbl = document.createElement('table');
let thead = document.createElement('thead');
let trhead = document.createElement('tr');
trhead.appendChild(document.createElement('th')); // empty corner
for(let c=0; c<INSTRUMENTS_COUNT; ++c){
let th = document.createElement('th');
th.textContent = song.instruments[c].name;
trhead.appendChild(th);
}
thead.appendChild(trhead);
tbl.appendChild(thead);
let tbody = document.createElement('tbody');
let pattern = song.patterns[editingPatternIndex];
for(let r=0; r<ROWS_PER_PATTERN; ++r){
let tr = document.createElement('tr');
let rowNumTd = document.createElement('td');
rowNumTd.textContent = r+1;
tr.appendChild(rowNumTd);
for(let c=0; c<INSTRUMENTS_COUNT; ++c){
let cell = document.createElement('td');
cell.className = 'pattern-cell';
let noteObj = pattern[r][c];
let noteText = noteObj.note === null ? '...' : NOTES[noteObj.note];
cell.textContent = noteText;
if(r === editingRow){
cell.style.background = '#4466aa';
}
cell.addEventListener('click', () => {
let newNoteIndex = noteObj.note === null ? 0 : (noteObj.note +1) % NOTES.length;
noteObj.note = newNoteIndex;
drawSequence();
});
tr.appendChild(cell);
}
tbody.appendChild(tr);
}
tbl.appendChild(tbody);
container.appendChild(tbl);
sequencerDiv.appendChild(container);
}
// --- Playback Scheduler ---
const lookahead = 25.0; // ms
const scheduleAheadTime = 0.1; // seconds
function nextStep() {
// advance currentStep
currentStep++;
if(currentStep >= ROWS_PER_PATTERN){
currentStep = 0;
currentSeqPos++;
if(currentSeqPos >= song.sequence.length){
if(song.loop) currentSeqPos = 0;
else stop();
}
editingPatternIndex = song.sequence[currentSeqPos];
}
}
function scheduleNote(step, time){
if(!playing) return;
let pattern = song.patterns[editingPatternIndex];
if(!pattern) return;
let row = pattern[step];
for(let c=0; c<INSTRUMENTS_COUNT; ++c){
let noteObj = row[c];
if(noteObj && noteObj.note !== null){
let freq = noteToFreq(noteObj.note);
let instr = song.instruments[c];
let noteDuration = 60 / song.bpm / 4; // 16th note duration approx
playNote(instr, freq, time, noteDuration);
}
}
}
function scheduler() {
if(!playing) return;
while(nextNoteTime < audioCtx.currentTime + scheduleAheadTime){
scheduleNote(currentStep, nextNoteTime);
nextStep();
nextNoteTime += 60.0 / song.bpm / 4; // 16th note timing
drawSequence(); // update UI for current step highlight
}
timerID = setTimeout(scheduler, lookahead);
}
function play() {
if(!audioCtx) audioCtx = new AudioCtx();
playing = true;
currentStep = 0;
currentSeqPos = 0;
editingPatternIndex = song.sequence[currentSeqPos];
nextNoteTime = audioCtx.currentTime + 0.05;
scheduler();
statusDiv.textContent = 'Playing...';
}
function stop() {
playing = false;
if(timerID) clearTimeout(timerID);
statusDiv.textContent = 'Stopped';
drawSequence();
}
// --- Event handlers ---
playBtn.addEventListener('click', () => {
if(!playing) play();
});
stopBtn.addEventListener('click', () => {
if(playing) stop();
});
bpmInput.addEventListener('change', (e) => {
let val = +e.target.value;
if(val >= 30 && val <= 300){
song.bpm = val;
}
});
loopBtn.addEventListener('click', () => {
song.loop = !song.loop;
loopBtn.style.background = song.loop ? '#5577cc' : null;
});
copyPatternBtn.addEventListener('click', () => {
copiedPattern = JSON.parse(JSON.stringify(song.patterns[editingPatternIndex]));
statusDiv.textContent = 'Pattern copied.';
});
pastePatternBtn.addEventListener('click', () => {
if(copiedPattern){
song.patterns[editingPatternIndex] = JSON.parse(JSON.stringify(copiedPattern));
drawSequence();
statusDiv.textContent = 'Pattern pasted.';
}
});
dupPatternBtn.addEventListener('click', () => {
if(song.patterns.length >= 64){
statusDiv.textContent = 'Max patterns reached.';
return;
}
let newPattern = JSON.parse(JSON.stringify(song.patterns[editingPatternIndex]));
song.patterns.push(newPattern);
song.sequence.push(song.patterns.length-1);
statusDiv.textContent = 'Pattern duplicated.';
});
delPatternBtn.addEventListener('click', () => {
if(song.patterns.length <= 1) {
statusDiv.textContent = 'Cannot delete last pattern.';
return;
}
song.patterns.splice(editingPatternIndex, 1);
// update sequence to not reference deleted pattern:
song.sequence = song.sequence.map(patIndex => patIndex >= editingPatternIndex ? patIndex-1 : patIndex);
// Clamp editingPatternIndex:
editingPatternIndex = 0;
drawSequence();
statusDiv.textContent = 'Pattern deleted.';
});
// Instrument Panel UI
function drawInstrumentPanel(){
instrumentPanel.innerHTML = '';
song.instruments.forEach((instr, i) => {
let container = document.createElement('div');
container.className = 'instrument';
let title = document.createElement('h3');
title.textContent = instr.name;
container.appendChild(title);
// Oscillator Type
let oscLabel = document.createElement('label');
oscLabel.textContent = 'Oscillator:';
container.appendChild(oscLabel);
let oscSelect = document.createElement('select');
['sine','square','sawtooth','triangle','custom'].forEach(type => {
let option = document.createElement('option');
option.value = type;
option.textContent = type;
if(type === instr.oscType) option.selected = true;
oscSelect.appendChild(option);
});
oscSelect.addEventListener('change', () => {
instr.oscType = oscSelect.value;
});
container.appendChild(oscSelect);
// Volume
let volLabel = document.createElement('label');
volLabel.textContent = 'Volume: ' + instr.volume.toFixed(2);
container.appendChild(volLabel);
let volRange = document.createElement('input');
volRange.type = 'range';
volRange.min = 0; volRange.max = 1; volRange.step = 0.01;
volRange.value = instr.volume;
volRange.addEventListener('input', () => {
instr.volume = +volRange.value;
volLabel.textContent = 'Volume: ' + instr.volume.toFixed(2);
});
container.appendChild(volRange);
// Detune
let detLabel = document.createElement('label');
detLabel.textContent = 'Detune (cents): ' + instr.detune.toFixed(0);
container.appendChild(detLabel);
let detRange = document.createElement('input');
detRange.type = 'range';
detRange.min = -100; detRange.max = 100; detRange.step = 1;
detRange.value = instr.detune;
detRange.addEventListener('input', () => {
instr.detune = +detRange.value;
detLabel.textContent = 'Detune (cents): ' + instr.detune.toFixed(0);
});
container.appendChild(detRange);
// ADSR sliders:
['attack','decay','sustain','release'].forEach(param => {
let lab = document.createElement('label');
lab.textContent = param.charAt(0).toUpperCase() + param.slice(1) + ': ' + instr.adsr[param].toFixed(2);
container.appendChild(lab);
let rng = document.createElement('input');
rng.type = 'range';
if(param==='sustain'){
rng.min = 0; rng.max = 1; rng.step = 0.05;
} else {
rng.min = 0; rng.max = 1; rng.step = 0.01;
}
rng.value = instr.adsr[param];
rng.addEventListener('input', () => {
instr.adsr[param] = +rng.value;
lab.textContent = param.charAt(0).toUpperCase() + param.slice(1) + ': ' + instr.adsr[param].toFixed(2);
});
container.appendChild(rng);
});
// Filter (freq)
let filtTypeLabel = document.createElement('label');
filtTypeLabel.textContent = 'Filter Type:';
container.appendChild(filtTypeLabel);
let filtTypeSel = document.createElement('select');
['lowpass','highpass','bandpass','notch','allpass','peaking','lowshelf','highshelf'].forEach(type => {
let option = document.createElement('option');
option.value = type;
option.textContent = type;
if(type === instr.filter.type) option.selected = true;
filtTypeSel.appendChild(option);
});
filtTypeSel.addEventListener('change', () => {
instr.filter.type = filtTypeSel.value;
});
container.appendChild(filtTypeSel);
let filtFreqLabel = document.createElement('label');
filtFreqLabel.textContent = 'Filter Frequency: ' + instr.filter.frequency;
container.appendChild(filtFreqLabel);
let filtFreqRange = document.createElement('input');
filtFreqRange.type = 'range';
filtFreqRange.min = 100; filtFreqRange.max = 8000; filtFreqRange.step = 10;
filtFreqRange.value = instr.filter.frequency;
filtFreqRange.addEventListener('input', () => {
instr.filter.frequency = +filtFreqRange.value;
filtFreqLabel.textContent = 'Filter Frequency: ' + instr.filter.frequency;
});
container.appendChild(filtFreqRange);
let filtQLabel = document.createElement('label');
filtQLabel.textContent = 'Filter Q: ' + instr.filter.Q.toFixed(2);
container.appendChild(filtQLabel);
let filtQRange = document.createElement('input');
filtQRange.type = 'range';
filtQRange.min = 0; filtQRange.max = 20; filtQRange.step = 0.1;
filtQRange.value = instr.filter.Q;
filtQRange.addEventListener('input', () => {
instr.filter.Q = +filtQRange.value;
filtQLabel.textContent = 'Filter Q: ' + instr.filter.Q.toFixed(2);
});
container.appendChild(filtQRange);
// Noise toggle
let noiseLabel = document.createElement('label');
noiseLabel.textContent = 'Noise: ';
let noiseCheck = document.createElement('input');
noiseCheck.type = 'checkbox';
noiseCheck.checked = instr.noise;
noiseCheck.addEventListener('change', () => {
instr.noise = noiseCheck.checked;
});
noiseLabel.appendChild(noiseCheck);
container.appendChild(noiseLabel);
instrumentPanel.appendChild(container);
});
}
// Share URL encoding/decoding (basic JSON URI encoded)
function encodeSong() {
let data = {
bpm: song.bpm,
loop: song.loop,
sequence: song.sequence,
instruments: song.instruments,
patterns: song.patterns,
};
return encodeURIComponent(btoa(JSON.stringify(data)));
}
function decodeSong(encoded) {
try {
let jsonStr = atob(decodeURIComponent(encoded));
let data = JSON.parse(jsonStr);
song.bpm = data.bpm;
song.loop = data.loop;
song.sequence = data.sequence;
song.instruments = data.instruments.map((instr,i)=>{
let ins = new Instrument(i);
Object.assign(ins, data.instruments[i]);
return ins;
});
song.patterns = data.patterns;
return true;
} catch(e){
return false;
}
}
// Share button handler
shareBtn.addEventListener('click', () => {
let encoded = encodeSong();
let url = window.location.origin + window.location.pathname + '#song=' + encoded;
navigator.clipboard.writeText(url).then(() => {
statusDiv.textContent = 'Song URL copied to clipboard.';
}).catch(() => {
// fallback: show prompt
prompt('Song URL:', url);
});
});
// On load, check URL for song data
function loadFromURL(){
let hash = window.location.hash;
if(hash.startsWith('#song=')){
let encoded = hash.substr(6);
if(decodeSong(encoded)){
statusDiv.textContent = 'Song loaded from URL.';
bpmInput.value = song.bpm;
loopBtn.style.background = song.loop ? '#5577cc' : null;
} else {
statusDiv.textContent = 'Failed to load song data from URL.';
}
}
}
// Keyboard shortcuts for pattern row navigation
window.addEventListener('keydown', (e) => {
if(e.target.tagName === 'INPUT' || e.target.tagName === 'SELECT' || e.target.isContentEditable) return;
switch(e.key) {
case 'ArrowDown':
editingRow = (editingRow +1) % ROWS_PER_PATTERN;
drawSequence();
e.preventDefault();
break;
case 'ArrowUp':
editingRow = (editingRow -1 + ROWS_PER_PATTERN) % ROWS_PER_PATTERN;
drawSequence();
e.preventDefault();
break;
case 'ArrowRight':
editingPatternIndex = (editingPatternIndex +1) % song.patterns.length;
drawSequence();
e.preventDefault();
break;
case 'ArrowLeft':
editingPatternIndex = (editingPatternIndex -1 + song.patterns.length) % song.patterns.length;
drawSequence();
e.preventDefault();
break;
case ' ':
if(playing) stop();
else play();
e.preventDefault();
break;
}
});
// Initialization
initSong();
drawSequence();
drawInstrumentPanel();
loadFromURL();
})();
</script>
</body>
</html>
If you want me to add a feature or make it smaller/more complex, please ask. This is a full working HTML file you can open in modern browsers.