ThreeJS Audio

It is used to create a non-positional (global ) audio object.

Code Example:

// create an AudioListener and add it to the camera
const listener = new THREE.AudioListener();
camera.add( listener );


// create a global audio source
const sound = new THREE.Audio( listener );


// load a sound and set it as the Audio object's buffer
const audioLoader = new THREE.AudioLoader();
audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
	sound.setBuffer( buffer );
	sound.setLoop( true );
	sound.setVolume( 0.5 );
	sound.play();
});

Constructor

Audio( listener : AudioListener )

listener — (required) AudioListener instance.

Properties

.autoplay : Boolean

Whether to start playback automatically. Default is false.

.context : AudioContext

The AudioContext of the listener given in the constructor.

.detune : Number

Modify pitch, measured in cents. +/- 100 is a semitone. +/- 1200 is an octave. Default is 0.

.filters : Array

An array of AudioNodes is represented by this class. To generate more sophisticated sound effects, it can be used to apply a variety of low-order filters. In most cases, the array contains BiquadFilterNodes instances. Audio.setFilter or Audio.setFilters are used to set filters.

.gain : GainNode

A GainNode created using AudioContext.createGain().

.hasPlaybackControl : Boolean

Whether playback can be controlled using the play(), pause() etc. methods. Default is true.

.isPlaying : Boolean

Whether the audio is currently playing.

.listener : AudioListener

A reference to the listener object of this audio.

.playbackRate : Number

Speed of playback. Default is 1.

.offset : Number

An offset for when playback should start within the audio buffer. The offset parameter of AudioBufferSourceNode is the same. start(). The default value is 0.

.duration : Number

Overrides the audio's duration. The duration parameter of AudioBufferSourceNode.start is the same as the duration parameter of AudioBufferSourceNode.start (). The default is undefined, which means it will play the entire buffer.

.source : String

An AudioBufferSourceNode created using AudioContext.createBufferSource().

.sourceType : String

Type of the audio source. Default is string 'empty'.

.type : String

String denoting the type, set to 'Audio'.

Methods

.connect () :this

Connect to the Audio.source. This is used internally on initialisation and when setting / removing filters.

.disconnect () : this

Disconnect from the Audio.source. This is used internally when setting / removing filters.

.getFilter () : BiquadFilterNode

Returns the first element of the filters array.

.getFilters () : Array

Returns the filters array.

.getLoop () : Boolean

Return the value of source.loop (whether playback should loop).

.getOutput () : GainNode

Return the gainNode.

.getPlaybackRate () : Float

Return the value of playbackRate.

.getVolume ( value ) : Float

Return the current volume.

.play ( delay ) : this

If hasPlaybackControl is true, starts playback.

.pause () : this

If hasPlaybackControl is true, pauses playback.

.onEnded () : undefined

Called automatically when playback finished.

.setBuffer ( audioBuffer ) : this

Setup the source to the audioBuffer, and sets sourceType to 'buffer'.

If autoplay, also starts playback.

.setFilter ( filter ) : this

Applies a single filter node to the audio.

.setFilters ( value : Array ) : this

value - arrays of filters.

Applies an array of filter nodes to the audio.

.setLoop ( value : Boolean ) : this

Set source.loop to value (whether playback should loop).

.setLoopStart ( value : Float ) : this

Set source.loopStart to value.

.setLoopEnd ( value : Float ) : this

Set source.loopEnd to value.

.setMediaElementSource ( mediaElement ) : this

Applies the given object of type HTMLMediaElement as the source of this audio.

Also sets hasPlaybackControl to false.

.setMediaStreamSource ( mediaStream ) : this

Applies the given object of type MediaStream as the source of this audio.

Also sets hasPlaybackControl to false.

.setNodeSource ( audioNode ) : this

Setup the source to the audioBuffer, and sets sourceType to 'audioNode'.

Also sets hasPlaybackControl to false.

.setPlaybackRate ( value : Float ) : this

If hasPlaybackControl is enabled, set the playbackRate to value.

.setVolume ( value : Float ) : this

Set the volume.

.stop () : this

If hasPlaybackControl is enabled, stops playback.

AudioAnalyser

Create an AudioAnalyser object that analyses audio data using an AnalyserNode.

Code Example:

// create an AudioListener and add it to the camera
const listener = new THREE.AudioListener();
camera.add( listener );


// create an Audio source
const sound = new THREE.Audio( listener );


// load a sound and set it as the Audio object's buffer
const audioLoader = new THREE.AudioLoader();
audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
	sound.setBuffer( buffer );
	sound.setLoop(true);
	sound.setVolume(0.5);
	sound.play();
});


