(() => {
const AudioCtx = window.AudioContext || window.webkitAudioContext;
const audioCtx = new AudioCtx();
let bpm = 125;
let rowsPerPattern = 16;
let patternsPerTrack = 4;
let isPlaying = false;
let currentRow = 0;
let timerId;
// Simple note frequency map (A4 = 440Hz)
// For demo only: use 12-tone equal temperament, octave 4 default
const notesFreq = {
C: 261.63,
'C#': 277.18,
D: 293.66,
'D#': 311.13,
E: 329.63,
F: 349.23,
'F#': 369.99,
G: 392.00,
'G#': 415.30,
A: 440.00,
'A#': 466.16,
B: 493.88
};
function freqFromNote(noteStr) {
// example input: C4, D#5
if (!noteStr || noteStr === '-') return null;
const regex = /^([A-G]#?)(\d)$/;
const m = noteStr.match(regex);
if (!m) return null;
let [_, note, octaveStr] = m;
const octave = parseInt(octaveStr);
const baseFreq = notesFreq[note];
return baseFreq * Math.pow(2, octave - 4);
}
// Get form elements
const bpmInput = document.getElementById('bpm');
const rowsPerPatternInput = document.getElementById('rowsPerPattern');
const patternsPerTrackInput = document.getElementById('patternsPerTrack');
const oscTypeSelect = document.getElementById('osc-type');
const volumeSlider = document.getElementById('volume');
const detuneSlider = document.getElementById('detune');
const attackInput = document.getElementById('attack');
const decayInput = document.getElementById('decay');
const sustainInput = document.getElementById('sustain');
const releaseInput = document.getElementById('release');
const playBtn = document.getElementById('play');
const stopBtn = document.getElementById('stop');
const shareBtn = document.getElementById('share');
const patternEditor = document.getElementById('pattern-editor');
// Helper: adsr envelope
function applyADSR(gainNode, startTime, dur) {
const attack = parseFloat(attackInput.value);
const decay = parseFloat(decayInput.value);
const sustain = parseFloat(sustainInput.value);
const release = parseFloat(releaseInput.value);
const maxGain = 1.0;
const sustainLevel = sustain * maxGain;
gainNode.gain.cancelScheduledValues(startTime);
gainNode.gain.setValueAtTime(0, startTime);
gainNode.gain.linearRampToValueAtTime(maxGain, startTime + attack);
gainNode.gain.linearRampToValueAtTime(sustainLevel, startTime + attack + decay);
gainNode.gain.setValueAtTime(sustainLevel, startTime + dur - release);
gainNode.gain.linearRampToValueAtTime(0, startTime + dur);
}
// Play single note
function playNote(noteStr, startTime, duration) {
const freq = freqFromNote(noteStr);
if (!freq) return;
// Create oscillator and gain node
const osc = audioCtx.createOscillator();
const gainNode = audioCtx.createGain();
osc.type = oscTypeSelect.value;
osc.frequency.setValueAtTime(freq, startTime);
const detune = parseInt(detuneSlider.value);
osc.detune.setValueAtTime(detune, startTime);
gainNode.gain.setValueAtTime(0, startTime);
osc.connect(gainNode);
gainNode.connect(audioCtx.destination);
osc.start(startTime);
osc.stop(startTime + duration);
applyADSR(gainNode, startTime, duration);
}
// Parse pattern data textarea into array of rows
// Each row: [note, instrument, volume, detune]
function parsePatterns() {
const lines = patternEditor.value.trim().split('\n');
let patternData = [];
for (let line of lines) {
const parts = line.trim().split(/\s+/);
if (parts.length < 1) {
patternData.push({ note: '-', instrument: '0', volume: '0', detune: '0' });
continue;
}
const [note, instrument, volume, detune] = parts;
patternData.push({
note: note || '-',
instrument: instrument || '0',
volume: volume || '0',
detune: detune || '0',
});
}
return patternData;
}
function scheduleTrack() {
if (!isPlaying) return;
const playbackBpm = parseInt(bpmInput.value);
const rowsPP = parseInt(rowsPerPatternInput.value);
const patternData = parsePatterns();
const beatDuration = 60 / playbackBpm; // seconds per beat
// For chiptune trackers: 4 rows per beat typical, so row duration:
const rowDuration = beatDuration / 4;
const now = audioCtx.currentTime;
// Schedule next N rows, then loop
for (let i = 0; i < rowsPP; i++) {
const idx = (currentRow + i) % patternData.length;
const row = patternData[idx];
if (row.note !== '-' && row.note !== '---') {
playNote(row.note, now + i * rowDuration, rowDuration * 0.9);
}
}
currentRow = (currentRow + rowsPP) % patternData.length;
timerId = setTimeout(scheduleTrack, rowsPP * rowDuration * 1000);
}
function startPlayback() {
if (!audioCtx) return;
if (audioCtx.state === 'suspended') {
audioCtx.resume();
}
if (isPlaying) return;
isPlaying = true;
currentRow = 0;
scheduleTrack();
}
function stopPlayback() {
if (!isPlaying) return;
isPlaying = false;
clearTimeout(timerId);
}
playBtn.addEventListener('click', startPlayback);
stopBtn.addEventListener('click', stopPlayback);
// Keyboard shortcuts: space = play/pause
window.addEventListener('keydown', (e) => {
if (e.code === 'Space') {
e.preventDefault();
if (isPlaying) stopPlayback();
else startPlayback();
}
});
// Share song: encode textarea + settings into URL hash
shareBtn.addEventListener('click', () => {
const state = {
bpm: bpmInput.value,
rowsPerPattern: rowsPerPatternInput.value,
patternsPerTrack: patternsPerTrackInput.value,
oscType: oscTypeSelect.value,
volume: volumeSlider.value,
detune: detuneSlider.value,
attack: attackInput.value,
decay: decayInput.value,
sustain: sustainInput.value,
release: releaseInput.value,
pattern: patternEditor.value,
};
const encoded = encodeURIComponent(btoa(JSON.stringify(state)));
window.location.hash = encoded;
alert('Song state copied to url hash! Share the entire URL');
});
// On page load, decode URL hash and load
function loadFromHash() {
const hash = window.location.hash.substr(1);
if (!hash) return;
try {
const str = atob(decodeURIComponent(hash));
const state = JSON.parse(str);
bpmInput.value = state.bpm || bpmInput.value;
rowsPerPatternInput.value = state.rowsPerPattern || rowsPerPatternInput.value;
patternsPerTrackInput.value = state.patternsPerTrack || patternsPerTrackInput.value;
oscTypeSelect.value = state.oscType || oscTypeSelect.value;
volumeSlider.value = state.volume || volumeSlider.value;
detuneSlider.value = state.detune || detuneSlider.value;
attackInput.value = state.attack || attackInput.value;
decayInput.value = state.decay || decayInput.value;
sustainInput.value = state.sustain || sustainInput.value;
releaseInput.value = state.release || releaseInput.value;
patternEditor.value = state.pattern || patternEditor.value;
} catch (e) {
console.warn('Invalid or corrupt song data in URL');
}
}
loadFromHash();
})();