Skip to main content

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​

ParameterTypeDefaultDescription
xnumberrequiredListener position on the x axis.
ynumberrequiredListener position on the y axis.
znumberrequiredListener position on the z axis.
skipDispatchEventbooleanfalseSet 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') with isMaster: true, position, orientation (the forward vector) and up.
  • Only sounds with a 3D panner are affected. Stereo panned sounds sound the same wherever the listener is.

See also​