ByteWarrior in-browser bytebeat player library


SUBMITTED BY: Guest

DATE: March 28, 2013, 8:17 a.m.

FORMAT: JavaScript

SIZE: 1.8 kB

HITS: 1397

  1. /*
  2. * ByteWarrior library for playing and exporting bytebeat tunes in your browser
  3. * by Multiversum
  4. * Usage: new ByteWarrior(pattern_string, sampleRate, duration), then call play() and pause() methods
  5. * Pattern string is mandatory, you can omit all other parameters, then their defaults will be:
  6. * sample rate - 8000 Hz, duration - 16 sec
  7. * pattern_string accepts a JS expression from single 't' parameter
  8. * The following functions can be specified without Math: sin, cos, tan, floor, ceil
  9. * Example:
  10. * var bb = new ByteWarrior("((t<<1)^((t<<18)+(t>>7)&t>>12))|t>>(4-(1^7&(t>>19)))|t>>7"); bb.play()
  11. * Export to WAV is done with accessing wavedata parameter:
  12. * var bb = new ByteWarrior(pattern,8000,120);
  13. * var wavDataURI = bb.wavedata;
  14. * This library is public domain. Have fun!
  15. */
  16. ByteWarrior = function(pstring, sampleRate, duration) {
  17. this.rate = sampleRate||8000;
  18. this.duration = duration||16;
  19. this.pattern = eval("(function(t){return "+pstring.replace(/sin|cos|tan|floor|ceil/g,function(s){return "Math."+s})+"})");
  20. this.audio = new Audio();
  21. this.toWav = function(){
  22. var nsamples = this.duration*this.rate,
  23. i2b=function(v){return [0xFF&v,0xFF&(v>>8),0xFF&(v>>16),0xFF&(v>>24)]},
  24. wave=[].concat([82,73,70,70],i2b(44+nsamples),
  25. [87,65,86,69,102,109,116,32,16,0,0,0,1,0,1,0],i2b(this.rate),i2b(this.rate),
  26. [1,0,8,0,100,97,116,97],i2b(nsamples));
  27. for(var t=0;t<nsamples;t++)wave.push(0xFF&this.pattern(t));
  28. return "data:audio/x-wav;base64,"+btoa(wave.reduce(function(a,b){return a+String.fromCharCode(b)},''))
  29. };
  30. this.audio.src = this.wavedata = this.toWav();
  31. this.play = function(){this.audio.play()};
  32. this.pause = function(){this.audio.pause()}
  33. }

comments powered by Disqus