Three.js how to fade out audio?

此生再无相见时 提交于 2019-12-23 09:38:21

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/35497506/three-js-how-to-fade-out-audio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!