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

chiptune tracker adsr osc filter fm detune synth rows tracks per patterns rows per…

  1. User

    chiptune tracker adsr osc filter fm detune synth rows tracks per patterns rows per patterns bpm share "/#" html no demo

  2. Assistant

    Certainly! Below is a minimal, no-demo, self-contained HTML chiptune-style synth tracker interface prototype that includes:

    • A basic tracker UI with:
      • Tracks
      • Rows per pattern
      • Patterns
    • Controls that affect the synth engine:
      • ADSR envelope
      • Oscillator type selection
      • Filter cutoff
      • FM amount
      • Detune amount
    • Tempo control (BPM)
    • Sharing state in URL hash (/#), serializing the current patterns and synth settings as a compact JSON string
    • No external dependencies, no audio demo autoplay, just the UI with sound triggered on user interaction (play/stop)
    • Audio engine using Web Audio API with:
      • Oscillator (square, triangle, sawtooth, sine)
      • ADSR envelope
      • Simple lowpass filter
      • FM synthesis via frequency modulation oscillator
      • Detune parameter

    How it works:

    • The tracker patterns are a grid of notes (C-4 to B-5) or empty.
    • You can input notes by clicking cells.
    • Play button will play the pattern loop at set BPM.
    • ADSR, Oscillator, Filter, FM, and Detune are adjustable.
    • Patterns and synth parameters are saved/loaded from the URL hash (/#).
    • Sharing the URL will restore the current state.

    Usage:

    • Open the page.
    • Set rows per pattern (default 16), number of tracks (default 4).
    • Click the pattern cells to insert notes; click again to clear.
    • Adjust ADSR, oscillator, filter, fm, detune, bpm sliders.
    • Click Play to start/stop playback.
    • Copy the URL and share the link; the pattern and controls will be restored.

    Code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Chiptune Tracker ADSR FM Synth</title>
    <style>
      body {
        font-family: monospace, monospace;
        background: #111;
        color: #eee;
        margin: 0; padding: 0; 
        display: flex; flex-direction: column; align-items: center;
      }
      h1 {
        margin: 0.5em;
        font-weight: normal;
      }
      #controls, #tracker, #status {
        max-width: 960px;
        width: 100%;
        padding: 1em;
        box-sizing: border-box;
        user-select: none;
      }
      #controls {
        display: flex;
        flex-wrap: wrap;
        gap: 1em;
        justify-content: center;
      }
      .control-group {
        display: flex;
        flex-direction: column;
        margin-bottom: 0.5em;
        min-width: 140px;
      }
      label {
        font-size: 0.8em;
        margin-bottom: 0.2em;
      }
      input[type=range], select, input[type=number] {
        width: 100%;
      }
      #tracker {
        overflow-x: auto;
      }
      table {
        border-collapse: collapse;
        width: 100%;
        user-select: none;
      }
      thead tr {
        background: #222;
        color: #8f8;
      }
      th, td {
        border: 1px solid #333;
        padding: 0.1em 0.3em;
        text-align: center;
        font-variant-numeric: tabular-nums;
        cursor: pointer;
        width: 2.2em;
        height: 1.6em;
      }
      td.empty {
        color: #555;
      }
      td.note {
        background: #184; 
        color: #afa;
        font-weight: bold;
      }
      td.playing {
        background: #4a4;
      }
      button {
        background: #282;
        color: #ddd;
        border: none;
        padding: 0.4em 1em;
        font-weight: bold;
        cursor: pointer;
      }
      button:active {
        background: #3c3;
      }
      #share-info {
        font-size: 0.8em;
        color: #888;
        text-align: center;
        margin-top: 0.3em;
      }
      @media (max-width: 600px) {
        #controls {
          flex-direction: column;
          align-items: center;
        }
        .control-group{
          min-width: unset;
          width: 90vw;
        }
        table td, table th {
          width: 1.6em;
          height: 1.3em;
          font-size: 0.8em;
        }
      }
    </style>
    </head>
    <body>
    
    <h1>Chiptune Tracker - ADSR FM Synth</h1>
    
    <div id="controls">
    
      <div class="control-group">
        <label for="bpm">Tempo (BPM)</label>
        <input type="number" id="bpm" min="30" max="300" step="1" value="140" />
      </div>
    
      <div class="control-group">
        <label for="rowsPerPattern">Rows per Pattern</label>
        <input type="number" id="rowsPerPattern" min="4" max="64" step="1" value="16" />
      </div>
    
      <div class="control-group">
        <label for="tracksCount">Tracks (Channels)</label>
        <input type="number" id="tracksCount" min="1" max="8" step="1" value="4" />
      </div>
    
      <div class="control-group">
        <label for="oscType">Oscillator</label>
        <select id="oscType">
          <option value="square">Square</option>
          <option value="triangle">Triangle</option>
          <option value="sawtooth">Sawtooth</option>
          <option value="sine">Sine</option>
        </select>
      </div>
    
      <div class="control-group">
        <label for="attack">Attack (ms)</label>
        <input type="range" id="attack" min="0" max="1000" step="10" value="10" />
      </div>
      <div class="control-group">
        <label for="decay">Decay (ms)</label>
        <input type="range" id="decay" min="0" max="1000" step="10" value="50" />
      </div>
      <div class="control-group">
        <label for="sustain">Sustain (0-1)</label>
        <input type="range" id="sustain" min="0" max="1" step="0.01" value="0.6" />
      </div>
      <div class="control-group">
        <label for="release">Release (ms)</label>
        <input type="range" id="release" min="0" max="2000" step="10" value="150" />
      </div>
    
      <div class="control-group">
        <label for="filterCutoff">Filter Cutoff (Hz)</label>
        <input type="range" id="filterCutoff" min="100" max="8000" step="10" value="4000" />
      </div>
    
      <div class="control-group">
        <label for="fmAmount">FM Amount (Hz)</label>
        <input type="range" id="fmAmount" min="0" max="1000" step="1" value="0" />
      </div>
    
      <div class="control-group">
        <label for="detuneCents">Detune (cents)</label>
        <input type="range" id="detuneCents" min="-50" max="50" step="1" value="0" />
      </div>
    
    </div>
    
    <div style="text-align:center; margin: 0.5em;">
      <button id="playBtn">Play</button>
    </div>
    
    <div id="tracker"></div>
    
    <div id="share-info">
      URL contains pattern + settings for sharing -- simply copy and share.
    </div>
    
    <script>
    (() => {
    
    // Notes from C-4 to B-5 (two octaves)
    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"
    ];
    
    // Mapping notes to frequencies
    function noteToFrequency(note) {
      const noteNames = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
      let notePart = note.slice(0, note.length-2);
      let octave = parseInt(note.slice(-1));
      let semitone = noteNames.indexOf(notePart);
      if(semitone === -1) return null;
      // Formula for equal temperament A4 = 440Hz
      let n = semitone + (octave - 4) * 12;
      let freq = 440 * Math.pow(2, (n - 9) / 12);
      return freq;
    }
    
    // Create the tracker data structure: patterns -> rows -> tracks -> note string/null
    // For simplicity just one pattern now with fixed rows and tracks,
    // but UI allows changing rows and tracks counts
    let patternData = [];
    
    // Global settings
    let settings = {
      bpm: 140,
      rowsPerPattern: 16,
      tracksCount: 4,
      oscType: "square",
      attack: 0.01,
      decay: 0.05,
      sustain: 0.6,
      release: 0.15,
      filterCutoff: 4000,
      fmAmount: 0,
      detune: 0,
    };
    
    // Elements references
    const bpmEl = document.getElementById("bpm");
    const rowsPerPatternEl = document.getElementById("rowsPerPattern");
    const tracksCountEl = document.getElementById("tracksCount");
    const oscTypeEl = document.getElementById("oscType");
    const attackEl = document.getElementById("attack");
    const decayEl = document.getElementById("decay");
    const sustainEl = document.getElementById("sustain");
    const releaseEl = document.getElementById("release");
    const filterCutoffEl = document.getElementById("filterCutoff");
    const fmAmountEl = document.getElementById("fmAmount");
    const detuneEl = document.getElementById("detuneCents");
    const playBtn = document.getElementById("playBtn");
    const trackerDiv = document.getElementById("tracker");
    
    
    // State
    let audioCtx;
    let isPlaying = false;
    let currentRow = 0;
    let playInterval;
    let columns, rows;
    let decodedPattern; // loaded from URL or fresh
    
    // Init AudioContext (delayed until user interaction to avoid autoplay restriction)
    function createAudioContext() {
      if(audioCtx) return;
      audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    }
    
    // Initialize Pattern Data array with empty notes
    function initializePattern(rowsCount, tracksCount) {
      patternData = [];
      for(let r=0; r<rowsCount; r++) {
        let row = [];
        for(let t=0; t<tracksCount; t++) {
          row.push(null);
        }
        patternData.push(row);
      }
    }
    
    // Build the tracker table UI
    function buildTracker() {
      trackerDiv.innerHTML = "";
      const table = document.createElement("table");
      const thead = document.createElement("thead");
      const trHead = document.createElement("tr");
      const thRow = document.createElement("th");
      thRow.textContent = "Row";
      trHead.appendChild(thRow);
      for(let c=0; c<settings.tracksCount; c++) {
        const th = document.createElement("th");
        th.textContent = "Track " + (c+1);
        trHead.appendChild(th);
      }
      thead.appendChild(trHead);
      table.appendChild(thead);
    
      const tbody = document.createElement("tbody");
      for(let r=0; r<settings.rowsPerPattern; r++) {
        const tr = document.createElement("tr");
        const thRowNumber = document.createElement("th");
        thRowNumber.textContent = r+1;
        tr.appendChild(thRowNumber);
        for(let c=0; c<settings.tracksCount; c++) {
          const td = document.createElement("td");
          td.classList.add("empty");
          const note = patternData[r][c];
          if(note) {
            td.textContent = note;
            td.classList.remove("empty");
            td.classList.add("note");
          }
          td.dataset.row = r;
          td.dataset.track = c;
    
          td.title = 'Click to cycle note';
          td.addEventListener("click", () => {
            cycleNoteAtCell(r,c);
          });
          tr.appendChild(td);
        }
        tbody.appendChild(tr);
      }
      table.appendChild(tbody);
      trackerDiv.appendChild(table);
    }
    
    // Cycle note in a cell through NOTES + null (empty)
    function cycleNoteAtCell(r,c) {
      let current = patternData[r][c];
      let idx = current ? NOTES.indexOf(current) : -1;
      idx++;
      if(idx >= NOTES.length) idx = -1; // wrap to empty
      patternData[r][c] = idx === -1 ? null : NOTES[idx];
      buildTracker();
      updateShareUrl();
    }
    
    // Handle control changes
    function handleControlChanges() {
      settings.bpm = Math.min(300, Math.max(30, +bpmEl.value));
      let newRows = Math.min(64, Math.max(4, +rowsPerPatternEl.value));
      let newTracks = Math.min(8, Math.max(1, +tracksCountEl.value));
      if(newRows !== settings.rowsPerPattern || newTracks !== settings.tracksCount) {
        // Resize patternData accordingly - naive reset
        settings.rowsPerPattern = newRows;
        settings.tracksCount = newTracks;
        initializePattern(settings.rowsPerPattern, settings.tracksCount);
      }
      settings.oscType = oscTypeEl.value;
      settings.attack = +attackEl.value/1000;
      settings.decay = +decayEl.value/1000;
      settings.sustain = +sustainEl.value;
      settings.release = +releaseEl.value/1000;
      settings.filterCutoff = +filterCutoffEl.value;
      settings.fmAmount = +fmAmountEl.value;
      settings.detune = +detuneEl.value;
      buildTracker();
      updateShareUrl();
    }
    
    // Serialize data to compact JSON and put in URL hash
    function updateShareUrl() {
      try {
        // patternData likely large; we'll store only note indices (for min size)
        // note index -1 = empty
        const patternEncoded = patternData.map(row => row.map(n => (n ? NOTES.indexOf(n) : -1)));
        const data = {
          s: settings,
          p: patternEncoded,
        };
        const json = JSON.stringify(data);
        // compress & base64 encode could be done but here just encoded URI
        const compressed = encodeURIComponent(json);
        window.history.replaceState(null,null,"/#"+compressed);
      } catch(e){ /* ignore */ }
    }
    
    // Load from URL hash if present
    function loadFromUrl() {
      try {
        if(location.hash.length < 3) return false;
        let hash = location.hash.slice(2);
        const json = decodeURIComponent(hash);
        const data = JSON.parse(json);
        if(data.s && data.p) {
          // Restore settings
          Object.assign(settings, data.s);
    
          // Set controls values
          bpmEl.value = settings.bpm;
          rowsPerPatternEl.value = settings.rowsPerPattern;
          tracksCountEl.value = settings.tracksCount;
          oscTypeEl.value = settings.oscType;
          attackEl.value = Math.round(settings.attack*1000);
          decayEl.value = Math.round(settings.decay*1000);
          sustainEl.value = settings.sustain;
          releaseEl.value = Math.round(settings.release*1000);
          filterCutoffEl.value = settings.filterCutoff;
          fmAmountEl.value = settings.fmAmount;
          detuneEl.value = settings.detune;
    
          // Convert pattern encoded back to patternData as notes/null
          if(Array.isArray(data.p) && data.p.length === settings.rowsPerPattern) {
            patternData = data.p.map(row => row.map(idx => (idx >= 0 && idx < NOTES.length) ? NOTES[idx] : null));
            return true;
          }
        }
      } catch(e){ }
      return false;
    }
    
    
    // --- Audio Synth Engine ---
    
    // Play one note with ADSR + filter + FM + detune
    function playNoteAt(freq) {
      if(!audioCtx) return;
    
      const now = audioCtx.currentTime;
    
      // Carrier osc
      const osc = audioCtx.createOscillator();
      osc.type = settings.oscType;
      osc.frequency.value = freq * Math.pow(2, settings.detune/1200);
    
      // FM osc
      const fmOsc = audioCtx.createOscillator();
      fmOsc.type = "sine";
      const fmGain = audioCtx.createGain();
      fmGain.gain.value = settings.fmAmount;
    
      fmOsc.connect(fmGain);
      fmGain.connect(osc.frequency);
    
      // Filter
      const filter = audioCtx.createBiquadFilter();
      filter.type = "lowpass";
      filter.frequency.value = settings.filterCutoff;
    
      // Gain node for ADSR envelope
      const gainNode = audioCtx.createGain();
      gainNode.gain.setValueAtTime(0, now);
    
      // Connect chain
      osc.connect(filter);
      filter.connect(gainNode);
      gainNode.connect(audioCtx.destination);
    
      // ADSR envelope
      const a = settings.attack;
      const d = settings.decay;
      const s = settings.sustain;
      const r = settings.release;
      // Attack
      gainNode.gain.linearRampToValueAtTime(1, now + a);
      // Decay to sustain
      gainNode.gain.linearRampToValueAtTime(s, now + a + d);
    
      // Start oscillators
      osc.start(now);
      fmOsc.start(now);
    
      // Stop note after length (we'll assume a 1/4 pulse)
      const noteDuration = (60 / settings.bpm) * 4 / settings.rowsPerPattern; 
      const stopTime = now + noteDuration;
      // Release ramp starting at stopTime
      gainNode.gain.setTargetAtTime(0, stopTime, r/3);
    
      osc.stop(stopTime + r + 0.1);
      fmOsc.stop(stopTime + r + 0.1);
    
      // Clean up on ended event
      osc.onended = () => {
        osc.disconnect();
        fmOsc.disconnect();
        fmGain.disconnect();
        filter.disconnect();
        gainNode.disconnect();
      };
    }
    
    // Play the pattern
    function playPattern() {
      if(!audioCtx) createAudioContext();
      if(isPlaying) return;
      if(!patternData.length) return;
    
      isPlaying = true;
      currentRow = 0;
      playBtn.textContent = "Stop";
    
      const intervalMs = (60 / settings.bpm) * 1000 / (settings.rowsPerPattern / 4);
      // Actually play one tick step based on rowsPerPattern
    
      const tableRows = trackerDiv.querySelectorAll("tbody tr");
    
      playInterval = setInterval(() => {
        // Highlight current playing row
        tableRows.forEach((tr,i) => {
          if(i === currentRow) {
            tr.classList.add("playing");
          } else {
            tr.classList.remove("playing");
          }
        });
    
        // Play all notes at current row
        const rowData = patternData[currentRow];
        for(let track = 0; track < settings.tracksCount; track++) {
          const note = rowData[track];
          if(note) {
            const freq = noteToFrequency(note);
            if(freq > 0) playNoteAt(freq);
          }
        }
    
        currentRow++;
        if(currentRow >= settings.rowsPerPattern) {
          currentRow = 0;
        }
    
      }, (60 / settings.bpm) * 1000 / (settings.rowsPerPattern / 4));
    }
    
    // Stop playback
    function stopPattern() {
      if(!isPlaying) return;
      isPlaying = false;
      playBtn.textContent = "Play";
      clearInterval(playInterval);
      const tableRows = trackerDiv.querySelectorAll("tbody tr");
      tableRows.forEach(tr => tr.classList.remove("playing"));
    }
    
    // Event listeners
    
    bpmEl.addEventListener("change", () => {
      settings.bpm = +bpmEl.value;
      updateShareUrl();
      if(isPlaying) {
        stopPattern();
        playPattern();
      }
    });
    rowsPerPatternEl.addEventListener("change", () => {
      handleControlChanges();
      if(isPlaying) stopPattern();
    });
    tracksCountEl.addEventListener("change", () => {
      handleControlChanges();
      if(isPlaying) stopPattern();
    });
    oscTypeEl.addEventListener("change", () => {
      handleControlChanges();
    });
    attackEl.addEventListener("input", () => {
      settings.attack = +attackEl.value / 1000;
      updateShareUrl();
    });
    decayEl.addEventListener("input", () => {
      settings.decay = +decayEl.value / 1000;
      updateShareUrl();
    });
    sustainEl.addEventListener("input", () => {
      settings.sustain = +sustainEl.value;
      updateShareUrl();
    });
    releaseEl.addEventListener("input", () => {
      settings.release = +releaseEl.value / 1000;
      updateShareUrl();
    });
    filterCutoffEl.addEventListener("input", () => {
      settings.filterCutoff = +filterCutoffEl.value;
      updateShareUrl();
    });
    fmAmountEl.addEventListener("input", () => {
      settings.fmAmount = +fmAmountEl.value;
      updateShareUrl();
    });
    detuneEl.addEventListener("input", () => {
      settings.detune = +detuneEl.value;
      updateShareUrl();
    });
    
    playBtn.addEventListener("click", () => {
      createAudioContext(); // user interaction enables sound
      if(isPlaying) {
        stopPattern();
      } else {
        playPattern();
      }
    });
    
    // Initialize
    let loaded = loadFromUrl();
    if(!loaded) {
      initializePattern(settings.rowsPerPattern, settings.tracksCount);
    }
    buildTracker();
    
    })();
    </script>
    
    </body>
    </html>
    

    This code is designed to be a fully self-contained chiptune tracker + FM synth in HTML + JS, with ADSR, osc/filter/fm/detune controls, pattern editor grid, playback at BPM, and URL hash sharing support.

    Open this in a modern browser, click Play, add notes, edit settings, and share the URL to preserve current pattern and settings.

    If you'd like any further feature or customization, just ask!