vincentsaluzzo / node-microphone

microphone is a simple module that use `arecord` ALSA tools method to capture sound from a USB Microphone
56 stars 48 forks source link

How to stream recorded Audio from Microphone to client #7

Open sebastianzillessen opened 9 years ago

sebastianzillessen commented 9 years ago

Hi.

I would like to stream the live input from the microphone to a connected client of the node server using your plugin. How could I accomplish this?

What I tried so far:

I managed to stream a wavfile directly to the client by using the repro https://github.com/villanuevawill/webaudio-sample. But when I try to replace the streams, it fails to work with the microphone.

I'm really a beginner concerning node and microphone, any help is appreciated! Thanks!

My code is below:

Server:

var express = require('express');
var fs = require('fs');
var ejs = require('ejs');
var path = require('path');

var app = express();
app.use(express.static(__dirname + '/public'));
var mic = require('microphone');
// test file for direct streaming
var filepath = path.join(__dirname, 'test.wav');

app.get('/music', function(req, res){
    res.set({'Content-Type': 'audio/wav'});
    // the following 2 lines enable me to stream a test file (directly via WAV) to my client.
    // If you use them instead of the microphone, then all works.
    //var readStream = fs.createReadStream(filepath);
    //readStream.pipe(res);
   mic.startCapture({}); 
   mic.audioStream.on('data', function(data) {
        //process.stdout.write(data);
    process.stdout.write(".");
        res.write(data);
    });
app.get('/music', function(req, res){
    res.set({'Content-Type': 'audio/wav'});
    mic.startCapture({});
    mic.audioStream.on('data', function(data) {
        //process.stdout.write(data);
    process.stdout.write(".");
        res.write(data);
    });
});
app.listen(8000);
console.log("Listening on Port 8000");

Client:


window.AudioContext = window.AudioContext || window.webkitAudioContext;
context = new AudioContext();

function process(Data) {
  source = context.createBufferSource(); // Create Sound Source
console.log("Processing: "+JSON.stringify(Data));
  context.decodeAudioData(Data, function(buffer){
    source.buffer = buffer;
    source.connect(context.destination); 
    source.start(context.currentTime);
  });
};

function loadSound() {
  var request = new XMLHttpRequest();
  request.open("GET", "/music", true); 
  request.responseType = "arraybuffer"; 

  request.onload = function() {
      // this is never called when I use the microphone wav stream.
      // when I use the WAV test file as input it works nice.
      var Data = request.response;
      process(Data);
  };

  request.send();
};

loadSound()
tilman commented 7 years ago

Have you found a working solution?