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

chiptune sequencer adsr osc filter fm detune synth track share "/#" html

  1. User

    chiptune sequencer adsr osc filter fm detune synth track share "/#" html

  2. Assistant

    Certainly! Below is a simple example of a chiptune-style synthesizer implemented in HTML and JavaScript using the Web Audio API. It includes the following features:

    • Sequencer: A step sequencer that plays a sequence of notes.
    • ADSR: Basic Attack, Decay, Sustain, Release envelope control.
    • Oscillator: Triangle wave (typical for chiptune sounds).
    • Filter: Low-pass filter.
    • FM (Frequency Modulation): Simple FM synthesis modulation.
    • Detune: Fine-tuning the oscillator pitch.
    • Synth Track: Ability to play a sequence and share the track data via the URL hash.

    How it works

    • You can enter a custom sequence of notes (C4, D4, E4, etc.).
    • Control ADSR envelope parameters via sliders.
    • Adjust filter cutoff frequency.
    • Set FM modulation amount.
    • Detune oscillator frequency.
    • Play/pause the sequence.
    • Share the current settings & sequence by copying the URL (they get serialized into the URL hash).

    Full Code

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Chiptune Synth Sequencer</title>
    <style>
      body {
        font-family: monospace, monospace;
        background: #1e1e1e;
        color: #eee;
        margin: 0;
        padding: 1rem;
      }
      input[type=range] {
        width: 100%;
      }
      label {
        display: block;
        margin-top: 10px;
      }
      textarea {
        width: 100%;
        height: 5rem;
        background: #2e2e2e;
        color: #eee;
        border: none;
        resize: vertical;
      }
      button {
        margin-top: 10px;
        padding: 0.5rem 1rem;
        background: #007acc;
        border: none;
        color: white;
        cursor: pointer;
      }
      button:hover {
        background: #005f99;
      }
      .container {
        max-width: 600px;
        margin: auto;
      }
      .row {
        margin-top: 10px;
      }
      .flex {
        display: flex;
        gap: 10px;
      }
      .flex > div {
        flex: 1;
      }
      small {
        color: #aaa;
      }
    </style>
    </head>
    <body>
    <div class="container">
      <h1>Chiptune Synth Sequencer</h1>
    
      <label for="sequence">Sequence (notes separated by space, use rests as "-"):</label>
      <textarea id="sequence" placeholder="C4 E4 G4 C5 - G4 E4 C4"></textarea>
    
      <div class="row flex">
        <div>
          <label>Attack <small>(ms)</small>
            <input type="range" id="attack" min="0" max="1000" value="50" />
          </label>
        </div>
        <div>
          <label>Decay <small>(ms)</small>
            <input type="range" id="decay" min="0" max="1000" value="100" />
          </label>
        </div>
        <div>
          <label>Sustain <small>(0-1)</small>
            <input type="range" id="sustain" min="0" max="1" step="0.01" value="0.7" />
          </label>
        </div>
        <div>
          <label>Release <small>(ms)</small>
            <input type="range" id="release" min="0" max="1000" value="200" />
          </label>
        </div>
      </div>
    
      <div class="row flex">
        <div>
          <label>Filter Cutoff <small>(Hz)</small>
            <input type="range" id="filterCutoff" min="500" max="5000" value="2000" />
          </label>
        </div>
        <div>
          <label>FM Amount <small>(Hz)</small>
            <input type="range" id="fmAmount" min="0" max="1000" value="0" />
          </label>
        </div>
        <div>
          <label>Detune <small>(cents)</small>
            <input type="range" id="detune" min="-100" max="100" value="0" />
          </label>
        </div>
      </div>
    
      <button id="playBtn">Play</button>
      <button id="shareBtn">Copy Share URL</button>
      <p id="status"></p>
    </div>
    
    <script>
    (() => {
      const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
      const seqInput = document.getElementById('sequence');
      const attackInput = document.getElementById('attack');
      const decayInput = document.getElementById('decay');
      const sustainInput = document.getElementById('sustain');
      const releaseInput = document.getElementById('release');
      const filterCutoffInput = document.getElementById('filterCutoff');
      const fmAmountInput = document.getElementById('fmAmount');
      const detuneInput = document.getElementById('detune');
      const playBtn = document.getElementById('playBtn');
      const shareBtn = document.getElementById('shareBtn');
      const status = document.getElementById('status');
    
      let isPlaying = false;
      let currentStep = 0;
      let timerId = null;
      let tempo = 120; // BPM
      const stepDuration = 0.25; // quarter note, i.e. 16 steps per bar
    
      // Note frequency helpers (basic equal temperament)
      const noteFreqMap = (() => {
        const A4 = 440;
        const notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
        let map = {};
        for (let octave = 0; octave <= 8; octave++) {
          for (let i = 0; i < notes.length; i++) {
            let key = notes[i] + octave;
            let n = i + 12 * (octave - 4);
            let freq = A4 * Math.pow(2, n / 12);
            map[key] = freq;
          }
        }
        return map;
      })();
    
      // Parse sequence into frequencies or null for rests
      function parseSequence(seq) {
        return seq.trim().split(/\s+/).map(note => {
          if (note === '-' || note.toLowerCase() === 'rest') return null;
          if (noteFreqMap[note]) return noteFreqMap[note];
          // Try to parse scientific note format e.g. c#4 or d4 lowercase:
          const m = note.match(/^([a-gA-G])(#?)(\d)$/);
          if (m) {
            const noteName = m[1].toUpperCase() + (m[2] || '') + m[3];
            if (noteFreqMap[noteName]) return noteFreqMap[noteName];
          }
          return null;
        });
      }
    
      // Simple ADSR envelope gain automation
      function applyEnvelope(gainNode, now, attack, decay, sustain, release, noteDuration) {
        gainNode.gain.cancelScheduledValues(now);
        gainNode.gain.setValueAtTime(0.0001, now);
        gainNode.gain.exponentialRampToValueAtTime(1, now + attack);
        gainNode.gain.exponentialRampToValueAtTime(sustain, now + attack + decay);
        // release after note duration
        gainNode.gain.setValueAtTime(sustain, now + noteDuration);
        gainNode.gain.exponentialRampToValueAtTime(0.0001, now + noteDuration + release);
      }
    
      // Create and play a single note with FM synthesis, detune, filter, and ADSR
      function playNote(freq, duration, params) {
        if (!freq) return;
        const now = audioCtx.currentTime;
        const { attack, decay, sustain, release, filterCutoff, fmAmount, detune } = params;
    
        // Oscillator (carrier)
        const osc = audioCtx.createOscillator();
        osc.type = 'triangle';
        osc.frequency.setValueAtTime(freq, now);
        osc.detune.setValueAtTime(detune, now);
    
        // FM oscillator (modulator)
        const fmOsc = audioCtx.createOscillator();
        fmOsc.type = 'square';
        fmOsc.frequency.setValueAtTime(2, now); // low freq modulator
        const fmGain = audioCtx.createGain();
        fmGain.gain.setValueAtTime(fmAmount, now);
    
        // Connect FM oscillator to carrier freq
        fmOsc.connect(fmGain);
        fmGain.connect(osc.frequency);
    
        // Filter
        const filter = audioCtx.createBiquadFilter();
        filter.type = 'lowpass';
        filter.frequency.setValueAtTime(filterCutoff, now);
    
        // Output gain (for ADSR)
        const gainNode = audioCtx.createGain();
    
        // Connect node chain: osc -> filter -> gain -> destination
        osc.connect(filter);
        filter.connect(gainNode);
        gainNode.connect(audioCtx.destination);
    
        // Start oscillators
        osc.start(now);
        fmOsc.start(now);
    
        // Apply envelope
        applyEnvelope(gainNode, now, attack, decay, sustain, release, duration);
    
        // Stop oscillators after envelope completes
        const stopTime = now + duration + release + 0.1;
        osc.stop(stopTime);
        fmOsc.stop(stopTime);
      }
    
      // Play sequence step by step
      function playSequence() {
        if (!isPlaying) return;
        const seq = parseSequence(seqInput.value);
        const params = {
          attack: +attackInput.value / 1000,
          decay: +decayInput.value / 1000,
          sustain: +sustainInput.value,
          release: +releaseInput.value / 1000,
          filterCutoff: +filterCutoffInput.value,
          fmAmount: +fmAmountInput.value,
          detune: +detuneInput.value
        };
    
        const freq = seq[currentStep % seq.length];
        playNote(freq, stepDuration, params);
    
        currentStep++;
        timerId = setTimeout(playSequence, (60 / tempo) * 1000 * stepDuration);
      }
    
      // Start playback
      function start() {
        if (audioCtx.state === 'suspended') {
          audioCtx.resume();
        }
        if (isPlaying) return;
        if (!seqInput.value.trim()) {
          status.textContent = 'Please enter a sequence first.';
          return;
        }
        currentStep = 0;
        isPlaying = true;
        playBtn.textContent = 'Stop';
        status.textContent = 'Playing...';
        playSequence();
      }
    
      // Stop playback
      function stop() {
        isPlaying = false;
        clearTimeout(timerId);
        playBtn.textContent = 'Play';
        status.textContent = 'Stopped.';
      }
    
      // Toggle play/stop
      playBtn.addEventListener('click', () => {
        if (isPlaying) {
          stop();
        } else {
          start();
        }
      });
    
      // Share track by encoding sequence and params into URL hash
      function serializeState() {
        const state = {
          seq: seqInput.value.trim(),
          attack: attackInput.value,
          decay: decayInput.value,
          sustain: sustainInput.value,
          release: releaseInput.value,
          filterCutoff: filterCutoffInput.value,
          fmAmount: fmAmountInput.value,
          detune: detuneInput.value
        };
        return btoa(JSON.stringify(state));
      }
    
      // Load state from URL hash if available
      function loadState() {
        try {
          if (location.hash.length > 2) {
            const decoded = atob(location.hash.substring(2));
            const state = JSON.parse(decoded);
            if (state.seq) seqInput.value = state.seq;
            if (state.attack) attackInput.value = state.attack;
            if (state.decay) decayInput.value = state.decay;
            if (state.sustain) sustainInput.value = state.sustain;
            if (state.release) releaseInput.value = state.release;
            if (state.filterCutoff) filterCutoffInput.value = state.filterCutoff;
            if (state.fmAmount) fmAmountInput.value = state.fmAmount;
            if (state.detune) detuneInput.value = state.detune;
    
            status.textContent = 'Loaded track from URL.';
          }
        } catch (e) {
          console.warn('Failed to load track from URL', e);
        }
      }
    
      // Share button handling
      shareBtn.addEventListener('click', () => {
        const encoded = serializeState();
        const shareUrl = `${location.origin}${location.pathname}#/${encoded}`;
        navigator.clipboard.writeText(shareUrl).then(() => {
          status.textContent = 'Share URL copied to clipboard!';
        }).catch(() => {
          status.textContent = 'Failed to copy to clipboard.';
        });
      });
    
      // Load from URL on startup
      window.addEventListener('load', () => {
        loadState();
      });
    })();
    </script>
    </body>
    </html>
    

    How to use:

    1. Paste the code into an .html file.
    2. Open it with a modern browser (Chrome, Firefox, Edge).
    3. Enter a sequence of notes separated by spaces (e.g., C4 E4 G4 C5 - G4 E4 C4).
      • Use - or rest for silent steps.
    4. Adjust ADSR, filter cutoff, FM amount, and detune as desired.
    5. Click Play to start the sequencer.
    6. Click Copy Share URL to generate a URL with your current track/settings encoded in the hash.
    7. Share the URL with others or save it to reload your track later.

    If you'd like me to add MIDI input, export features, or advanced waveforms, just ask!

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