Browse Source

Merge pull request #6233 from matthewtung/audio-controls

Controls for THREE.Audio
Mr.doob 10 years ago
parent
commit
9cdd892cbb
1 changed files with 55 additions and 3 deletions
  1. 55 3
      src/extras/audio/Audio.js

+ 55 - 3
src/extras/audio/Audio.js

@@ -2,14 +2,17 @@
  * @author mrdoob / http://mrdoob.com/
  * @author mrdoob / http://mrdoob.com/
  */
  */
 
 
-THREE.Audio = function ( listener ) {
+THREE.Audio = function ( listener, autoplay ) {
 
 
 	THREE.Object3D.call( this );
 	THREE.Object3D.call( this );
 
 
 	this.type = 'Audio';
 	this.type = 'Audio';
 
 
+	this.autoplay = autoplay || false;
+
 	this.context = listener.context;
 	this.context = listener.context;
 	this.source = this.context.createBufferSource();
 	this.source = this.context.createBufferSource();
+	this.source.onended = this.onEnded.bind(this);
 
 
 	this.gain = this.context.createGain();
 	this.gain = this.context.createGain();
 	this.gain.connect( this.context.destination );
 	this.gain.connect( this.context.destination );
@@ -17,6 +20,9 @@ THREE.Audio = function ( listener ) {
 	this.panner = this.context.createPanner();
 	this.panner = this.context.createPanner();
 	this.panner.connect( this.gain );
 	this.panner.connect( this.gain );
 
 
+	this.startTime = 0;
+	this.isPlaying = false;
+
 };
 };
 
 
 THREE.Audio.prototype = Object.create( THREE.Object3D.prototype );
 THREE.Audio.prototype = Object.create( THREE.Object3D.prototype );
@@ -34,8 +40,8 @@ THREE.Audio.prototype.load = function ( file ) {
 		scope.context.decodeAudioData( this.response, function ( buffer ) {
 		scope.context.decodeAudioData( this.response, function ( buffer ) {
 
 
 			scope.source.buffer = buffer;
 			scope.source.buffer = buffer;
-			scope.source.connect( scope.panner );
-			scope.source.start( 0 );
+
+			if( scope.autoplay ) scope.play();
 
 
 		} );
 		} );
 
 
@@ -46,6 +52,52 @@ THREE.Audio.prototype.load = function ( file ) {
 
 
 };
 };
 
 
+THREE.Audio.prototype.play = function () {
+
+	if ( ! this.isPlaying ) {
+
+		var source = this.context.createBufferSource();
+
+		source.buffer = this.source.buffer;
+		source.loop = this.source.loop;
+		source.onended = this.source.onended;
+		source.connect( this.panner );
+		source.start( 0, this.startTime );
+
+		this.isPlaying = true;
+
+		this.source = source;
+
+	}
+
+	else {
+
+		console.warn("Audio is already playing.")
+
+	}
+
+};
+
+THREE.Audio.prototype.pause = function () {
+
+	this.source.stop();
+	this.startTime = this.context.currentTime;
+
+};
+
+THREE.Audio.prototype.stop = function () {
+
+	this.source.stop();
+	this.startTime = 0;
+
+};
+
+THREE.Audio.prototype.onEnded = function() {
+
+	this.isPlaying = false;
+
+};
+
 THREE.Audio.prototype.setLoop = function ( value ) {
 THREE.Audio.prototype.setLoop = function ( value ) {
 
 
 	this.source.loop = value;
 	this.source.loop = value;