setListenerPosition
Move the listener, the ear in the scene. Moving sounds around a fixed ear works for a menu or a map. A first-person camera needs it the other way round: the sounds stay where they are and you move.
setListenerPosition(x: number, y: number, z: number, skipDispatchEvent?: boolean): void;
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
x | number | required | Listener position on the x axis. |
y | number | required | Listener position on the y axis. |
z | number | required | Listener position on the z axis. |
skipDispatchEvent | boolean | false | Set to true to leave out the listener_changed event, for example when you update the listener every frame. |
Returns
Nothing.
Example
import { SoundHub } from 'soundhub';
const soundHub = new SoundHub();
await soundHub.loadSound('rain', '/audio/rain.mp3');
// The rain stays put, ten units ahead
soundHub.play('rain', { loop: true });
soundHub.setSpatialPosition(0, 0, -10, 'rain');
// Follow the player and the camera every frame
function onFrame() {
soundHub.setListenerPosition(player.x, 0, player.z, true);
soundHub.setListenerOrientation(camera.forwardX, 0, camera.forwardZ, 0, 1, 0, true);
requestAnimationFrame(onFrame);
}
requestAnimationFrame(onFrame);
// Read it back, or start over
soundHub.getListenerPosition(); // { x: 3, y: 0, z: -4 }
soundHub.getListenerOrientation(); // { forward: { x, y, z }, up: { x, y, z } }
soundHub.resetListener(); // back to 0, 0, 0, looking down negative z
Moving the listener and moving sounds use the same panner nodes, so you can mix them: move the listener with the camera and keep moving a helicopter with setSpatialPosition.
Good to know
- Added in 6.2.0.
- Does nothing when spatial audio is off or unsupported, which it is only on request or in a browser without the listener audio params. Spatial audio is on by default.
- The values are rounded to 2 decimals.
- Every call dispatches
SoundEventsEnum.LISTENER_CHANGED('listener_changed') withisMaster: true,position,orientation(the forward vector) andup. - Only sounds with a 3D panner are affected. Stereo panned sounds sound the same wherever the listener is.
See also
setListenerOrientation: turn the listener's head.getListenerPosition: read the position back.resetListener: back to the centre.setSpatialPosition: move a sound instead.- Spatial audio: the overview.