audio

Sound makes simulations seem much more real. This example simulates a sound eminating from a red cube. The sound plays forever, but its volume is adjusted depending on the distance of the camera from the cube.

Mixer.init(10);

The mixer is an object that can play multiple simultaneous sounds for you, i.e. it mixes them together. The maximum number of simultaneous sounds (the "polyphony") is controlled by the argument, here set to 10.

var snd = MediaLoader.loadSound("alarm","sounds/129464__robinhood76__02832-heavy-alarm.wav");

This is how individual sounds are loaded. The first argument is a name for the sound, and is currently not used. The second is a path to the particular sound file to load. The supported HTML5 audio formats are currently wav, mp3, and ogg.

The MediaLoader object can also load images. MediaLoader.loadingComplete() is not used here, but it returns true only when all sounds (and images) have been loaded. This might be a good idea if you are loading so many that it takes a substantial amount of time.

var chan = Mixer.play(snd,0.0,true);

Now the sound snd (first argument) is playing with volume 0.0 (second argument) and in looping mode (third argument). The return value is the channel, which needs to be stored in order to adjust the volume while the sound is playing.

The render function now looks like this:

var renderFunc = function() {
  control.update(dt);
  renderer.render(scene,camera);
  chan.volume = computeVolume();
};

Note that in addition to updating the controller and rendering the scene, the volume of the channel is updated according to this function:

function computeVolume() {
  var diff = new THREE.Vector3();
  diff.subVectors(camera.position,cube.position);
  var dist = diff.length();
  var vol;
  if (dist>1.0)
    vol = 1.0/dist;  
  else
    vol = 1.0;
  return vol;
}

This function does some simple vector math to compute the distance of the camera from the cube. The volume is set to the maximum value (1.0) if we are with one unit distance from the cube, otherwise the inverse of the distance is used.

1-2-three
example 3: audio