sound.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. function myb64(bytes)
  2. {
  3. var binary = '';
  4. var len = bytes.byteLength;
  5. for (var i = 0; i < len; i++) {
  6. binary += String.fromCharCode( bytes[ i ] )
  7. }
  8. return window.btoa( binary );
  9. }
  10. function loopEnded()
  11. {
  12. this.currentTime = 0;
  13. this.play();
  14. }
  15. var sound = {
  16. j2c: null,
  17. init: function() {
  18. this.j2c = js2cppX.alloc();
  19. },
  20. create: function(){
  21. },
  22. play: function(path, volume, loop){
  23. try{
  24. var data = FS.readFile(path, {encoding:'binary'});
  25. }
  26. catch(er)
  27. {
  28. return 0;
  29. }
  30. var b64data = myb64(data);
  31. var src = "data:audio/ogg;base64," + b64data;
  32. var a = new Audio();
  33. a.src = src;
  34. a.play();
  35. a.volume = volume;
  36. if (loop)
  37. {
  38. a.addEventListener('ended', loopEnded, false);
  39. }
  40. var obj = {instance:a, looped:loop};
  41. return this.j2c.create(obj);
  42. },
  43. get: function(id){
  44. return this.j2c.get(id);
  45. },
  46. setLoop: function(id, loop){
  47. var s = sound.get(id);
  48. if (!s)
  49. return;
  50. if (s.looped == loop)
  51. return;
  52. s.looped = loop;
  53. if (loop)
  54. s.instance.addEventListener('ended', loopEnded, false);
  55. else
  56. s.instance.removeEventListener('ended', loopEnded);
  57. },
  58. setVolume: function(id, volume){
  59. var s = sound.get(id);
  60. if (!s)
  61. return;
  62. s.instance.volume = volume;
  63. },
  64. pause: function(id){
  65. var s = sound.get(id);
  66. if (!s)
  67. return;
  68. s.instance.pause();
  69. },
  70. resume: function(id){
  71. var s = sound.get(id);
  72. if (!s)
  73. return;
  74. s.instance.play();
  75. },
  76. stop: function(id){
  77. var s = sound.get(id);
  78. if (!s)
  79. return;
  80. if (s.looped)
  81. s.instance.removeEventListener('ended', loopEnded);
  82. s.instance.pause();
  83. },
  84. update: function(id){
  85. var s = sound.get(id);
  86. if (!s)
  87. return true;
  88. if (s.looped)
  89. return false;
  90. var ended = s.instance.ended;
  91. return ended;
  92. },
  93. free: function(id){
  94. this.j2c.free(id);
  95. },
  96. stats: function(){
  97. return this.j2c.get_size();
  98. },
  99. };