// create an AudioAnalyser, passing in the sound and desired fftSize
const analyser = new THREE.AudioAnalyser( sound, 32 );


// get the average frequency of the sound
const data = analyser.getAverageFrequency();

Constructor

AudioAnalyser( audio, fftSize )

Create a new AudioAnalyser.

Properties

.analyser : AnalyserNode

An AnalyserNode used to analyze audio.

.fftSize : Integer

A non-zero power of two up to 2048, representing the size of the FFT (Fast Fourier Transform) to be used to determine the frequency domain. See this page for details.

.data : Uint8Array

A Uint8Array with size determined by analyser.frequencyBinCount used to hold analysis data.

Methods

.getFrequencyData () : Uint8Array

Uses the Web Audio's getByteFrequencyData method. See that page.

.getAverageFrequency () : Number

Get the average of the frequencies returned by the getFrequencyData method.

AudioContext

This section includes the techniques for creating an AudioContext.

The AudioListener and AudioLoader classes use this internally.

The Web Audio API is used here.

Methods

.getContext () : AudioContext

Return the value of the variable context in the outer scope, if defined, otherwise set it to a new AudioContext.

.setContext ( value : AudioContext ) : AudioContext

Set the variable context in the outer scope to value.

AudioListener

The AudioListener is a virtual listener for all of the scene's positional and non-positional audio effects.

A single instance of AudioListener is normally created in a three.js application. For audio entities like as Audio and PositionalAudio, it is a required function Object() { [native code] } parameter.

The listener object is almost always a camera's kid. As a result, the camera's 3D transformation replicates the listener's 3D transformation.

Code Example:

// create an AudioListener and add it to the camera
const listener = new THREE.AudioListener();
camera.add( listener );


// create a global audio source
const sound = new THREE.Audio( listener );


// load a sound and set it as the Audio object's buffer
const audioLoader = new THREE.AudioLoader();
audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
	sound.setBuffer( buffer );
	sound.setLoop(true);
	sound.setVolume(0.5);
	sound.play();
});

Constructor

AudioListener( )

Create a new AudioListener.

Properties

.context : AudioContext

The AudioContext of the listener given in the constructor.

.gain : GainNode

A GainNode created using AudioContext.createGain().

.filter : AudioNode

Default is null.

.timeDelta : Number

Time delta value for audio entities. Use in context of AudioParam.linearRampToValueAtTimeDefault(). Default is 0.

Methods

.getInput () : GainNode

Return the gainNode.

.removeFilter () : this

Set the filter property to null.

.getFilter () : AudioNode

Returns the value of the filter property.

.setFilter ( value : AudioNode ) : this

Set the filter property to value.

.getMasterVolume () : Float

Return the volume.

.setMasterVolume ( value : Number ) : this

Set the volume.

PositionalAudio

It is used to create a positional audio object.

Code Example:

// create an AudioListener and add it to the camera
const listener = new THREE.AudioListener();
camera.add( listener );


// create the PositionalAudio object (passing in the listener)
const sound = new THREE.PositionalAudio( listener );


// load a sound and set it as the PositionalAudio object's buffer
const audioLoader = new THREE.AudioLoader();
audioLoader.load( 'sounds/song.ogg', function( buffer ) {
	sound.setBuffer( buffer );
	sound.setRefDistance( 20 );
	sound.play();
});


// create an object for the sound to play from
const sphere = new THREE.SphereGeometry( 20, 32, 16 );
const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
const mesh = new THREE.Mesh( sphere, material );
scene.add( mesh );


// finally add the sound to the mesh
mesh.add( sound );

Constructor

PositionalAudio( listener : AudioListener )

listener — (required) AudioListener instance.

Properties and Methods

The properties and methods are inherited from the Audio package. The unique properties and methods are as follows:

.panner : PannerNode

The PositionalAudio's PannerNode.

.getOutput () : PannerNode

Returns the panner.

.getRefDistance () : Float

Returns the value of panner.refDistance.

.setRefDistance ( value : Float ) : this

Sets the value of panner.refDistance.

.getRolloffFactor () : Float

Returns the value of panner.rolloffFactor.

.setRolloffFactor ( value : Float ) : this

Sets the value of panner.rolloffFactor.

.getDistanceModel () : String

Returns the value of panner.distanceModel.

.setDistanceModel ( value : String ) : this

Sets the value of panner.distanceModel.

.getMaxDistance () : Float

Returns the value of panner.maxDistance.

.setMaxDistance ( value : Float ) : this

Sets the value of panner.maxDistance.

.setDirectionalCone ( coneInnerAngle : Float, coneOuterAngle : Float, coneOuterGain : Float ) : this

