title: How to stream MP3 data via WebSockets with node.js and socket.io?
body: <p>I have problems streaming MP3 data via WebSocket with node.js and socket.io. Everything seems to work but decodeAudioData doesn't play fair with me.</p>
  
  <p>This is my toy server:</p>
  
  <pre><code>var app = require('http').createServer(handler)
    , io = require('socket.io').listen(app)
    , fs = require('fs')
  
  app.listen(8081);
  
  function handler (req, res) {
      res.writeHead(200, {
          'Content-Type': 'text/html',
      });
      res.end('Hello, world!');
  }
  
  io.configure('development', function() {
    io.set('log level', 1);
  
    io.set('transports', [ 'websocket' ]);
  });
  
  io.sockets.on('connection', function (socket) {
      console.log('connection established');
  
      var readStream = fs.createReadStream("test.mp3", 
                                           {'flags': 'r',
                                            'encoding': 'binary', 
                                            'mode': 0666, 
                                            'bufferSize': 64 * 1024});
      readStream.on('data', function(data) {
          console.log(typeof data);
          console.log('sending chunk of data')
          socket.send(data);
      });
  
      socket.on('disconnect', function () {
          console.log('connection droped');
      });
  });
  
  console.log('Server running at http://127.0.0.1:8081/');
  </code></pre>
  
  <p>The client receives the data as type string but I want to feed the data to decodeAudioData and it seems it doesn't like strings. The call to decodeAudioData results in the following error message:</p>
  
  <pre><code>Uncaught Error: SYNTAX_ERR: DOM Exception 12
  </code></pre>
  
  <p>I think decodeAudioData needs the data stored in an ArrayBuffer. Is there a way to convert the data?</p>
  
  <p>This is the client code:</p>
  
  <pre><code>&lt;script src="http://127.0.0.1:8081/socket.io/socket.io.js"&gt;&lt;/script&gt;
  &lt;script&gt;
      var audioBuffer = null;
      var context = null;
      window.addEventListener('load', init, false);
      function init() {
          try {
              context = new webkitAudioContext();
          } catch(e) {
              alert('Web Audio API is not supported in this browser');
          }
      }
  
      function decodeHandler(buffer) {
          console.log(data);
      }
  
      var socket = io.connect('http://127.0.0.1:8081');
      socket.on('message', function (data) {
              // HERE IS THE PROBLEM
          context.decodeAudioData(data, decodeHandler, function(e) { console.log(e); });
      });
  &lt;/script&gt;
  </code></pre>