Web Audio API oscillator won't make any sound

148 Views Asked by At

I'm trying to test a simple oscillator not attached to any world object on the scene. Simply a tone, but following the example for a oscillator node does not seem to play anything. Does it require some kind of user interaction first to be allowed to play?

I also have a cube rotating on the scene, but it shouldn't affect anything. The script:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

var geometry = new THREE.BoxGeometry();
var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
var cube = new THREE.Mesh( geometry, material );
scene.add( cube );

camera.position.z = 5;

function animate() {
    requestAnimationFrame( animate );

    cube.rotation.x += 0.05;
    cube.rotation.y += 0.01;

    renderer.render( scene, camera );
}
animate();


// create web audio api context
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();

// create Oscillator node
var oscillator = audioCtx.createOscillator();

oscillator.type = 'square';
oscillator.frequency.setValueAtTime(440, audioCtx.currentTime); // value in hertz
var gainNode = audioCtx.createGain();
oscillator.connect(gainNode);
oscillator.connect(audioCtx.destination);

var initialFreq = 3000;
var initialVol = 0.500;

gainNode.gain.value = initialVol;
gainNode.gain.minValue = initialVol;
gainNode.gain.maxValue = initialVol;

oscillator.frequency.value = 3000;

oscillator.start();
0

There are 0 best solutions below