Skip to content

Commit 4dd5355

Browse files
committed
feat: audio fading
1 parent a7b42b1 commit 4dd5355

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

src/audio/Audio.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -736,6 +736,35 @@ class Audio extends Object3D {
736736

737737
}
738738

739+
/**
740+
* Fades the audio in by increasing volume gradually from `volumeNow` to `volumeThen`,
741+
* within the passed time interval.
742+
*
743+
* @param {number} duration - The duration of the fade.
744+
* @param {number} [volumeNow=0] - The volume at the start of the fade.
745+
* @param {number} [volumeThen=1] - The volume at the end of the fade.
746+
* @return {Audio} A reference to this instance.
747+
*/
748+
fadeIn( duration, volumeNow = 0, volumeThen = 1 ) {
749+
750+
return this._scheduleFading( duration, volumeNow, volumeThen );
751+
752+
}
753+
754+
/**
755+
* Fades the audio out by decreasing volume gradually from the current volume to `volumeThen`,
756+
* within the passed time interval.
757+
*
758+
* @param {number} duration - The duration of the fade.
759+
* @param {number} [volumeThen=0] - The volume at the end of the fade.
760+
* @return {Audio} A reference to this instance.
761+
*/
762+
fadeOut( duration, volumeThen = 0 ) {
763+
764+
return this._scheduleFading( duration, this.getVolume(), volumeThen );
765+
766+
}
767+
739768
copy( source, recursive ) {
740769

741770
super.copy( source, recursive );
@@ -773,6 +802,25 @@ class Audio extends Object3D {
773802

774803
}
775804

805+
_scheduleFading( duration, volumeNow, volumeThen ) {
806+
807+
const currentTime = this.listener.context.currentTime;
808+
/**
809+
* 95% of the duration.
810+
*
811+
* Reference: {@link https://developer.mozilla.org/en-US/docs/Web/API/AudioParam/setTargetAtTime#choosing_a_good_timeconstant}
812+
*/
813+
const timeConstant = duration / 3;
814+
815+
this.gain.gain
816+
.cancelScheduledValues( currentTime )
817+
.setValueAtTime( volumeNow, currentTime )
818+
.setTargetAtTime( volumeThen, currentTime, timeConstant );
819+
820+
return this;
821+
822+
}
823+
776824
}
777825

778826
export { Audio };

0 commit comments

Comments
 (0)