SHARE
TWEET

bytebeat.js (v2)

a guest Apr 16th, 2017 89 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // bytebeat.js (v2)
  2. // by funute - public domain
  3.  
  4. /**
  5.  * Now in ES6!
  6.  * Run using node like this:
  7.  *
  8.  * $ node bytebeat.js < input.js | pacat --format=u8 --channels=1 --rate=8000 (PulseAudio)
  9.  * $ node bytebeat.js < input.js | aplay --rate=8000 (ALSA)
  10.  *
  11.  * You can also "render" to a raw file like this:
  12.  *
  13.  * $ node bytebeat.js < input.js > output.raw
  14.  *
  15.  * Or you can just run it, enter stuff in, and listen like this:
  16.  *
  17.  * $ node bytebeat.js | aplay --rate=8000
  18.  * ((t >> 10) & 42) * t
  19.  * ^D
  20.  */
  21.  
  22. if (process.stdout.isTTY) {
  23.     console.log('stdout is tty, exiting');
  24.     process.exit(1);
  25. }
  26.  
  27. const CHUNK = 1024;
  28. const LIM = Number(process.argv[2]) || -1;
  29. let expr = 'return ';
  30.  
  31. process.stdin.on('data', (buf) => {
  32.     expr += buf;
  33. });
  34.  
  35. process.stdin.on('end', () => {
  36.     // hacky "globalization" of Math (!)
  37.     const mathNames = Object.getOwnPropertyNames(Math);
  38.     const mathProps = mathNames.map((prop) => {
  39.         return Math[prop];
  40.     });
  41.  
  42.     const mfun = new Function(...mathNames, 't', expr);
  43.     const fun = mfun.bind(null, ...mathProps)
  44.  
  45.     let t = 0;
  46.  
  47.     function write() {
  48.         let ok = true;
  49.         while (ok && (t < LIM || LIM == -1)) {
  50.             const data = new Buffer(CHUNK);
  51.             for (let k = 0; k < CHUNK; ++k) {
  52.                 data[k] = fun(t+k);
  53.             }
  54.             ok = process.stdout.write(data);
  55.             t += CHUNK;
  56.         }
  57.         if (t < LIM || LIM == -1) {
  58.             process.stdout.once('drain', write);
  59.         }
  60.     };
  61.     write();
  62. });
  63.  
  64. process.stdout.on('error', (err) => {
  65.     if (err.code === 'EPIPE') {
  66.         process.exit(0);
  67.     } else {
  68.         throw(err);
  69.     }
  70. });
RAW Paste Data
Want to get better at JavaScript?
Learn to code JavaScript in 2017
Top