Skip to main content

setSpatialPosition

Place a sound in 3D space. Call it once to position a sound, or every frame to move it, such as a helicopter flying past.

setSpatialPosition(x: number, y: number, z: number, soundId?: string | null, soundPannerConfig?: SoundPannerConfig, skipDispatchEvent?: boolean): void;

Parameters​

ParameterTypeDefaultDescription
xnumberrequiredPosition on the x axis. With the default listener, positive x is to the right.
ynumberrequiredPosition on the y axis. Positive y is up.
znumberrequiredPosition on the z axis. The default listener looks down negative z, so -5 is in front of you.
soundIdstring | nullundefinedID of the sound to move. Leave it out, or pass null, to move the master panner instead (see Good to know).
soundPannerConfigSoundPannerConfigundefinedPanner settings such as panningModel, distanceModel and the cone angles. See Spatial audio.
skipDispatchEventbooleanfalseSet to true to leave out the spatial_position_changed event, for example when you update the position every frame.

Returns​

Nothing.

Example​

import { SoundHub, PanningModel, DistanceModel } from 'soundhub';

const soundHub = new SoundHub();
await soundHub.loadSound('rain', '/audio/rain.mp3');

soundHub.play('rain', { loop: true });

// Five units in front and two to the left, with custom panner settings
soundHub.setSpatialPosition(-2, 0, -5, 'rain', {
panningModel: PanningModel.HRTF,
distanceModel: DistanceModel.Inverse,
refDistance: 1,
rolloffFactor: 2,
});

// Circle around the listener without flooding the event bus
let angle = 0;
function onFrame() {
angle += 0.02;
soundHub.setSpatialPosition(Math.cos(angle) * 4, 0, Math.sin(angle) * 4, 'rain', undefined, true);
requestAnimationFrame(onFrame);
}
requestAnimationFrame(onFrame);

Good to know​

  • Does nothing when spatial audio is off or unsupported. Check isSpatialAudioEnabled if nothing happens.
  • Coordinates are rounded to 2 decimals.
  • If the sound has a stereo panner, it is removed without a pan_changed event and the sound switches to SoundPanType.Spatial.
  • The panner settings are built once, when the panner is created: the defaults, then pannerNodeConfig from the hub config, then soundPannerConfig. On later calls only the keys you pass in soundPannerConfig are changed.
  • The position is written to the sound's play options, so the next play() starts at the same spot. You can also call it before play().
  • Without a soundId the call goes to setMasterSpatialPosition. skipDispatchEvent is not passed along, so a global_spatial_position_changed event is always dispatched.
  • An unknown id, or the id of a stream, is ignored without an error. Otherwise every call dispatches SoundEventsEnum.SPATIAL_POSITION_CHANGED ('spatial_position_changed') with position and pannerConfig.

See also​