Maurício Giordano
Maurício Giordano

Reputation: 3276

BinaryJs + Audio API schedule array buffers

I have a node.js server streaming some ArrayBuffers:

var BinaryServer = require('binaryjs').BinaryServer;
var fs = require('fs');

var server = BinaryServer({port: 2000});

server.on('connection', function(client){
  var file = fs.createReadStream(__dirname + '/music/02 Enter Sandman.mp3');
  client.send(file);
});

On the client, I'm listening to those chunks and trying to play them one after another:

var client = new BinaryClient('ws://localhost:2000');

var context = new AudioContext();

var source = context.createBufferSource();
source.connect(context.destination);

var audioStart = 0;
var audioStop = 0;

client.on('stream', function(stream, meta)
{
    stream.on('data', function(data)
    {
        var audio = new Float32Array(data);
        var audioBuffer = context.createBuffer(1, audio.length, 44100);

        audioBuffer.getChannelData(0).set(audio);

        audioBuffer = context.createBuffer(data, true);

        audioStop += audioBuffer.duration;
        
        source = context.createBufferSource();
        source.connect(context.destination);
        source.buffer = audioBuffer;
        source.start(audioStart);
        //source.stop(audioStop);

        console.log(audioStart + " - " + audioStop);

        audioStart += audioBuffer.duration;
    });
});

I'm constantly getting this error:

Uncaught InvalidStateError: Failed to execute 'start' on 'AudioBufferSourceNode': cannot call start more than once.

Only the first chunk plays

Could someone explain me how this supposed to work?

Upvotes: 0

Views: 683

Answers (1)

Le poney vaillant
Le poney vaillant

Reputation: 11

The problem come with Web Audio API, you can't load two or more sources in the same channel.

You can disconnect source with: source.disconnect(); and reconnect him with: source.connect(context.destination);

More information here: https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API

Upvotes: 1

Related Questions