Skip to content
The 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

    You want a chiptune tracker / pattern sequencer web app with features like:

    • BPM control
    • Chords
    • Custom pattern size & rows per pattern
    • Multiple instruments/synths per instrument
    • Custom waveforms / oscillators
    • Volume, detune, ADSR, filter, noise controls
    • Pattern manipulation (copy, paste, duplicate, delete)
    • Looping patterns
    • Share song via URL hash (like /#[...])
    • Keyboard shortcuts
    • No demo or irrelevant UI stuff—just a focused code solution.

    Below is a starter implementation in pure HTML/JS/CSS, demonstrating the core architecture. It’s small enough so you can extend it further:


    What this example includes:

    • Pattern grid with rows/columns configurable
    • Instruments, each with synth parameters: waveform, volume, detune, ADSR, noise
    • A simple chiptune synth using Web Audio API oscillator + noise + filter + ADSR envelope
    • Controls: BPM, pattern size, rows, play/stop
    • Pattern manipulation: copy, paste, duplicate, delete, loop
    • Keyboard shortcuts for navigation & editing
    • Pattern sharing by encoding JSON data into URL hash and decoding on load

    Code

    <!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; background: #111; color: #eee; margin:0; }
      #app { max-width: 960px; margin: auto; padding: 1em; }
      button,input,select { background:#222; color:#eee; border:none; padding:0.3em 0.6em; font-family: monospace; }
      button:hover,input:focus,select:focus { outline: 1px solid #55f; }
      #patternGrid { display: grid; margin-top:1em; border: 1px solid #555;}
      .cell { border: 1px solid #333; padding: 2px 4px; text-align:center; cursor:pointer; user-select:none; }
      .cell.active { background: #2a2; }
      .cell.selected { background: #555; }
      .cell.editing { background: #55f; color:#fff; }
      .headerRow { font-weight: bold; background: #222; }
      #controls, #toolbar { display: flex; gap: 1em; margin-bottom: 1em; flex-wrap: wrap; }
      label { display:flex; flex-direction: column; font-size: 0.8em; }
      h1 { margin-top:0; }
      #instruments { margin-top: 1em; }
      .instrument {
        border: 1px solid #444;
        background: #222;
        padding: 0.5em;
        margin-bottom: 1em;
      }
      .instrument h3 {
        margin: 0 0 0.5em 0;
        font-weight: normal;
        font-size: 1.1em;
      }
      .instrument input, .instrument select {
        margin-bottom: 0.3em;
        width: 100%;
      }
    </style>
    </head>
    <body>
      <div id="app">
        <h1>Chiptune Tracker</h1>
        <div id="controls">
          <label>BPM <input id="bpm" type="number" min="20" max="300" value="120" /></label>
          <label>Patterns <input id="numPatterns" type="number" min="1" max="16" value="4"/></label>
          <label>Rows/Pattern <input id="rowsPerPattern" type="number" min="4" max="32" step="4" value="16"/></label>
          <button id="playBtn">▶ Play</button>
          <button id="stopBtn" disabled>■ Stop</button>
          <button id="shareBtn">Share</button>
        </div>
    
        <div id="patternSelector">
          <label>Current Pattern
            <select id="currentPattern"></select>
          </label>
        </div>
    
        <div id="patternGrid"></div>
    
        <div id="toolbar" style="margin-top:0.5em;">
          <button data-action="copy">Copy</button>
          <button data-action="paste">Paste</button>
          <button data-action="dupe">Duplicate</button>
          <button data-action="del">Delete</button>
          <button data-action="loopToggle">Toggle Loop</button>
        </div>
    
        <div id="instruments"></div>
      </div>
    
    <script>
    (() => {
    
    // ----- Utility -----
    function noteToFreq(note) {
      // simple mapping C-4=261.63Hz
      // note is like C-4 or D#5; support C0-B7 here
      if (!note) return 0;
      let m = note.match(/^([A-G])(#?)(\d)$/);
      if (!m) return 0;
      const baseFreq = 440; // A4
      const notes = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B'];
      let [ , letter, sharp, octave ] = m;
      octave = +octave;
      let noteName = letter + (sharp||'');
      let noteIndex = notes.indexOf(noteName);
      if(noteIndex<0) return 0;
      let keyNumber = noteIndex + (octave * 12);
      // A4 = key 57 (A=9 + 4*12=57)
      // Frequency formula:
      return baseFreq * Math.pow(2, (keyNumber - 57) / 12);
    }
    
    // ----- State -----
    const state = {
      bpm: 120,
      numPatterns: 4,
      rowsPerPattern: 16,
      currentPattern: 0,
      patterns: [],
      instruments: [],
      clipboardPattern: null,
      loopPattern: false,
      playing: false,
      playTimer: null,
      playRow: 0,
      editPos: {pattern:0, row:0, col:0},
    };
    
    function makeEmptyPattern(rows, cols) {
      // each cell: { note: null|string, chord: [] }
      let cells = [];
      for(let r=0; r<rows; r++){
        let row = [];
        for(let c=0; c<cols; c++){
          row.push({note:null,chord:[], volume:1});
        }
        cells.push(row);
      }
      return cells;
    }
    
    // Default synth config per instrument
    function makeDefaultInstrument(name){
      return {
        name,
        waveform: 'square',
        volume: 0.8,
        detune: 0,
        adsr: {attack:0.01, decay:0.1, sustain:0.5, release:0.3},
        filter: {type:'lowpass', frequency:8000, Q:1},
        noise: 0,
        patternAssignments: [], // array of pattern indexes assigned?
      }
    }
    
    // ----- Initialize -----
    
    function init() {
      // Create instruments
      if(state.instruments.length===0){
        for(let i=0; i<3; i++){
          state.instruments.push(makeDefaultInstrument("Inst "+(i+1)));
        }
      }
      // Create patterns:
      state.patterns = [];
      for(let i=0; i<state.numPatterns; i++){
        state.patterns.push(makeEmptyPattern(state.rowsPerPattern, state.instruments.length));
      }
      state.currentPattern = 0;
    }
    
    // ----- DOM Elements -----
    const bpmInput = document.getElementById("bpm");
    const numPatternsInput = document.getElementById("numPatterns");
    const rowsPerPatternInput = document.getElementById("rowsPerPattern");
    const playBtn = document.getElementById("playBtn");
    const stopBtn = document.getElementById("stopBtn");
    const patternGrid = document.getElementById("patternGrid");
    const currentPatternSelect = document.getElementById("currentPattern");
    const shareBtn = document.getElementById("shareBtn");
    const instrumentsDiv = document.getElementById("instruments");
    const toolbar = document.getElementById("toolbar");
    
    // ----- Render Pattern Selector -----
    function renderPatternSelector() {
      currentPatternSelect.innerHTML = "";
      for(let i=0; i<state.numPatterns; i++){
        const opt = document.createElement("option");
        opt.value = i;
        opt.textContent = "Pattern "+(i+1);
        currentPatternSelect.appendChild(opt);
      }
      currentPatternSelect.value = state.currentPattern;
    }
    
    // ----- Render Pattern Grid -----
    function renderPatternGrid() {
      const rows = state.rowsPerPattern;
      const cols = state.instruments.length;
      patternGrid.style.gridTemplateColumns = `repeat(${cols+1}, 3em)`;
      patternGrid.innerHTML = "";
      // header row
      const headerRow = document.createElement("div");
      headerRow.classList.add("headerRow");
      headerRow.textContent = "Row\\Inst";
      patternGrid.appendChild(headerRow);
      for(let ci=0; ci<cols; ci++){
        const cell = document.createElement("div");
        cell.classList.add("headerRow");
        cell.textContent = state.instruments[ci].name;
        patternGrid.appendChild(cell);
      }
      // pattern rows
      const patt = state.patterns[state.currentPattern];
    
      for(let r=0; r<rows; r++){
        const rowHeader = document.createElement("div");
        rowHeader.classList.add("headerRow");
        rowHeader.textContent = (r+1);
        patternGrid.appendChild(rowHeader);
        for(let c=0; c<cols; c++){
          const cell = document.createElement("div");
          cell.classList.add("cell");
          cell.dataset.row = r;
          cell.dataset.col = c;
          const data = patt[r][c];
          cell.textContent = data.note || "--";
          if(r===state.editPos.row && c===state.editPos.col) {
            cell.classList.add("editing");
          }
          patternGrid.appendChild(cell);
        }
      }
    }
    
    // ----- Render Instruments -----
    function renderInstruments() {
      instrumentsDiv.innerHTML = "";
      state.instruments.forEach((inst,i) => {
        const div = document.createElement("div");
        div.className = "instrument";
        div.innerHTML = `
          <h3>${inst.name}</h3>
          <label>Waveform
            <select data-inst="${i}" data-param="waveform">
              <option value="square">square</option>
              <option value="triangle">triangle</option>
              <option value="sawtooth">sawtooth</option>
              <option value="sine">sine</option>
            </select>
          </label>
          <label>Volume
            <input type="range" min="0" max="1" step="0.01" value="${inst.volume}" data-inst="${i}" data-param="volume"/>
          </label>
          <label>Detune (cents)
            <input type="number" min="-100" max="100" step="1" value="${inst.detune}" data-inst="${i}" data-param="detune"/>
          </label>
          <label>ADSR Attack (s)
            <input type="number" min="0" max="2" step="0.01" value="${inst.adsr.attack}" data-inst="${i}" data-param="adsr-attack"/>
          </label>
          <label>ADSR Decay (s)
            <input type="number" min="0" max="2" step="0.01" value="${inst.adsr.decay}" data-inst="${i}" data-param="adsr-decay"/>
          </label>
          <label>ADSR Sustain (0-1)
            <input type="number" min="0" max="1" step="0.01" value="${inst.adsr.sustain}" data-inst="${i}" data-param="adsr-sustain"/>
          </label>
          <label>ADSR Release (s)
            <input type="number" min="0" max="2" step="0.01" value="${inst.adsr.release}" data-inst="${i}" data-param="adsr-release"/>
          </label>
          <label>Filter Freq (Hz)
            <input type="number" min="20" max="22050" step="1" value="${inst.filter.frequency}" data-inst="${i}" data-param="filter-frequency"/>
          </label>
          <label>Filter Q
            <input type="number" min="0" max="30" step="0.1" value="${inst.filter.Q}" data-inst="${i}" data-param="filter-Q"/>
          </label>
          <label>Noise Mix (0-1)
            <input type="number" min="0" max="1" step="0.01" value="${inst.noise}" data-inst="${i}" data-param="noise"/>
          </label>
        `;
        instrumentsDiv.appendChild(div);
        // Set select values
        const waveformSelect = div.querySelector("select[data-param='waveform']");
        waveformSelect.value = inst.waveform;
      });
    }
    // ----- Update Instrument Param on input -----
    instrumentsDiv.addEventListener("input", e=>{
      const el = e.target;
      const i = el.dataset.inst;
      const p = el.dataset.param;
      if(i==null || !p) return;
      let val = el.value;
      const inst = state.instruments[i];
      if(!inst) return;
      if(p.startsWith('adsr-')){
        const key = p.split('-')[1];
        inst.adsr[key] = parseFloat(val);
      } else if(p.startsWith('filter-')){
        const key = p.split('-')[1];
        inst.filter[key] = parseFloat(val);
      } else if(p==='volume' || p==='noise') {
        inst[p] = parseFloat(val);
      } else if(p === 'detune') {
        inst.detune = parseInt(val);
      } else if(p ==='waveform') {
        inst.waveform = val;
      }
    });
    
    // ----- Pattern Grid Click Editing -----
    patternGrid.addEventListener("click", e=>{
      const cell = e.target.closest(".cell");
      if(!cell) return;
      const r = +cell.dataset.row;
      const c = +cell.dataset.col;
      if(r==null || c==null) return;
    
      state.editPos = {pattern: state.currentPattern, row: r, col: c};
      renderPatternGrid();
      startEditingCell(cell);
    });
    
    function startEditingCell(cell) {
      // prompt for note/chord input: simple textual prompt here for demo
      const r = state.editPos.row;
      const c = state.editPos.col;
      let currentNote = state.patterns[state.currentPattern][r][c].note || '';
      // simple dialog: prompt
      let userInput = prompt("Enter note (e.g. C4, D#5) or chord (e.g. C4 E4 G4), or empty to clear:", currentNote);
      if(userInput!==null) {
        // parse chord:
        let notes = userInput.split(/\s+/).filter(x=>x.length>0);
        let note = notes.length? notes[0] : null;
        // We support only single note for now.
        state.patterns[state.currentPattern][r][c].note = note || null;
        // future: save chord or multiple notes array into chord field
      }
      renderPatternGrid();
    }
    
    // ----- Playback Synth -----
    const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    const masterGain = audioCtx.createGain();
    masterGain.gain.value = 0.5;
    masterGain.connect(audioCtx.destination);
    
    function playNote(inst, freq, startTime, duration) {
      if(freq<=0) return;
      const o = audioCtx.createOscillator();
      const g = audioCtx.createGain();
      const f = audioCtx.createBiquadFilter();
      const noiseGain = audioCtx.createGain();
      // Setup oscillator
      o.type = inst.waveform;
      o.frequency.setValueAtTime(freq, startTime);
      o.detune.setValueAtTime(inst.detune, startTime);
    
      // Setup filter
      f.type = inst.filter.type;
      f.frequency.setValueAtTime(inst.filter.frequency, startTime);
      f.Q.setValueAtTime(inst.filter.Q, startTime);
    
      // Gain + ADSR envelope
      g.gain.setValueAtTime(0, startTime);
      g.gain.linearRampToValueAtTime(inst.volume, startTime + inst.adsr.attack);
      g.gain.linearRampToValueAtTime(inst.volume * inst.adsr.sustain, startTime + inst.adsr.attack + inst.adsr.decay);
      g.gain.setValueAtTime(inst.volume * inst.adsr.sustain, startTime + duration - inst.adsr.release);
      g.gain.linearRampToValueAtTime(0, startTime + duration);
    
      // Noise
      if(inst.noise > 0) {
        const bufferSize = audioCtx.sampleRate * 0.1;
        const noiseBuffer = audioCtx.createBuffer(1, bufferSize, audioCtx.sampleRate);
        let output = noiseBuffer.getChannelData(0);
        for(let i=0; i<bufferSize; i++) {
          output[i] = (Math.random() * 2 - 1) * inst.noise;
        }
        const noiseSource = audioCtx.createBufferSource();
        noiseSource.buffer = noiseBuffer;
        noiseSource.loop = true;
        noiseSource.start(startTime);
        noiseSource.stop(startTime + duration);
        noiseSource.connect(noiseGain);
        noiseGain.gain.setValueAtTime(inst.noise, startTime);
        noiseGain.connect(g);
      }
    
      o.connect(f);
      f.connect(g);
      g.connect(masterGain);
      o.start(startTime);
      o.stop(startTime + duration);
    }
    
    function playRow(row) {
      const now = audioCtx.currentTime;
      const secPerBeat = 60/state.bpm;
      let duration = secPerBeat; // one beat per row
      const patt = state.patterns[state.currentPattern];
      for(let instIdx=0; instIdx < state.instruments.length; instIdx++){
        const inst = state.instruments[instIdx];
        const cell = patt[row][instIdx];
        let freq = noteToFreq(cell.note);
        if(freq>0) {
          playNote(inst, freq, now, duration);
        }
      }
    }
    
    function stepPlay() {
      playRow(state.playRow);
      state.playRow++;
      if(state.playRow>=state.rowsPerPattern){
        if(state.loopPattern){
          state.playRow=0;
        } else {
          stopPlayback();
          return;
        }
      }
      const interval = (60 / state.bpm) * 1000;
      state.playTimer = setTimeout(stepPlay, interval);
    }
    
    function startPlayback() {
      if(audioCtx.state === 'suspended') {
        audioCtx.resume();
      }
      state.playRow = 0;
      state.playing = true;
      playBtn.disabled = true;
      stopBtn.disabled = false;
      stepPlay();
    }
    
    function stopPlayback() {
      state.playing = false;
      if(state.playTimer) 
        clearTimeout(state.playTimer);
      playBtn.disabled = false;
      stopBtn.disabled = true;
    }
    
    // ----- Toolbar Actions -----
    toolbar.addEventListener("click", e=>{
      if(e.target.dataset.action){
        performAction(e.target.dataset.action);
      }
    });
    
    function performAction(action) {
      const pattern = state.patterns[state.currentPattern];
      switch(action){
        case "copy":
          // Deep clone pattern
          state.clipboardPattern = JSON.parse(JSON.stringify(pattern));
          alert("Pattern copied!");
          break;
        case "paste":
          if(state.clipboardPattern){
            state.patterns[state.currentPattern] = JSON.parse(JSON.stringify(state.clipboardPattern));
            renderPatternGrid();
          } else {
            alert("Clipboard empty");
          }
          break;
        case "dupe":
          // Duplicate current pattern at end, if space
          if(state.patterns.length < 16) {
            const dup = JSON.parse(JSON.stringify(pattern));
            state.patterns.push(dup);
            state.numPatterns++;
            renderPatternSelector();
            alert("Pattern duplicated to end");
          } else {
            alert("Max patterns reached");
          }
          break;
        case "del":
          // Clear current pattern
          for(let r=0;r<state.rowsPerPattern;r++){
            for(let c=0;c<state.instruments.length;c++){
              pattern[r][c] = {note:null, chord:[], volume:1};
            }
          }
          renderPatternGrid();
          break;
        case "loopToggle":
          state.loopPattern = !state.loopPattern;
          alert("Loop " + (state.loopPattern ? "enabled" : "disabled"));
          break;
      }
    }
    
    // ----- Handle Pattern selector -----
    currentPatternSelect.addEventListener("change", e=>{
      state.currentPattern = +currentPatternSelect.value;
      renderPatternGrid();
    });
    
    // Handle config changes
    bpmInput.addEventListener("change", e=>{
      let val = +bpmInput.value;
      if(val<20) val=20;
      if(val>300) val=300;
      state.bpm = val;
      bpmInput.value = val;
    });
    numPatternsInput.addEventListener("change", e=>{
      let val = +numPatternsInput.value;
      if(val < 1) val=1;
      if(val > 16) val=16;
      const prev = state.numPatterns;
      state.numPatterns = val;
      if(val > prev){
        for(let i=prev; i<val; i++){
          state.patterns[i] = makeEmptyPattern(state.rowsPerPattern, state.instruments.length);
        }
      } else if(val < prev) {
        state.patterns.length = val;
      }
      renderPatternSelector();
    });
    rowsPerPatternInput.addEventListener("change", e=>{
      let val = +rowsPerPatternInput.value;
      if(val<4) val=4;
      if(val>32) val=32;
      if(val%4 !== 0) val = Math.round(val/4)*4; 
      state.rowsPerPattern=val;
      // Resize existing patterns
      state.patterns.forEach(patt=>{
        if(patt.length > val) {
          patt.length = val;
        } else {
          while(patt.length < val) {
            // add empty row
            patt.push([]);
            for(let c=0; c<state.instruments.length; c++){
              patt[patt.length-1].push({note:null,chord:[],volume:1});
            }
          }
        }
      });
      renderPatternGrid();
    });
    
    // ----- Keyboard Shortcuts -----
    document.body.addEventListener("keydown", e=>{
      const pos = state.editPos;
      // Navigation
      if(e.target.tagName==="INPUT") return;
      if(e.key==="ArrowRight"){
        e.preventDefault();
        pos.col++;
        if(pos.col >= state.instruments.length) pos.col=0;
        renderPatternGrid();
      }
      else if(e.key==="ArrowLeft"){
        e.preventDefault();
        pos.col--;
        if(pos.col < 0) pos.col=state.instruments.length-1;
        renderPatternGrid();
      }
      else if(e.key==="ArrowDown"){
        e.preventDefault();
        pos.row++;
        if(pos.row >= state.rowsPerPattern) pos.row=0;
        renderPatternGrid();
      }
      else if(e.key==="ArrowUp"){
        e.preventDefault();
        pos.row--;
        if(pos.row < 0) pos.row=state.rowsPerPattern-1;
        renderPatternGrid();
      }
      else if(e.key==="Enter"){
        e.preventDefault();
        // Edit cell
        const cells = document.querySelectorAll(".cell");
        const idx = 1 + pos.row * (state.instruments.length + 1) + (pos.col + 1);
        const cell = cells[idx];
        if(cell) startEditingCell(cell);
      }
    });
    
    // ----- Share: Encode/Decode State -----
    function encodeState() {
      // We minimize size by encoding only essential data:
      let data = {
        bpm: state.bpm,
        patterns: state.patterns,
        instruments: state.instruments,
      };
      return encodeURIComponent(btoa(JSON.stringify(data)));
    }
    
    function decodeState(str) {
      try {
        const json = atob(decodeURIComponent(str));
        const data = JSON.parse(json);
        if(data.bpm) state.bpm = data.bpm;
        if(data.patterns) state.patterns = data.patterns;
        if(data.instruments) state.instruments = data.instruments;
        state.numPatterns = state.patterns.length;
        state.rowsPerPattern = state.patterns[0]?.length || 16;
      } catch(e) {
        alert("Failed to load song data.");
      }
    }
    
    shareBtn.addEventListener("click", e=>{
      const hash = encodeState();
      const url = window.location.origin + window.location.pathname + '/#' + hash;
      prompt("Share URL:", url);
    });
    
    // On load: check hash
    window.addEventListener("load", e=>{
      if(window.location.hash.length>1){
        decodeState(window.location.hash.slice(1));
      } else {
        init();
      }
      renderPatternSelector();
      renderInstruments();
      renderPatternGrid();
      bpmInput.value = state.bpm;
      rowsPerPatternInput.value = state.rowsPerPattern;
      numPatternsInput.value = state.numPatterns;
    });
    
    // Stop playback on page unload (good practice)
    window.addEventListener("beforeunload", e=>{
      stopPlayback();
    });
    
    // Play/Stop buttons
    playBtn.addEventListener("click", e=>{
      startPlayback();
    });
    stopBtn.addEventListener("click", e=>{
      stopPlayback();
    });
    
    })();
    </script>
    </body>
    </html>
    

    Usage notes

    • Click a cell (row/instrument) to enter a note or chord (only single note supported for now).
    • Use arrow keys to move selection.
    • Press Enter to edit note at selected cell.
    • Play/Stop buttons play pattern with BPM timing.
    • Instruments configurable with waveform, volume, detune, ADSR, filter, noise mix.
    • Toolbar supports copying/pasting entire pattern, duplicating pattern, clearing it, toggling loop.
    • Share your song by clicking the Share button; this encodes your song data as a base64 JSON in the URL after the hash.
    • Open the URL with hash to load an encoded song.
    • Max 16 patterns; adjustable rows per pattern.

    What this is not

    • Complete chord support (could be extended).
    • No advanced FX or custom waveforms beyond standard oscillator types.
    • UI is minimal but functional; can be improved.
    • No demo/play data included by default, as requested.

    If you want me to expand it (e.g. chord support, custom waveforms, multiple synth oscillators per instrument), just ask!

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