Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

html css js chiptune tracker pattern sequencer bpm chord size patterns rows per pattern…

  1. User

    html css js chiptune tracker pattern sequencer bpm chord size patterns rows per pattern synth per instrument custom waveform osc volume detune adsr filter noise share song shortcuts dupe delete copy paste pattern loop "/#" no demo

  2. Assistant

    It sounds like you want a small web-based chiptune tracker / pattern sequencer built with HTML, CSS, and JavaScript, featuring:

    • BPM control
    • Patterns, pattern rows
    • Multiple instruments (synths) with custom waveforms (oscillators)
    • Per instrument volume, detune, ADSR envelope, filter, noise
    • Pattern editing: add/delete/duplicate/copy/paste patterns
    • Chords in patterns
    • Looping patterns
    • Keyboard shortcuts for edits
    • Share song (URL/hash or similar)
    • No external demo, just code

    Here’s a minimal but functional starting point for a chiptune tracker that meets your requirements. This example uses Web Audio API for the synths and basic UI for pattern editing.


    How it works in brief

    • You have several patterns, each pattern is a grid: rows × channels (instruments)
    • Each cell can have a note (C-4, D#4 etc.) or chord (comma separated notes)
    • Playback engine uses Web Audio to play notes per pattern row following BPM
    • You can add/delete/duplicate/copy/paste patterns
    • You can edit ADSR/filter/detune/volume per instrument
    • Custom waveforms per instrument selectable from standard waveforms or noise
    • Keyboard shortcuts and UI buttons for quick pattern editing
    • URL hash serializes the song state so you can share or reload

    Code

    Open with an HTML5 browser, edit patterns, press play.

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Chiptune Tracker / Pattern Sequencer</title>
    <style>
      body {
        font-family: monospace;
        background: #222;
        color: #ddd;
        margin: 0; padding: 0;
        user-select: none;
      }
      #container {
        display: flex;
        flex-direction: column;
        min-height: 100vh;
        padding: 10px;
      }
      #controls {
        display: flex;
        justify-content: space-between;
        padding-bottom: 8px;
      }
      button, select, input[type=number] {
        font-family: monospace;
        font-size: 14px;
        margin-right: 8px;
        background: #333;
        border: 1px solid #555;
        color: #ddd;
        padding: 6px 12px;
        cursor: pointer;
      }
      button:hover, select:hover, input[type=number]:hover {
        border-color: #0af;
      }
      button:disabled {
        opacity: 0.4;
        cursor: not-allowed;
      }
      #pattern-list {
        margin-bottom: 8px;
      }
      #sequencer {
        display: table;
        border-collapse: collapse;
        width: 100%;
        overflow-x: auto;
      }
      .row {
        display: table-row;
      }
      .cell, .header-cell {
        display: table-cell;
        border: 1px solid #444;
        width: 60px;
        height: 24px;
        text-align: center;
        vertical-align: middle;
        cursor: pointer;
        background: #111;
      }
      .header-cell {
        background: #333;
        font-weight: bold;
        user-select: none;
      }
      .cell.editing {
        outline: 2px solid #0af;
        background: #223366;
      }
      .cell.playing {
        background: #0a0;
        color: #efe;
      }
      #instrument-controls {
        display: flex;
        margin-top: 10px;
        gap: 16px;
        overflow-x: auto;
      }
      .instrument {
        border: 1px solid #444;
        padding: 6px;
        background: #111;
        flex: 1 0 200px;
      }
      .instrument h3 {
        margin: 0 0 6px 0;
        font-size: 16px;
      }
      label {
        font-size: 13px;
        display: block;
        margin-top: 4px;
      }
      input[type=range] {
        width: 100%;
      }
      #share-url {
        width: 100%;
        font-size: 12px;
        font-family: monospace;
        margin-top: 6px;
        background: #111;
        border: 1px solid #444;
        color: #ddd;
        padding: 4px;
      }
      /* Tooltip */
      .tooltip {
        position: relative;
        display: inline-block;
      }
      .tooltip:hover::after {
        content: attr(data-tip);
        position: absolute;
        background: #222;
        padding: 4px 6px;
        font-size: 11px;
        border-radius: 3px;
        color: #eee;
        white-space: nowrap;
        top: 110%;
        left: 50%;
        transform: translateX(-50%);
        pointer-events: none;
        z-index: 20;
      }
    </style>
    </head>
    <body>
    <div id="container">
      <div id="controls">
        <div>
          <label for="bpm">BPM:</label>
          <input type="number" id="bpm" min="30" max="300" value="120" title="Beats Per Minute" />
          <button id="play-pause" title="Play/Pause (Space)">Play</button>
          <button id="stop" title="Stop (S)">Stop</button>
        </div>
        <div>
          <button id="add-pattern" title="Add Pattern (+)">Add Pattern</button>
          <button id="dup-pattern" title="Duplicate Pattern (D)">Duplicate Pattern</button>
          <button id="del-pattern" title="Delete Pattern (Del)">Delete Pattern</button>
          <button id="copy-pattern" title="Copy Pattern (Ctrl+C)">Copy</button>
          <button id="paste-pattern" title="Paste Pattern (Ctrl+V)" disabled>Paste</button>
        </div>
        <div>
          <label for="loop-toggle" class="tooltip" data-tip="Loop playback">Loop
            <input type="checkbox" id="loop-toggle" checked />
          </label>
        </div>
      </div>
      <div id="pattern-list" aria-label="Pattern selector"></div>
      <div id="sequencer" aria-label="Pattern grid"></div>
      
      <div id="instrument-controls" aria-label="Instrument Controls"></div>
      <textarea id="share-url" readonly aria-label="Sharable song URL" title="URL to share or reload your song"></textarea>
    </div>
    
    <script>
    (() => {
      // Constants & Utils
      const NOTES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
      const noteToFreq = (note) => {
        // note like C-4, D#5 etc
        let m = /^([A-G]#?)-?(\d)$/.exec(note);
        if (!m) return null;
        let [_, n, octave] = m;
        let noteIndex = NOTES.indexOf(n);
        if (noteIndex < 0) return null;
        return 440 * Math.pow(2, (noteIndex - 9 + (octave - 4)*12)/12);
      };
    
      // Parse chord string like "C-4,E-4,G-4" into frequencies
      const parseChord = (str) => {
        return str.split(',').map(s => noteToFreq(s.trim())).filter(f => f!=null);
      };
    
      // Serialize song data to string -> then encodeURIComponent
      // We'll serialize as JSON string to keep it simple
    
      // Default Settings
      const DEFAULT_BPM = 120;
      const PATTERN_ROWS = 16;
      const CHANNELS = 4; // instruments
    
      // Waveform options
      const WAVEFORMS = ['square', 'sine', 'triangle', 'sawtooth', 'noise'];
    
      // Song data structure:
      /*
      {
        bpm: number,
        patterns: [
          [{note: string|null (e.g. "C-4,E-4"), ...}, ... per channel]
        ],
        instruments: [
          {
            waveform: 'sine'|'square'|'triangle'|'sawtooth'|'noise',
            volume: 0-1,
            detune: cents,
            adsr: {attack,sustain,decay,release} seconds,
            filter: {type:'lowpass'|'highpass'..., frequency: number},
            noiseMix: 0-1,
          }
        ],
        order: [pattern indices], // for playback order
      }
      */
    
      // --- State ---
      let song = null;
    
      // Clipboard for copy/paste patterns
      let clipboardPattern = null;
    
      // Playback state
      let audioCtx = null;
      let isPlaying = false;
      let currentRow = 0;
      let currentPatternIndex = 0;
      let playTimer = null;
    
      // HTML Elements
      const bpmInput = document.getElementById('bpm');
      const playBtn = document.getElementById('play-pause');
      const stopBtn = document.getElementById('stop');
      const patternListDiv = document.getElementById('pattern-list');
      const sequencerDiv = document.getElementById('sequencer');
      const instrumentControlsDiv = document.getElementById('instrument-controls');
      const addPatternBtn = document.getElementById('add-pattern');
      const delPatternBtn = document.getElementById('del-pattern');
      const dupPatternBtn = document.getElementById('dup-pattern');
      const copyPatternBtn = document.getElementById('copy-pattern');
      const pastePatternBtn = document.getElementById('paste-pattern');
      const loopToggle = document.getElementById('loop-toggle');
      const shareUrlTextarea = document.getElementById('share-url');
    
      // --- Initialization ---
      function newPattern() {
        // Returns array of rows, each row is array of cells, length = CHANNELS
        let rows = [];
        for(let i=0; i<PATTERN_ROWS; i++) {
          let row = new Array(CHANNELS).fill(null);
          rows.push(row);
        }
        return rows;
      }
    
      function newInstrument() {
        return {
          waveform: 'square',
          volume: 0.5,
          detune: 0, // cents
          adsr: {attack:0.01,sustain:0.1,decay:0.1,release:0.1},
          filter: {type:'lowpass', frequency: 1200},
          noiseMix: 0.0,
        };
      }
    
      function newSong() {
        return {
          bpm: DEFAULT_BPM,
          patterns: [newPattern()],
          instruments: Array(CHANNELS).fill(0).map(() => newInstrument()),
          order: [0], // play order of patterns (for now just 1 pattern)
        };
      }
    
      function setSong(newS) {
        song = newS;
        bpmInput.value = song.bpm;
        renderPatternList();
        currentPatternIndex = 0;
        renderSequencer();
        renderInstruments();
        updateShareUrl();
      }
    
      // --- Pattern UI ---
    
      let editingCell = null; // {row, channel} or null
    
      function renderPatternList() {
        patternListDiv.innerHTML = '';
        song.patterns.forEach((p, i) => {
          let btn = document.createElement('button');
          btn.textContent = `Pattern #${i}`;
          btn.style.backgroundColor = (i === currentPatternIndex) ? '#0af' : '#333';
          btn.style.color = (i === currentPatternIndex) ? '#fff' : '#ccc';
          btn.title = `Select Pattern #${i}`;
          btn.onclick = () => {
            if(isPlaying) stop();
            currentPatternIndex = i;
            renderPatternList();
            renderSequencer();
          };
          patternListDiv.appendChild(btn);
        });
      }
    
      function renderSequencer() {
        sequencerDiv.innerHTML = '';
        // Header row
        let headerRow = document.createElement('div');
        headerRow.className = 'row';
        let hr0 = document.createElement('div');
        hr0.className = 'header-cell';
        hr0.textContent = 'Row';
        headerRow.appendChild(hr0);
        for(let ch=0; ch<CHANNELS; ch++) {
          let hc = document.createElement('div');
          hc.className = 'header-cell';
          hc.textContent = `Ch${ch}`;
          headerRow.appendChild(hc);
        }
        sequencerDiv.appendChild(headerRow);
    
        // Cells rows
        let pat = song.patterns[currentPatternIndex];
        for(let r=0; r<PATTERN_ROWS; r++) {
          let rowDiv = document.createElement('div');
          rowDiv.className = 'row';
          // Row number cell
          let rowNum = document.createElement('div');
          rowNum.className = 'header-cell';
          rowNum.textContent = (r+1);
          rowDiv.appendChild(rowNum);
          for(let ch=0; ch<CHANNELS; ch++) {
            let cell = document.createElement('div');
            cell.className = 'cell';
            let val = pat[r][ch];
            cell.textContent = val || '';
            cell.dataset.row = r;
            cell.dataset.ch = ch;
    
            if(editingCell && editingCell.row === r && editingCell.ch === ch) {
              cell.classList.add('editing');
              setTimeout(() => cell.focus(), 10);
            }
    
            // Highlight playing row
            if(isPlaying && r === currentRow) {
              cell.classList.add('playing');
            }
    
            cell.tabIndex = 0;
            cell.title = "Click or type notes (e.g. C-4, D#5). Use commas for chords";
            cell.onclick = (e) => {
              if(isPlaying) stop();
              startEditingCell(r, ch);
            };
            cell.onkeydown = (e) => {
              // Keyboard shortcuts for editing
              if(e.key === 'Enter') {
                e.preventDefault();
                if(editingCell) stopEditingCell();
              } else if(e.key === 'Escape') {
                e.preventDefault();
                cancelEditingCell();
              } else if(e.key === 'Backspace' || e.key === 'Delete') {
                e.preventDefault();
                pat[r][ch] = null;
                renderSequencer();
                updateShareUrl();
              } else if(!editingCell) {
                // Start editing on typing note char or number
                if(/^[a-gA-G0-9#,-]$/.test(e.key)) {
                  startEditingCell(r, ch, e.key);
                  e.preventDefault();
                }
              }
            };
            sequencerDiv.appendChild(rowDiv);
            rowDiv.appendChild(cell);
          }
          sequencerDiv.appendChild(rowDiv);
        }
      }
    
      function startEditingCell(row, ch, firstChar='') {
        if(editingCell) stopEditingCell();
        editingCell = {row, ch};
        const pat = song.patterns[currentPatternIndex];
        let val = pat[row][ch] || '';
        val = firstChar ? firstChar : val;
        renderSequencer();
        // Find the DOM cell and make contenteditable for in-place edit
        let cell = [...sequencerDiv.querySelectorAll('.cell')]
          .find(c => Number(c.dataset.row)===row && Number(c.dataset.ch)===ch);
        if(!cell) return;
        cell.contentEditable = "true";
        cell.focus();
        cell.textContent = val;
        // Move caret to end
        document.execCommand('selectAll', false, null);
        document.getSelection().collapseToEnd();
    
        // Handle blur or enter to save
        function save() {
          pat[row][ch] = cell.textContent.trim() || null;
          cell.contentEditable = "false";
          editingCell = null;
          renderSequencer();
          updateShareUrl();
          cell.removeEventListener('blur', onBlur);
          cell.removeEventListener('keydown', onKeyDown);
        }
        function cancel() {
          cell.contentEditable = "false";
          editingCell = null;
          renderSequencer();
          cell.removeEventListener('blur', onBlur);
          cell.removeEventListener('keydown', onKeyDown);
        }
        function onBlur() {
          save();
        }
        function onKeyDown(e) {
          if(e.key === 'Enter') {
            e.preventDefault();
            save();
          } else if(e.key === 'Escape') {
            e.preventDefault();
            cancel();
          }
        }
        cell.addEventListener('blur', onBlur);
        cell.addEventListener('keydown', onKeyDown);
      }
    
      function stopEditingCell() {
        if(!editingCell) return;
        // Save by blurring
        let cell = [...sequencerDiv.querySelectorAll('.cell')]
          .find(c => Number(c.dataset.row)===editingCell.row && Number(c.dataset.ch)===editingCell.ch);
        if(cell) cell.blur();
      }
      function cancelEditingCell() {
        if(!editingCell) return;
        let cell = [...sequencerDiv.querySelectorAll('.cell')]
          .find(c => Number(c.dataset.row)===editingCell.row && Number(c.dataset.ch)===editingCell.ch);
        if(cell) {
          cell.textContent = song.patterns[currentPatternIndex][editingCell.row][editingCell.ch]||'';
          cell.contentEditable = "false";
        }
        editingCell = null;
        renderSequencer();
      }
    
      // --- Instruments UI ---
      function renderInstruments() {
        instrumentControlsDiv.innerHTML = '';
        song.instruments.forEach((ins, i) => {
          let div = document.createElement('div');
          div.className = 'instrument';
          div.tabIndex = 0;
          div.setAttribute('aria-label', `Instrument ${i} controls`);
    
          const idPrefix = `ins${i}`;
    
          div.innerHTML = `
            <h3>Instrument #${i}</h3>
            <label for="${idPrefix}-waveform">Waveform:
              <select id="${idPrefix}-waveform" aria-label="Waveform">
                ${WAVEFORMS.map(wf => `<option value="${wf}" ${wf===ins.waveform ? 'selected' : ''}>${wf}</option>`).join('')}
              </select>
            </label>
            <label for="${idPrefix}-volume">Volume: <span id="${idPrefix}-volume-val">${ins.volume.toFixed(2)}</span></label>
            <input type="range" id="${idPrefix}-volume" min="0" max="1" step="0.01" value="${ins.volume}" />
            <label for="${idPrefix}-detune">Detune (cents): <span id="${idPrefix}-detune-val">${ins.detune}</span></label>
            <input type="range" id="${idPrefix}-detune" min="-100" max="100" step="1" value="${ins.detune}" />
            <label>ADSR (seconds):</label>
            <label for="${idPrefix}-attack">Attack: <span id="${idPrefix}-attack-val">${ins.adsr.attack.toFixed(2)}</span></label>
            <input type="range" id="${idPrefix}-attack" min="0" max="1" step="0.01" value="${ins.adsr.attack}" />
            <label for="${idPrefix}-decay">Decay: <span id="${idPrefix}-decay-val">${ins.adsr.decay.toFixed(2)}</span></label>
            <input type="range" id="${idPrefix}-decay" min="0" max="1" step="0.01" value="${ins.adsr.decay}" />
            <label for="${idPrefix}-sustain">Sustain: <span id="${idPrefix}-sustain-val">${ins.adsr.sustain.toFixed(2)}</span></label>
            <input type="range" id="${idPrefix}-sustain" min="0" max="1" step="0.01" value="${ins.adsr.sustain}" />
            <label for="${idPrefix}-release">Release: <span id="${idPrefix}-release-val">${ins.adsr.release.toFixed(2)}</span></label>
            <input type="range" id="${idPrefix}-release" min="0" max="1" step="0.01" value="${ins.adsr.release}" />
            <label for="${idPrefix}-filterFreq">Filter Frequency: <span id="${idPrefix}-filterFreq-val">${ins.filter.frequency}</span></label>
            <input type="range" id="${idPrefix}-filterFreq" min="100" max="5000" step="10" value="${ins.filter.frequency}" />
            <label for="${idPrefix}-noiseMix">Noise Mix: <span id="${idPrefix}-noiseMix-val">${ins.noiseMix.toFixed(2)}</span></label>
            <input type="range" id="${idPrefix}-noiseMix" min="0" max="1" step="0.01" value="${ins.noiseMix}" />
          `;
    
          instrumentControlsDiv.appendChild(div);
    
          // Attach events
          const wfSelect = div.querySelector(`#${idPrefix}-waveform`);
          const volumeRange = div.querySelector(`#${idPrefix}-volume`);
          const detuneRange = div.querySelector(`#${idPrefix}-detune`);
          const attackRange = div.querySelector(`#${idPrefix}-attack`);
          const decayRange = div.querySelector(`#${idPrefix}-decay`);
          const sustainRange = div.querySelector(`#${idPrefix}-sustain`);
          const releaseRange = div.querySelector(`#${idPrefix}-release`);
          const filterFreqRange = div.querySelector(`#${idPrefix}-filterFreq`);
          const noiseMixRange = div.querySelector(`#${idPrefix}-noiseMix`);
    
          const updateValSpan = (id) => {
            div.querySelector(`#${id}`).textContent = div.querySelector(`#${id.replace('-val','')}`).value;
          };
    
          wfSelect.onchange = () => {
            ins.waveform = wfSelect.value;
            updateShareUrl();
          };
          volumeRange.oninput = () => {
            ins.volume = parseFloat(volumeRange.value);
            updateValSpan(`${idPrefix}-volume-val`);
            updateShareUrl();
          };
          detuneRange.oninput = () => {
            ins.detune = parseInt(detuneRange.value);
            updateValSpan(`${idPrefix}-detune-val`);
            updateShareUrl();
          };
          attackRange.oninput = () => {
            ins.adsr.attack = parseFloat(attackRange.value);
            updateValSpan(`${idPrefix}-attack-val`);
            updateShareUrl();
          };
          decayRange.oninput = () => {
            ins.adsr.decay = parseFloat(decayRange.value);
            updateValSpan(`${idPrefix}-decay-val`);
            updateShareUrl();
          };
          sustainRange.oninput = () => {
            ins.adsr.sustain = parseFloat(sustainRange.value);
            updateValSpan(`${idPrefix}-sustain-val`);
            updateShareUrl();
          };
          releaseRange.oninput = () => {
            ins.adsr.release = parseFloat(releaseRange.value);
            updateValSpan(`${idPrefix}-release-val`);
            updateShareUrl();
          };
          filterFreqRange.oninput = () => {
            ins.filter.frequency = parseInt(filterFreqRange.value);
            updateValSpan(`${idPrefix}-filterFreq-val`);
            updateShareUrl();
          };
          noiseMixRange.oninput = () => {
            ins.noiseMix = parseFloat(noiseMixRange.value);
            updateValSpan(`${idPrefix}-noiseMix-val`);
            updateShareUrl();
          };
        });
      }
    
      // --- Playback ---
    
      function createNoiseBuffer() {
        let bufferSize = audioCtx.sampleRate;
        let buffer = audioCtx.createBuffer(1, bufferSize, audioCtx.sampleRate);
        let output = buffer.getChannelData(0);
        for(let i=0; i<bufferSize; i++) {
          output[i] = Math.random()*2-1;
        }
        return buffer;
      }
    
      function playNote(instrument, frequency, durationSec) {
        if(!audioCtx) return;
    
        const now = audioCtx.currentTime;
    
        // oscillator or noise source
        let oscNode;
        if(instrument.waveform === 'noise') {
          oscNode = audioCtx.createBufferSource();
          oscNode.buffer = createNoiseBuffer();
          oscNode.loop = true;
        } else {
          oscNode = audioCtx.createOscillator();
          oscNode.type = instrument.waveform;
          oscNode.frequency.setValueAtTime(frequency, now);
          oscNode.detune.setValueAtTime(instrument.detune, now);
        }
    
        // Gain envelope for ADSR
        let gainNode = audioCtx.createGain();
        gainNode.gain.setValueAtTime(0, now);
        // Attack
        gainNode.gain.linearRampToValueAtTime(instrument.volume, now + instrument.adsr.attack);
        // Decay to sustain
        gainNode.gain.linearRampToValueAtTime(instrument.volume * instrument.adsr.sustain, now + instrument.adsr.attack + instrument.adsr.decay);
        // Sustain level maintained...
        // Release triggered after duration
        gainNode.gain.setTargetAtTime(0, now + durationSec, instrument.adsr.release);
    
        // Filter
        let filterNode = audioCtx.createBiquadFilter();
        filterNode.type = instrument.filter.type || 'lowpass';
        filterNode.frequency.setValueAtTime(instrument.filter.frequency, now);
    
        // Noise mix: connect noise source + osc
        if(instrument.waveform !== 'noise' && instrument.noiseMix > 0) {
          // Mix oscillator and noise
          let noiseSource = audioCtx.createBufferSource();
          noiseSource.buffer = createNoiseBuffer();
          noiseSource.loop = true;
          
          let noiseGain = audioCtx.createGain();
          noiseGain.gain.setValueAtTime(instrument.volume * instrument.noiseMix, now);
    
          let oscGain = audioCtx.createGain();
          oscGain.gain.setValueAtTime(instrument.volume * (1 - instrument.noiseMix), now);
    
          oscNode.connect(oscGain).connect(filterNode).connect(gainNode).connect(audioCtx.destination);
          noiseSource.connect(noiseGain).connect(filterNode);
    
          oscNode.start(now);
          noiseSource.start(now);
    
          oscNode.stop(now + durationSec + 1);
          noiseSource.stop(now + durationSec + 1);
        } else {
          oscNode.connect(filterNode);
          filterNode.connect(gainNode);
          gainNode.connect(audioCtx.destination);
    
          oscNode.start(now);
          oscNode.stop(now + durationSec + 1);
        }
      }
    
      function playRow() {
        if(!audioCtx) return;
        let patternIndex = song.order[currentPatternIndex] ?? 0;
        let pat = song.patterns[currentPatternIndex];
        let rowData = pat[currentRow];
    
        // Play notes per channel
        rowData.forEach((cell, ch) => {
          if(cell) {
            let freqs = parseChord(cell);
            let ins = song.instruments[ch];
            freqs.forEach(freq => playNote(ins, freq, 0.3));
          }
        });
      }
    
      function scheduler() {
        if(!isPlaying) return;
        playRow();
        renderSequencer();
    
        currentRow++;
        if(currentRow >= PATTERN_ROWS) {
          currentRow = 0;
          if(!loopToggle.checked) {
            stop();
            return;
          }
        }
        // Schedule next row
        let intervalMs = 60000 / (song.bpm * 4); // assuming 16th notes, 4 rows per beat
        playTimer = setTimeout(scheduler, intervalMs);
      }
    
      function play() {
        if(!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
        if(isPlaying) return;
        isPlaying = true;
        currentRow = 0;
        playBtn.textContent = 'Pause';
        scheduler();
      }
    
      function pause() {
        isPlaying = false;
        playBtn.textContent = 'Play';
        if(playTimer) clearTimeout(playTimer);
      }
      function stop() {
        pause();
        currentRow = 0;
        renderSequencer();
      }
    
      // --- Pattern Edit Buttons ---
      addPatternBtn.onclick = () => {
        if(isPlaying) stop();
        song.patterns.push(newPattern());
        currentPatternIndex = song.patterns.length-1;
        renderPatternList();
        renderSequencer();
        updateShareUrl();
      };
    
      delPatternBtn.onclick = () => {
        if(song.patterns.length <= 1) {
          alert("At least one pattern is required!");
          return;
        }
        if(isPlaying) stop();
        song.patterns.splice(currentPatternIndex,1);
        if(currentPatternIndex >= song.patterns.length) currentPatternIndex = song.patterns.length-1;
        renderPatternList();
        renderSequencer();
        updateShareUrl();
      };
    
      dupPatternBtn.onclick = () => {
        if(isPlaying) stop();
        let copy = song.patterns[currentPatternIndex].map(row => row.slice());
        song.patterns.push(copy);
        currentPatternIndex = song.patterns.length-1;
        renderPatternList();
        renderSequencer();
        updateShareUrl();
      };
    
      copyPatternBtn.onclick = () => {
        clipboardPattern = song.patterns[currentPatternIndex].map(row => row.slice());
        pastePatternBtn.disabled = false;
      };
    
      pastePatternBtn.onclick = () => {
        if(!clipboardPattern) return;
        if(isPlaying) stop();
        song.patterns[currentPatternIndex] = clipboardPattern.map(row => row.slice());
        renderSequencer();
        updateShareUrl();
      };
    
      bpmInput.onchange = () => {
        const val = parseInt(bpmInput.value);
        if(val>=30 && val<=300){
          song.bpm = val;
          updateShareUrl();
        } else {
          bpmInput.value = song.bpm;
        }
      };
    
      playBtn.onclick = () => {
        if(isPlaying) {
          pause();
        } else {
          play();
        }
      };
    
      stopBtn.onclick = stop;
    
      // --- Share via URL ---
    
      function serializeSong() {
        // We'll strip repeated nulls to shorten string & compress minimally
        // Actually for simplicity serialize JSON directly
        try {
          return JSON.stringify(song);
        } catch {
          return '{}';
        }
      }
      function deserializeSong(str) {
        try {
          return JSON.parse(str);
        } catch (e) {
          return null;
        }
      }
      function updateShareUrl() {
        let data = serializeSong();
        let packed = btoa(unescape(encodeURIComponent(data)));
        let url = `${location.origin}${location.pathname}#/song=${packed}`;
        shareUrlTextarea.value = url;
      }
      function loadFromUrl() {
        if(location.hash.startsWith('#/song=')){
          let packed = location.hash.slice(7);
          try {
            let json = decodeURIComponent(escape(atob(packed)));
            let s = deserializeSong(json);
            if(s) {
              setSong(s);
              return true;
            }
          } catch {}
        }
        return false;
      }
    
      // --- Keyboard shortcuts ---
      window.addEventListener('keydown', e => {
        if(e.target.isContentEditable || e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
    
        if(e.code === 'Space') {
          e.preventDefault();
          if(isPlaying) pause(); else play();
        } else if(e.code === 'KeyS') {
          e.preventDefault();
          stop();
        } else if(e.code === 'KeyD') { // dupe pattern
          e.preventDefault();
          dupPatternBtn.click();
        } else if(e.code === 'Delete') {
          e.preventDefault();
          delPatternBtn.click();
        } else if(e.ctrlKey && e.code === 'KeyC') {
          e.preventDefault();
          copyPatternBtn.click();
        } else if(e.ctrlKey && e.code === 'KeyV') {
          e.preventDefault();
          pastePatternBtn.click();
        } else if(e.code === 'Equal') {
          e.preventDefault();
          addPatternBtn.click();
        }
      });
    
      // --- Init Program ---
      if(!loadFromUrl()) {
        setSong(newSong());
      } else {
        updateShareUrl();
      }
    })();
    </script>
    </body>
    </html>
    

    Features included:

    • 4-channel pattern sequencer, 16 rows
    • Pattern add/duplicate/delete/copy/paste with buttons and keyboard shortcuts
    • Play/pause/stop with timing based on BPM
    • Loop toggle checkbox
    • Per instrument controls:
      • Waveform (square, sine, triangle, sawtooth, noise)
      • Volume slider
      • Detune slider
      • ADSR envelope sliders
      • Filter frequency slider (lowpass)
      • Noise mix slider (mix noise with osc)
    • Notes are entered in cells as text, support chords (comma separated notes) e.g. C-4,E-4,G-4
    • Share song state in URL using base64 encoded JSON in hash for easy sharing and reload
    • Keyboard shortcuts:
      • Space: Play/pause
      • S: Stop
      • D: Duplicate pattern
      • Del: Delete pattern
      • Ctrl+C: Copy pattern
      • Ctrl+V: Paste pattern
      • = (Equals): Add pattern

    Usage

    • Click on cells in the pattern grid and type notes like C-4, D#5, or chords C-4,E-4,G-4. Press Enter or click outside to save.
    • Use the instrument panels below to tweak waveform and synth params.
    • Use Play/Pause and Stop controls to play sequence.
    • Share the song by copying the URL in the bottom textarea.
    • Add/dup/delete/copy/paste patterns with buttons or shortcuts.
    • Pattern selection at top.

    If you need it extended (like more channels, custom waveforms, sample support), that can be done, but this covers your request in a compact code that runs fully client side with no dependencies or external demo.

    Feel free to ask for enhancements or explanations!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.