The Audio.getVolume()
method is a part of the three.js
library that allows you to retrieve the current volume of an audio source that is being played.
audioSource.getVolume();
There are no parameters for this method.
The getVolume()
method returns a decimal value between 0
and 1
that represents the current volume of the audio source.
const audioLoader = new THREE.AudioLoader();
const listener = new THREE.AudioListener();
const camera = new THREE.PerspectiveCamera( 90, window.innerWidth / window.innerHeight, 0.1, 1000 );
const audioSource = new THREE.PositionalAudio( listener );
audioLoader.load( 'music.mp3', function( buffer ) {
audioSource.setBuffer( buffer );
audioSource.setRefDistance( 20 );
audioSource.play();
});
const volBtn = document.getElementById('volume-btn');
volBtn.addEventListener('click', () => {
const currentVolume = audioSource.getVolume();
audioSource.setVolume( currentVolume === 0 ? 1 : 0 );
});
In the above example, we have created a PositionalAudio
object from an audio file and played it with a volume button that toggles the audio off and on. We achieved this functionality using the getVolume()
method to retrieve the current audio volume and setVolume()
method to alter the audio volume.
Note that the volume of a PositionalAudio
object can be set individually for each audio source, and it can also be spatially controlled by setting the refDistance
, maxDistance
and rolloffFactor
properties of the audio source.
The Audio.getVolume()
method is a vital tool for controlling the volume of an audio source in a three.js
project. It can be used to retrieve and manipulate the current volume of an audio source, allowing for complex audio effects that can be spatially controlled in your 3D environment.