This method can be used in order to transform an omnidirectional sound into a directional sound.


Related Topics

ThreeJS Compatibiliy Check and Running Locally

Even though this is becoming less of an issue, some devices or browsers may still be incompatible with WebGL. The method below enables you to check if it is supported...

3 minutes read.

ThreeJS Material

Abstract base class for materials. Materials describe the appearance of objects. They are defined in a (mostly) renderer-independent way, so you don't have to rewrite materials if you decide to use...

6 minutes read.

ThreeJS BufferAttribute

This class stores data for an attribute associated with a BufferGeometry (such as vertex positions, face indices, normals, colours, UVs, and any custom attributes), allowing for more efficient data passing...

4 minutes read.

ThreeJS AnimationAction

AnimationActions are used to schedule the playback of animations saved in AnimationClips. Note that the majority of AnimationAction's methods can be chained together. The "Animation System" page in the "Next Steps" part...

6 minutes read.

ThreeJS Material - Mesh

MeshBasicMaterial A material for drawing geometries in a simple shaded (flat or wireframe) way. This material is not affected by lights. Constructor MeshBasicMaterial( parameters : Object ) parameters - (optional) an object with one or...

24 minutes read.

ThreeJS InterleavedBuffer

The term "interleaved" refers to the packing of multiple attributes, possibly of different types (e.g., position, normal, uv, colour) into a single array buffer. Constructor InterleavedBuffer( array : TypedArray, stride : Integer...

3 minutes read.

ThreeJS Loader 1

AnimationLoader Class for loading AnimationClips in JSON format. This uses the FileLoader internally for loading files. Code Example // instantiate a loader const loader = new THREE.AnimationLoader(); // load a resource loader.load( // resource URL 'animations/animation.js', // onLoad callback function...

8 minutes read.

ThreeJS Managers

DefaultLoadingManager When no custom manager is specified, most loaders use a global instance of the LoadingManager. This will suffice for most purposes, but there may be times when you want separate loading...

4 minutes read.

ThreeJS Helper 1

ArrowHelper A 3D arrow object for visualizing directions. Code Example const dir = new THREE.Vector3( 1, 2, 0 ); //normalize the direction vector (convert to vector of length 1) dir.normalize(); const origin = new THREE.Vector3( 0,...

5 minutes read.

ThreeJS Using post-processing

Many three.js applications render their 3D objects directly to the screen. Sometimes, however, you want to apply one or more graphical effects like Depth-Of-Field, Bloom, Film Grain or various types...

2 minutes read.

ThreeJS Creating VR Content

This article gives a quick introduction of the main components of a three.js-based web-based VR application. Workflow      First, you have to include VRButton.js into your project. import { VRButton } from...

1 minute read.

ThreeJS Loading 3D Models

There are hundreds of file formats for 3D models, each with its own purpose, set of features, and level of complexity. Although three.js has a lot of loaders, choosing the...

2 minutes read.

ThreeJS AnimationObjectGroup and Utils

AnimationObjectGroup A group of objects that receives a shared animation state. Usage Add items you'd normally send as 'root' to AnimationMixer's function Object() { [native code] } or clipAction method, and instead pass...

2 minutes read.

ThreeJS Testing with npm

This article explains how to install three.js in a node.js environment so that automated tests may be run. Tests can be done manually or with the help of automated CI...

4 minutes read.

ThreeJS Renderers

WebGLMultipleRenderTargets A special render target that enables a fragment shader to write to several textures. This approach is useful for advanced rendering techniques like post-processing or deferred rendering. Heads up: WebGLMultipleRenderTargets...

15 minutes read.

ThreeJS Math

Box2 Represents an axis-aligned bounding box (AABB) in 2D space. Constructor Box2( min : Vector2, max : Vector2 ) min - (optional) Vector2 representing the lower (x, y) boundary of the box. Default is...

48 minutes read.

ThreeJS Uniform

Uniforms are global GLSL variables. They are passed to shader programs. Code Example When declaring a uniform of a ShaderMaterial, it is declared by value or by object. uniforms: { time: { value: 1.0...

2 minutes read.

ThreeJS Layers

A Layers object assigns an Object3D to one or more of the 32 layers numbered 0 to 31 - the layers are internally stored as a bit mask, and all...

1 minute read.

ThreeJS AnimationClip

An AnimationClip is a group of keyframe tracks that may be reused to depict an animation. The "Animation System" page in the "Next Steps" part of the handbook provides an overview...

2 minutes read.

ThreeJS Object3D

This is the base class for most three.js objects, and it provides a set of properties and methods for manipulating objects in 3D space. It should be noted that this can...

9 minutes read.