Audio pause not working properly

Hello everyone,

It’s my first time posting an issue and I am new to Github so please be tolerant.
I am using the latest version of three.js.
I noticed that pausing an audio source (Positional or not) wasn’t working properly. When playing after pause, there was a gap between the “offset” of the audio when pausing and that of the audio when playing again afterwards. Indeed, as the code is using AudioBufferSourceNodes that can only be played once, it is necessary to create a new source node when playing, but it has to be set to the right offset.
After looking at the code, I suggest the following fix :
(modifications appear in the Audio constructor (this.offset), and the methods play, pause and stop)


function Audio( listener ) {

		Object3D.call( this );

		this.type = 'Audio';

		this.context = listener.context;

		this.gain = this.context.createGain();
		this.gain.connect( listener.getInput() );

		this.autoplay = false;

		this.buffer = null;
		this.loop = false;
		this.startTime = this.context.currentTime;
		this.playbackRate = 1;
		this.isPlaying = false;
		this.hasPlaybackControl = true;
		this.sourceType = 'empty';
		this.offset = 0;
		this.filters = [];
		this.offset = 0;

	}
		play: function () {

			if ( this.isPlaying === true ) {

				console.warn( 'THREE.Audio: Audio is already playing.' );
				return;

			}

			if ( this.hasPlaybackControl === false ) {

				console.warn( 'THREE.Audio: this Audio has no playback control.' );
				return;

			}

			var source = this.context.createBufferSource();

			source.buffer = this.buffer;
			source.loop = this.loop;
			source.onended = this.onEnded.bind( this );
			this.startTime = this.context.currentTime;
			source.playbackRate.setValueAtTime( this.playbackRate, this.startTime );
			source.start( this.startTime, this.offset );

			this.isPlaying = true;

			this.source = source;

			return this.connect();

		},

		pause: function () {

			if ( this.hasPlaybackControl === false ) {

				console.warn( 'THREE.Audio: this Audio has no playback control.' );
				return;

			}
			if( this.isPlaying ) {
				this.source.stop();
				this.offset += this.context.currentTime - this.startTime;
				this.isPlaying = false;
			}

			return this;

		},

		stop: function () {

			if ( this.hasPlaybackControl === false ) {

				console.warn( 'THREE.Audio: this Audio has no playback control.' );
				return;

			}

			this.source.stop();
			this.offset = 0;
			this.isPlaying = false;

			return this;

		}

Author: Fantashit

1 thought on “Audio pause not working properly

  1. Thank you for your answers,
    I will try to do the pull request on monday. I’ll tell you if I need help, thanks for proposing.
    Pablo

Comments are closed.