Permalink
Browse files

read events in a loop for ondatas

  • Loading branch information...
1 parent 264a2ea commit cc3b4524749dac08f7abd2f92a2fc10cbdad82c1 @substack committed Jun 4, 2012
Showing with 68 additions and 6 deletions.
  1. +64 −2 sox.cc
  2. +4 −4 test.js
View
66 sox.cc
@@ -11,7 +11,11 @@ using namespace node;
struct node_sox_request {
sox_format_t *in, *out;
sox_effects_chain_t *chain;
+ Persistent<Function> ondata;
Persistent<Function> onend;
+ bool out_open;
+ char *buffer;
+ size_t buffer_size;
};
class Player : public ObjectWrap {
@@ -75,7 +79,29 @@ class Player : public ObjectWrap {
assert(in);
req->in = in;
- out = sox_open_write("default", &in->signal, NULL, "alsa", NULL, NULL);
+ Local<Object> ondata_ = Local<Object>::Cast(
+ opts->Get(String::NewSymbol("ondata"))
+ );
+
+ if (!ondata_->IsUndefined()) {
+ req->ondata = Persistent<Function>::New(
+ Local<Function>::Cast(ondata_)
+ );
+ req->buffer = (char *) malloc(4096);
+ req->buffer_size = 4096;
+
+ out = sox_open_memstream_write(
+ &req->buffer, &req->buffer_size, &in->signal,
+ NULL, "sox", NULL
+ );
+ req->out_open = true;
+ }
+ else {
+ out = sox_open_write(
+ "default", &in->signal, NULL, "alsa", NULL, NULL
+ );
+ }
+
assert(out);
req->out = out;
@@ -115,13 +141,49 @@ class Player : public ObjectWrap {
assert(sox_add_effect(chain, e, &in->signal, &out->signal) == SOX_SUCCESS);
free(e);
- eio_custom(eio_flow, EIO_PRI_DEFAULT, eio_flow_after, req);
+ if (ondata_->IsUndefined()) {
+ eio_custom(eio_flow, EIO_PRI_DEFAULT, eio_flow_after, req);
+ }
+ else {
+ eio_custom(eio_rw, EIO_PRI_DEFAULT, eio_rw_after, req);
+ }
+
ev_ref(EV_DEFAULT_UC);
player->Ref();
return scope.Close(arguments.This());
}
+ static void eio_rw (eio_req *ereq) {
+ sox_sample_t samples[4096];
+ node_sox_request *req = (node_sox_request *) ereq->data;
+
+ size_t number_read = sox_read(req->in, samples, (size_t) 4096);
+ req->out_open = number_read > 0;
+printf("%d bytes read\r\n", (int) number_read);
+fflush(stdout);
+ assert(sox_write(req->out, samples, number_read) == number_read);
+ }
+
+ static int eio_rw_after (eio_req *ereq) {
+ node_sox_request *req = (node_sox_request *) ereq->data;
+
+ HandleScope scope;
+ Local<Value> argv[0];
+
+ if (!req->out_open) {
+ req->onend->Call(Context::GetCurrent()->Global(), 1, argv);
+
+ req->onend.Dispose();
+ free(req);
+ }
+ else {
+ eio_custom(eio_rw, EIO_PRI_DEFAULT, eio_rw_after, req);
+ }
+
+ return 0;
+ }
+
static void eio_flow (eio_req *ereq) {
node_sox_request *req = (node_sox_request *) ereq->data;
View
8 test.js
@@ -1,10 +1,10 @@
var Player = require('./build/Release/sox').Player;
+var fs = require('fs');
var player = new Player;
player.play({
+ ondata : function (buf) {
+ console.dir(buf);
+ },
onend : function () { console.log('end') },
});
-
-setTimeout(function () {
- player.stop();
-}, 2000);

0 comments on commit cc3b452

Please sign in to comment.