Audio.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. THREE.Audio = function ( listener, autoplay ) {
  5. THREE.Object3D.call( this );
  6. this.type = 'Audio';
  7. this.autoplay = autoplay || false;
  8. this.context = listener.context;
  9. this.source = this.context.createBufferSource();
  10. this.gain = this.context.createGain();
  11. this.gain.connect( this.context.destination );
  12. this.panner = this.context.createPanner();
  13. this.panner.connect( this.gain );
  14. this.startTime = 0;
  15. this.isPlaying = false;
  16. };
  17. THREE.Audio.prototype = Object.create( THREE.Object3D.prototype );
  18. THREE.Audio.prototype.constructor = THREE.Audio;
  19. THREE.Audio.prototype.load = function ( file ) {
  20. var scope = this;
  21. var request = new XMLHttpRequest();
  22. request.open( 'GET', file, true );
  23. request.responseType = 'arraybuffer';
  24. request.onload = function ( e ) {
  25. scope.context.decodeAudioData( this.response, function ( buffer ) {
  26. scope.source.buffer = buffer;
  27. if( scope.autoplay ) scope.play();
  28. } );
  29. };
  30. request.send();
  31. return this;
  32. };
  33. THREE.Audio.prototype.play = function () {
  34. if ( ! this.isPlaying ) {
  35. var source = this.context.createBufferSource();
  36. source.buffer = this.source.buffer;
  37. source.loop = this.source.loop;
  38. source.connect( this.panner );
  39. source.start( 0, this.startTime );
  40. this.isPlaying = true;
  41. this.source = source;
  42. }
  43. else {
  44. console.warn("Audio is already playing.")
  45. }
  46. };
  47. THREE.Audio.prototype.pause = function () {
  48. this.source.stop();
  49. this.startTime = this.context.currentTime;
  50. this.isPlaying = false;
  51. };
  52. THREE.Audio.prototype.stop = function () {
  53. this.source.stop();
  54. this.startTime = 0;
  55. this.isPlaying = false;
  56. };
  57. THREE.Audio.prototype.setLoop = function ( value ) {
  58. this.source.loop = value;
  59. };
  60. THREE.Audio.prototype.setRefDistance = function ( value ) {
  61. this.panner.refDistance = value;
  62. };
  63. THREE.Audio.prototype.setRolloffFactor = function ( value ) {
  64. this.panner.rolloffFactor = value;
  65. };
  66. THREE.Audio.prototype.setVolume = function ( value ) {
  67. this.gain.gain.value = value;
  68. };
  69. THREE.Audio.prototype.updateMatrixWorld = ( function () {
  70. var position = new THREE.Vector3();
  71. return function ( force ) {
  72. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  73. position.setFromMatrixPosition( this.matrixWorld );
  74. this.panner.setPosition( position.x, position.y, position.z );
  75. };
  76. } )();