Skip to content
The Chat Archive
o3-2025-04-16· OpenAI LMArena Human Preference 140K

Make me a Web Site for Playing Midis across multiple devices in sync with eachother,…

  1. User

    Make me a Web Site for Playing Midis across multiple devices in sync with eachother, with a track selector, there should be a host device that uploads the midis and assigns tracks to themselfs and the clients in real time with playback controls

  2. Assistant

    Below is a minimal-but-complete “proof-of-concept” that you can drop in a folder, run with Node JS, and immediately start playing synchronised MIDI files on any number of devices.
    One device becomes the host (/?host=1), uploads a .mid, assigns tracks to every connected client, and controls transport (play / pause / stop).
    All the heavy lifting on the client side is done with Tone.js, and real-time signalling is handled through Socket.IO.


    🗂️ 1. Project structure

    midi-sync/
    ├── package.json
    ├── server.js          ← Node / Express / Socket.IO backend
    └── public/
        └── index.html     ← Front-end (host + client UI in one file)
    

    📦 2. package.json

    {
      "name": "midi-sync",
      "version": "1.0.0",
      "type": "module",
      "dependencies": {
        "express": "^4.19.2",
        "multer":  "^1.4.5",
        "socket.io": "^4.7.2"
      },
      "scripts": { "start": "node server.js" }
    }
    

    Install everything:

    npm i
    

    🖥️ 3. server.js (backend)

    import express   from "express";
    import multer    from "multer";
    import http      from "http";
    import { Server } from "socket.io";
    
    const app    = express();
    const server = http.createServer(app);
    const io     = new Server(server);
    
    app.use(express.static("public"));
    const upload = multer({ storage: multer.memoryStorage() });
    
    /* ────────────────────────────────
       In-memory “state”
    ──────────────────────────────────*/
    let currentMidi = null;          // Buffer
    let midiName    = "";
    let assignments = {};            // socketId -> [trackIdx]
    
    /* ────────────────────────────────
       REST endpoint – host uploads .mid
    ──────────────────────────────────*/
    app.post("/upload", upload.single("midi"), (req, res) => {
      currentMidi = req.file.buffer;
      midiName    = req.file.originalname;
      assignments = {};
      io.emit("midi", {
        name : midiName,
        data : currentMidi.toString("base64")
      });
      res.sendStatus(200);
    });
    
    /* ────────────────────────────────
       WebSocket handling
    ──────────────────────────────────*/
    io.on("connection", socket => {
      console.log("⚡ Client", socket.id);
    
      // Send existing MIDI to late joiners
      if (currentMidi) {
        socket.emit("midi", { name: midiName, data: currentMidi.toString("base64") });
      }
    
      // Track assignment (host → clients)
      socket.on("assignTracks", ({ targetId, tracks }) => {
        assignments[targetId] = tracks;
        io.to(targetId).emit("assigned", tracks);
      });
    
      // Transport control (broadcast to all)
      socket.on("play",  start => io.emit("play",  start));
      socket.on("pause", ()    => io.emit("pause"));
      socket.on("stop",  ()    => io.emit("stop"));
    
      // Host asks who is online
      socket.on("requestClientList", () => {
        const clients = Array.from(io.sockets.sockets.values())
                             .map(s => ({ id: s.id }));
        socket.emit("clientList", clients);
      });
    
      socket.on("disconnect", () => {
        delete assignments[socket.id];
        io.emit("clientDisconnected", socket.id);
      });
    });
    
    server.listen(3000, () => console.log("🚀 http://localhost:3000"));
    

    🌐 4. public/index.html (front-end)

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>MIDI Sync Playground</title>
    
      <!-- Socket.IO -->
      <script src="https://cdn.jsdelivr.net/npm/socket.io@4.7.2/dist/socket.io.min.js"></script>
      <!-- Tone.js (MIDI parser + synth + transport) -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/tone/14.8.49/Tone.js"></script>
    
      <style>
        body{font-family:sans-serif;margin:2rem;max-width:900px}
        .host-only{border:1px solid #aaa;padding:1rem;margin-bottom:1rem}
        button{margin:0.25rem}
        code{background:#eee;padding:2px 4px;border-radius:3px}
      </style>
    </head>
    
    <body>
      <h1>🎹 MIDI Sync Playground</h1>
    
      <!-- Host panel -->
      <div id="hostPanel" class="host-only" style="display:none">
        <h2>Host controls</h2>
        <input type="file" id="midiFile" accept=".mid,.midi">
        <button id="uploadBtn">Upload MIDI</button>
    
        <h3>Assign Tracks</h3>
        <div id="clientList">No clients yet…</div>
    
        <h3>Transport</h3>
        <button id="playBtn">▶️ Play</button>
        <button id="pauseBtn">⏸️ Pause</button>
        <button id="stopBtn">⏹️ Stop</button>
      </div>
    
      <!-- Everybody sees this -->
      <h2 id="status">Waiting for MIDI…</h2>
      <p id="trackInfo"></p>
    
    <script>
    /* ────────────────────────────────
       Runtime flags
    ──────────────────────────────────*/
    const urlParams = new URLSearchParams(window.location.search);
    const isHost    = urlParams.get("host") === "1";
    document.getElementById("hostPanel").style.display = isHost ? "block" : "none";
    
    /* ────────────────────────────────
       Socket & Tone setup
    ──────────────────────────────────*/
    const socket        = io();
    let toneLoaded      = false;
    let midiData        = null;
    let parts           = [];
    let assignedTracks  = [];
    
    /* Helper: Base64 → ArrayBuffer */
    function b64ToArrayBuffer(b64) {
      const binary = atob(b64);
      const len    = binary.length;
      const bytes  = new Uint8Array(len);
      for (let i=0;i<len;i++) bytes[i] = binary.charCodeAt(i);
      return bytes.buffer;
    }
    
    /* Build Tone.Part per track */
    function buildParts() {
      parts.forEach(p => p.dispose());       // clean up
      parts = [];
    
      midiData.tracks.forEach((track, idx) => {
        // Cheap & cheerful synth for demo – swap with WebMIDI out if you like
        const synth = new Tone.PolySynth(Tone.Synth).toDestination();
    
        const part = new Tone.Part((time, note) => {
          if (!assignedTracks.includes(idx)) return;  // mute unassigned tracks
          synth.triggerAttackRelease(note.name, note.duration, time, note.velocity);
        }, track.notes).start(0);
    
        parts.push(part);
      });
    }
    
    socket.on("midi", ({ name, data }) => {
      midiData   = new Tone.Midi(b64ToArrayBuffer(data));
      document.getElementById("status").textContent = "Loaded: " + (name||"untitled");
      assignedTracks = [];                      // reset
      buildParts();
    });
    
    /* Track assignment from host */
    socket.on("assigned", tracks => {
      assignedTracks = tracks;
      document.getElementById("trackInfo").textContent =
        "My tracks: " + (tracks.length ? tracks.join(", ") : "none");
    });
    
    /* Transport commands  (server relays them) */
    socket.on("play",  targetMillis => {
      if (!midiData) return;
      // Start everyone at exactly the same AudioContext time
      const delaySeconds = (targetMillis - Date.now())/1000;
      Tone.Transport.start("+" + Math.max(delaySeconds, 0));
    });
    socket.on("pause", () => Tone.Transport.pause());
    socket.on("stop",  () => Tone.Transport.stop());
    
    /* ────────────────────────────────
       Host-only logic
    ──────────────────────────────────*/
    if (isHost) {
      const clientsDiv = document.getElementById("clientList");
    
      /* upload MIDI */
      uploadBtn.onclick = () => {
        const file = midiFile.files[0];
        if (!file) return alert("Pick a .mid first!");
        const fd   = new FormData();
        fd.append("midi", file);
        fetch("/upload", { method: "POST", body: fd });
      };
    
      /* Periodically ask who’s connected */
      function refreshClients() { socket.emit("requestClientList"); }
      setInterval(refreshClients, 2000);
    
      socket.on("clientList", clients => {
        clientsDiv.innerHTML = "";
        clients.forEach(c => {
          const el = document.createElement("div");
          el.innerHTML = `
            <strong>${c.id}</strong>
            <input id="t_${c.id}" placeholder="e.g. 0,2,5" size="10">
            <button onclick="assign('${c.id}')">Send</button>
          `;
          clientsDiv.appendChild(el);
        });
      });
    
      /* Send track assignment to server */
      window.assign = id => {
        const input  = document.getElementById("t_"+id).value.trim();
        const tracks = input.split(",")
                            .map(s => parseInt(s,10))
                            .filter(n => !Number.isNaN(n));
        socket.emit("assignTracks", { targetId: id, tracks });
      }
    
      /* transport buttons */
      playBtn.onclick  = () => socket.emit("play",  Date.now()+1000); // +1s for latency
      pauseBtn.onclick = () => socket.emit("pause");
      stopBtn.onclick  = () => socket.emit("stop");
    }
    </script>
    </body>
    </html>
    

    🚀 5. Run it

    npm start
    

    Open http://localhost:3000/?host=1 on one device (host)
    Open http://:3000/ on any other device(s) (clients)

    1. Host uploads a .mid.
    2. Host sees every connected socket ID, types which track numbers each device should play (comma-separated) and clicks “Send”.
    3. Press Play – all devices should start in unison (± the network jitter).

    🛠️ Extending & hardening

    • Replace the demo synth with WebMIDI output so each device can forward its track to an external synth/DAW.
    • Persist uploads on disk (diskStorage in Multer) if you need history.
    • For tighter sync: measure ping/round-trip time per client and compensate, or switch to WebRTC data channels.
    • Add per-track volume + mute/solo UI.
    • Secure “host” rights with a pass-phrase or auth token.

    Have fun & happy jamming! 🎶

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