beek
beek

Reputation: 3750

Web Audio with Three.js position 3D sounds

I've got a panorama player with 3d sounds I'm attempting to implement in Three.js and attempting to follow this http://www.html5rocks.com/en/tutorials/webaudio/positional_audio/

The camera is fixed, and the 3D sounds are placed around the scenes and I want the volume to be affected by if the camera is facing the scene or not.

The sounds are created thus (where position is a vector3)

function playSound(buffer, looping, position, volume) {
    var sound = {};
    sound.source = context.createBufferSource();
    sound.volume = context.createGain();
    sound.source.connect(sound.volume);
    sound.volume.connect(mainVolume);

     var gainNode = context.createGain();
     gainNode.gain.value = volume;
     sound.source.connect(gainNode);


    sound.source.buffer = buffer;
     if(looping)
         sound.source.loop = true;
     sound.source.connect(context.destination);
     sound.source.start();

     sound.panner = context.createPanner();
     sound.position = position;

     //sound.panner.updateMatrixWorld();
     sound.volume.connect(sound.panner);
     sound.panner.connect(mainVolume);

     sceneSounds.push( sound );
 }

This works well.

On the render loop

   lat = Math.max(-85, Math.min(85, lat));
    phi = THREE.Math.degToRad(90 - lat);
    theta = THREE.Math.degToRad(lon);

    target.x = 512 * Math.sin(phi) * Math.cos(theta);
    target.y = 512 * Math.cos(phi);
    target.z = 512 * Math.sin(phi) * Math.sin(theta);

    camera.lookAt(target);

    if(sceneSounds.length > 0)
        updateSceneSounds( target );

I'm calling this, with the camera target

function updateSceneSounds( target )
{

    for(var s in sceneSounds){
        var sound = sceneSounds[s];
        distance = sound.position.distanceTo( target );

        console.log( distance );

    }
}

The distances are coming out at numbers between 400-500, which won't really help I don't think, and are probably the wrong value to use.

Any clues or ideas the best way to go about this?

Upvotes: 1

Views: 5419

Answers (1)

mrdoob
mrdoob

Reputation: 19602

I just added this functionality today. Here's my implementation:

https://github.com/mrdoob/three.js/commit/5ba54f71665ff4cd714d0db26c5a32c2b1c1cc8c

Upvotes: 6

Related Questions