Three.js how to fade out audio?
Asked Answered
H

2

6

A want to make crossfade effect between two audio. I try Tween.JS for that, but it's not do it smoothly, how I want...

var sound_b_1 = new THREE.PositionalAudio( listener );
sound_b_1.load('mysound.ogg');
sound_b_1.setRefDistance(20);
sound_b_1.setVolume(1);
sound_b_1.autoplay = true;
scene.add(sound_b_1);

var volume = {x : 1}; // tweens not work without object
// using Tween.js
new TWEEN.Tween(volume).to({ 
    x: 0
}, 1000).onUpdate(function() {
   sound_b_1.setVolume(this.x);
}).onComplete(function() {
    sound_b_1.stop();
}).start();

Hot to do that using Tween or other ways?

Hitherto answered 19/2, 2016 at 4:47 Comment(1)
so the code you have is not working? can you create a fiddle?Saccharase
Q
3

I do not see anything wrong with the code you provided, works fine for me, only it is not complete. You need to call TWEEN.update(time) in your render/update function:

complete code:

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 );

camera.position.z = 5;

var listener = new THREE.AudioListener();
var sound_b_1 = new THREE.PositionalAudio( listener )
sound_b_1.load('mysound.ogg');
sound_b_1.setRefDistance(20);
sound_b_1.setVolume(1);
sound_b_1.autoplay = true;
scene.add(sound_b_1);

var volume = {x : 1}; // tweens not work without object
// using Tween.js
new TWEEN.Tween(volume).to({
    x: 0
}, 1000).onUpdate(function() {
   sound_b_1.setVolume(this.x);
}).onComplete(function() {
    sound_b_1.stop();
}).start();

var time = 0; // incrementing time variable
var render = function () {
    requestAnimationFrame( render );
    // normally the render render function is called 60 times a second.
    // convert to milliseconds
    time += ((1/60) * 1000);
    TWEEN.update(time);

    renderer.render(scene, camera);
};
//setTimeout(()=>{sound_b_1.stop();}, 5000);
render();

This will cause mysound.ogg to start playing at full volume and then interpolated linearly to no volume at all and then stop playing.

If you want another audio clip to start playing you just do the same thing but let the volume start at 0 and interpolate to 1.

Quadrifid answered 27/2, 2016 at 18:39 Comment(0)
S
0

Other solution would be using THREE.audioListener internal volume value:

var listener = new THREE.AudioListener();

new TWEEN.Tween(listener.gain.gain)
  .to(
   {
   value: 0,
   },
   1000
  ).start()
Spillway answered 26/2, 2021 at 10:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.