title: How to Stream Live Audio With Low Latency
body: <p>I have programmed a server that creates an audio stream from my MacBook's audio input, using <a href="https://www.npmjs.com/package/express" rel="noreferrer">express</a>, <a href="https://www.npmjs.com/package/osx-audio" rel="noreferrer">osx-audio</a> and <a href="https://www.npmjs.com/package/lame" rel="noreferrer">lame</a>:</p>
  
  <pre><code>const http = require("http");
  const express = require("express");
  const audio = require("osx-audio");
  const lame = require("lame");
  const audioInput = new audio.Input();
  
  const encoder = new lame.Encoder({
    channels: 2,
    bitDepth: 16,
    sampleRate: 44100,
    bitRate: 128,
    outSampleRate: 22050,
    mode: lame.STEREO
  });
  
  audioInput.pipe(encoder);
  
  const app = express();
  const server = http.Server(app);
  
  app.get("/stream.mp3", (req, res) =&gt; {
    res.set({
      "Content-Type": "audio/mpeg",
      "Transfer-Encoding": "chunked"
    });
    encoder.pipe(res);
  });
  
  server.listen(3000);
  </code></pre>
  
  <p>On the client side, the sound from this audio stream is included as an <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio" rel="noreferrer">&lt;audio&gt;</a> element like so:</p>
  
  <pre><code>&lt;audio controls autoplay preload="none"&gt;
    &lt;source src="./stream.mp3" type="audio/mpeg" /&gt;
    &lt;p&gt;Oops – your browser doesn't support HTML5 audio!&lt;/p&gt;
  &lt;/audio&gt;
  </code></pre>
  
  <p>This works – I can hear the sound from the input source I've selected on my laptop from any browser that is connected to the server when I click the “play” button on the audio element.</p>
  
  <p><strong>However</strong> the audio played by the browser lags several seconds behind the original signal. It seems although I'm using <code>preload="none"</code>, the browser buffers quite a lot of the audio stream before it starts playing it.</p>
  
  <p>Is there something obvious missing here? Is there a better way to achieve real-time audio with only a few milliseconds latency instead of several seconds?</p>
  
  <p>If you're interested, my project's complete source code is <a href="https://github.com/pahund/zapperment" rel="noreferrer">here on GitHub</a>.</p>