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

html css js rhythm game editor bpm load audio url play note record bars count rhythm…

  1. User

    html css js rhythm game editor bpm load audio url play note record bars count rhythm shortcuts delete share "#/"

  2. Assistant

    Creating a simple rhythm game editor with the following features:

    • Load audio from a URL
    • Play/pause audio
    • Show a timeline grid based on BPM and bars
    • Allow placing/removing notes on the grid (record mode)
    • Use keyboard shortcuts for navigation and editing
    • Display current note count
    • Ability to share/export the rhythm data via URL hash "#/..."

    I'll create a minimal but functional prototype in HTML/CSS/JS.


    Features plan:

    • Audio Loading: Input to enter audio URL, loads and plays it
    • BPM Input: Change BPM, default 120
    • Bars Input: Number of bars to display (e.g. 4 bars)
    • Timeline Grid: Divided into beats/subdivisions (e.g. 4 beats per bar, 4 subdivisions per beat)
    • Note Editor: Clicking grid toggles notes for that beat subdivision
    • Play: Plays audio in sync with grid highlight
    • Shortcuts:
      • Space: Play/pause audio
      • Arrow Left/Right: Move current bar view
      • Delete/Backspace: Delete selected note
      • R: Toggle record mode (allow placing notes)
    • Share: Export rhythm data (BPM, bars, note positions) into URL hash base64 encoded JSON; Loading the page with a hash loads editor state
    • Display: Number of notes currently placed

    Code

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Rhythm Game Editor</title>
    <style>
      body {
        font-family: monospace, monospace;
        margin: 0; padding: 0;
        background: #111;
        color: #eee;
        display: flex;
        flex-direction: column;
        height: 100vh;
        user-select: none;
      }
      header {
        padding: 10px;
        background: #222;
        display: flex;
        flex-wrap: wrap;
        gap: 12px;
        align-items: center;
      }
      header label {
        font-weight: bold;
      }
      input[type="text"], input[type="number"] {
        background: #333;
        border: none;
        color: #eee;
        padding: 4px 6px;
        width: 200px;
        border-radius: 4px;
      }
      input[type="number"] {
        width: 80px;
      }
      button {
        background: #444;
        color: #eee;
        border: none;
        padding: 6px 12px;
        border-radius: 4px;
        cursor: pointer;
      }
      button:hover {
        background: #666;
      }
      #timeline {
        flex-grow: 1;
        overflow-x: scroll;
        overflow-y: hidden;
        background: #222;
        border-top: 2px solid #555;
        border-bottom: 2px solid #555;
        white-space: nowrap;
        position: relative;
      }
      #grid {
        display: inline-grid;
        grid-auto-flow: column;
        grid-template-rows: repeat(4, 40px);
        gap: 1px;
        background: #333;
      }
      .cell {
        width: 40px;
        height: 40px;
        background: #111;
        border-radius: 4px;
        box-sizing: border-box;
        cursor: pointer;
        transition:
          background-color 0.2s,
          box-shadow 0.15s;
      }
      .cell.note {
        background: limegreen;
        box-shadow: 0 0 5px limegreen;
      }
      .cell.current {
        outline: 2px solid #ffa;
      }
      .header-row {
        position: sticky;
        top: 0;
        background: #222;
        color: #aaa;
        font-size: 14px;
        z-index: 10;
        display: grid;
        grid-auto-flow: column;
        grid-template-rows: 1fr;
        gap: 1px;
      }
      .header-cell {
        width: 40px;
        height: 30px;
        text-align: center;
        line-height: 30px;
        user-select: none;
      }
      #playhead {
        position: absolute;
        top: 0;
        bottom: 0;
        width: 2px;
        background: #ffa;
        pointer-events: none;
        transition: left 0.05s linear;
      }
      #status {
        padding: 6px 10px;
        background: #222;
        font-size: 14px;
        display: flex;
        justify-content: space-between;
      }
      #share-link {
        background: #222;
        border: none;
        color: #0af;
        font-size: 12px;
        width: 100%;
        padding: 6px 8px;
        font-family: monospace;
        resize: none;
      }
      @media (max-width: 600px) {
        header {
          flex-direction: column;
          gap: 8px;
        }
        input[type="text"] {
          width: 100%;
        }
      }
    </style>
    </head>
    <body>
    <header>
      <label>Audio URL: <input id="audioUrl" type="text" placeholder="Enter audio URL"/></label>
      <button id="loadAudioBtn">Load</button>
    
      <label>BPM: <input id="bpmInput" type="number" min="40" max="300" step="1" value="120" /></label>
      <label>Bars: <input id="barsInput" type="number" min="1" max="32" step="1" value="4" /></label>
      <button id="toggleRecordBtn" title="Toggle record mode (R)">Record: OFF</button>
      <button id="playPauseBtn" title="Play/Pause (Space)">Play</button>
      <button id="shareBtn" title="Share rhythm as URL hash">Share</button>
    </header>
    
    <div id="timeline" tabindex="0">
      <div id="headerRow" class="header-row"></div>
      <div id="grid"></div>
      <div id="playhead"></div>
    </div>
    
    <div id="status">
      <div>Notes: <span id="notesCount">0</span></div>
      <div>Current Time: <span id="currentTime">0.00</span> s</div>
    </div>
    
    <textarea id="share-link" readonly style="display:none;"></textarea>
    
    <audio id="audio" crossorigin="anonymous"></audio>
    
    <script>
    (() => {
      const audio = document.getElementById('audio');
      const audioUrlInput = document.getElementById('audioUrl');
      const loadAudioBtn = document.getElementById('loadAudioBtn');
      const bpmInput = document.getElementById('bpmInput');
      const barsInput = document.getElementById('barsInput');
      const toggleRecordBtn = document.getElementById('toggleRecordBtn');
      const playPauseBtn = document.getElementById('playPauseBtn');
      const shareBtn = document.getElementById('shareBtn');
      const shareLinkArea = document.getElementById('share-link');
    
      const timeline = document.getElementById('timeline');
      const grid = document.getElementById('grid');
      const headerRow = document.getElementById('headerRow');
      const playhead = document.getElementById('playhead');
      const notesCountElem = document.getElementById('notesCount');
      const currentTimeElem = document.getElementById('currentTime');
    
      // Constants for grid
      const tracksCount = 4; // 4 rows (e.g. drum pads)
      const subdivisionsPerBeat = 4; // 16th notes
      const beatsPerBar = 4;
    
      // State
      let bpm = +bpmInput.value;
      let bars = +barsInput.value;
      let secondsPerBeat = 60 / bpm;
      let secondsPerSubdivision = secondsPerBeat / subdivisionsPerBeat;
    
      // Note data structure: 2D array [column][track] boolean
      // column = bars * beats * subdivisionsPerBeat
      let totalColumns = bars * beatsPerBar * subdivisionsPerBeat; 
      let notes = new Map(); // key="col:row" value=true
    
      let recordMode = false;
      let playing = false;
      let animationFrameId = null;
      let startTime = 0; // audio context time of playback start
      let pauseOffset = 0;
      let currentPlayTime = 0;
    
      // Helpers
    
      function colToTime(col) {
        return col * secondsPerSubdivision;
      }
    
      function timeToCol(time) {
        return Math.floor(time / secondsPerSubdivision);
      }
    
      // Build grid & header
    
      function buildGrid() {
        totalColumns = bars * beatsPerBar * subdivisionsPerBeat;
        secondsPerBeat = 60 / bpm;
        secondsPerSubdivision = secondsPerBeat / subdivisionsPerBeat;
    
        notesCountElem.textContent = notes.size;
    
        // Clear previous content
        grid.innerHTML = '';
        headerRow.innerHTML = '';
    
        // Setup grid columns and rows CSS grid
        grid.style.gridTemplateColumns = `repeat(${totalColumns}, 40px)`;
        grid.style.gridTemplateRows = `repeat(${tracksCount}, 40px)`;
        headerRow.style.gridTemplateColumns = `repeat(${totalColumns}, 40px)`;
    
        // Header row - show beat and subdivision
        for(let col=0; col < totalColumns; col++){
          const beatIndex = Math.floor(col / subdivisionsPerBeat) % beatsPerBar + 1;
          const barIndex = Math.floor(col / (beatsPerBar * subdivisionsPerBeat)) + 1;
          const sub = (col % subdivisionsPerBeat) + 1;
    
          // Show bar and beat on first subdivision of each beat
          let text = '';
          if(sub === 1){
            text = `B${barIndex}b${beatIndex}`;
          } else {
            text = sub;
          }
          const headerCell = document.createElement('div');
          headerCell.classList.add('header-cell');
          headerCell.textContent = text;
          headerRow.appendChild(headerCell);
        }
        timeline.scrollLeft = 0;
    
        // Grid cells
        for(let row=0; row < tracksCount; row++){
          for(let col=0; col < totalColumns; col++){
            const cell = document.createElement('div');
            cell.classList.add('cell');
            const key = `${col}:${row}`;
            if(notes.has(key)){
              cell.classList.add('note');
            }
            cell.dataset.col = col;
            cell.dataset.row = row;
    
            cell.title = `Bar ${Math.floor(col/(beatsPerBar*subdivisionsPerBeat))+1}, Beat ${Math.floor((col/subdivisionsPerBeat)%beatsPerBar)+1}, Sub ${col%subdivisionsPerBeat+1}, Track ${row+1}`;
    
            // Toggle note on click if in record mode
            cell.addEventListener('click', () => {
              if(!recordMode) return;
              if(notes.has(key)){
                notes.delete(key);
                cell.classList.remove('note');
              } else {
                notes.set(key,true);
                cell.classList.add('note');
              }
              updateNotesCount();
            });
    
            grid.appendChild(cell);
          }
        }
      }
      function updateNotesCount(){
        notesCountElem.textContent = notes.size;
      }
    
      // Load audio from URL input
      loadAudioBtn.addEventListener('click', () => {
        const url = audioUrlInput.value.trim();
        if(!url){
          alert('Enter a valid audio URL');
          return;
        }
        audio.src = url;
        audio.load();
        pauseOffset = 0;
        playing = false;
        playPauseBtn.textContent = 'Play';
      });
    
      // Update BPM or bars input
      bpmInput.addEventListener('change', () => {
        const val = +bpmInput.value;
        if(val >=40 && val <=300){
          bpm = val;
          buildGrid();
          // Update timing for playback
          secondsPerBeat = 60 / bpm;
          secondsPerSubdivision = secondsPerBeat / subdivisionsPerBeat;
        }
      });
      barsInput.addEventListener('change', () => {
        const val = +barsInput.value;
        if(val >= 1 && val <= 32){
          bars = val;
          buildGrid();
        }
      });
    
      // Record mode toggle
      toggleRecordBtn.addEventListener('click', () => {
        recordMode = !recordMode;
        toggleRecordBtn.textContent = `Record: ${recordMode ? 'ON' : 'OFF'}`;
      });
    
      // Play/pause button
      playPauseBtn.addEventListener('click', () => {
        togglePlayPause();
      });
    
      function togglePlayPause(){
        if(!audio.src){
          alert('Please load an audio file');
          return;
        }
        if(playing){
          pausePlayback();
        } else {
          startPlayback();
        }
      }
      function startPlayback(){
        audio.currentTime = pauseOffset;
        audio.play();
        startTime = performance.now() - (pauseOffset*1000);
        playing = true;
        playPauseBtn.textContent = 'Pause';
        animate();
      }
    
      function pausePlayback(){
        audio.pause();
        pauseOffset = audio.currentTime;
        playing = false;
        playPauseBtn.textContent = 'Play';
        cancelAnimationFrame(animationFrameId);
      }
    
      // Animate playhead and highlight current column
      function animate(){
        animationFrameId = requestAnimationFrame(animate);
        if(!playing) return;
        currentPlayTime = (performance.now() - startTime) / 1000;
        currentTimeElem.textContent = currentPlayTime.toFixed(2);
    
        if(currentPlayTime >= audio.duration){
          pausePlayback();
          return;
        }
    
        const currentCol = timeToCol(currentPlayTime);
        const leftPx = currentCol * 41; // 40px + 1px gap
    
        // Move playhead
        playhead.style.left = leftPx + 'px';
    
        // Highlight current column
        [...grid.children].forEach(cell => {
          if( +cell.dataset.col === currentCol){
            cell.classList.add('current');
          } else {
            cell.classList.remove('current');
          }
        });
    
        // Auto scroll timeline left to keep playhead visible
        const timelineRect = timeline.getBoundingClientRect();
        const playheadX = leftPx - timeline.scrollLeft;
        if(playheadX < 80){
          timeline.scrollLeft -= 40;
        } else if(playheadX > timelineRect.width - 80){
          timeline.scrollLeft += 40;
        }
      }
    
      // Keyboard shortcuts
      timeline.addEventListener('keydown', e => {
        if(e.target !== timeline) return;
        switch(e.key.toLowerCase()){
          case ' ':
            e.preventDefault();
            togglePlayPause();
            break;
          case 'r':
            e.preventDefault();
            recordMode = !recordMode;
            toggleRecordBtn.textContent = `Record: ${recordMode ? 'ON' : 'OFF'}`;
            break;
          case 'arrowleft':
            e.preventDefault();
            timeline.scrollLeft -= bars * beatsPerBar * subdivisionsPerBeat * 20; // scroll by half viewport maybe
            break;
          case 'arrowright':
            e.preventDefault();
            timeline.scrollLeft += bars * beatsPerBar * subdivisionsPerBeat * 20;
            break;
          case 'delete':
          case 'backspace':
            // Delete notes under current playhead col if any
            e.preventDefault();
            if(!recordMode) return;
    
            // find current col from playhead left (or current time)
            const col = timeToCol(currentPlayTime);
            removeNotesAtColumn(col);
            break;
        }
      });
    
      function removeNotesAtColumn(col){
        let removed = 0;
        for(let row=0; row < tracksCount; row++){
          const key = `${col}:${row}`;
          if(notes.has(key)){
            notes.delete(key);
            removed++;
          }
        }
        if(removed > 0){
          buildGrid(); // rebuild grid to update visuals
        }
        updateNotesCount();
      }
    
      // Share/export rhythm state as base64 encoded JSON in URL hash
      shareBtn.addEventListener('click', () => {
        const data = {
          bpm,
          bars,
          notes: [...notes.keys()] // array of "col:row" strings
        };
        const json = JSON.stringify(data);
        const b64 = btoa(json);
        const url = window.location.origin + window.location.pathname + '#/' + b64;
        shareLinkArea.value = url;
        shareLinkArea.style.display = 'block';
        shareLinkArea.select();
        shareLinkArea.setSelectionRange(0, url.length);
        document.execCommand('copy');
        alert('Share URL copied to clipboard!');
      });
    
      // Load from URL hash
      function loadFromHash(){
        const hash = window.location.hash;
        if(hash.startsWith('#/')){
          try {
            const b64 = hash.slice(2);
            const decoded = atob(b64);
            const data = JSON.parse(decoded);
            if(typeof data.bpm === 'number' && typeof data.bars === 'number' && Array.isArray(data.notes)){
              bpm = data.bpm;
              bars = data.bars;
              bpmInput.value = bpm;
              barsInput.value = bars;
              notes.clear();
              data.notes.forEach(k => notes.set(k, true));
              buildGrid();
            }
          } catch(e){
            console.warn('Failed to load from hash', e);
          }
        }
      }
    
      // Initial build
      buildGrid();
      loadFromHash();
    
      // Focus timeline for keyboard shortcuts
      timeline.focus();
    
    })();
    </script>
    </body>
    </html>
    

    How to use:

    • Enter a direct audio URL (e.g. an mp3 hosted on a CORS-enabled endpoint) then click Load.
    • Set BPM and bars as you wish.
    • Click Record to enable placing notes.
    • Click the grid cells to toggle notes (green).
    • Click Play to play audio and see playhead.
    • Use Spacebar to play/pause, R to toggle record mode.
    • Use Delete or Backspace to clear notes on the current playhead column.
    • Use Left/Right arrows to scroll timeline.
    • Click Share to generate a URL you can share — it encodes the BPM, bars, and note placements.
    • Loading the page with such a URL restores the rhythm data.

    Note: This is a simple rhythm editor prototype. You can extend it for saving/loading real files, multiple instruments, different note types, etc.

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