three.js: Control gui and play sound set Volume

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <meta name="apple-moible-web-app-capable" content="yes">
    <meta name="apple-moible-web-app-status-bar-style" content="black">
    <title>Control gui and set Volume</title>
    <meta content=" Three.js r95 声音调节 set Volume" name="keywords">
    <meta content=" Three.js r95 播放声音并调节 set Volume" name="description">
    <meta name="author" content="Geovin Du 涂聚文 塗聚文">
    <link rel="shortcut icon" href="~/favicon.ico" type="image/x-icon" />
    <link rel="icon" href="/favicon.ico" />
    <link rel="bookmark" href="/favicon.ico" type="image/gif" />
    <script type="text/javascript" charset="UTF-8" src="../libs/three/three.js"></script>
    <script type="text/javascript" charset="UTF-8" src="../libs/three/controls/TrackballControls.js"></script>
    <script type="text/javascript" src="../libs/util/Stats.js"></script>
    <script type="text/javascript" src="../libs/util/dat.gui.js"></script>
    <script type="text/javascript" src="js/util.js"></script>
    <script type="text/javascript">
        function init() {
 
 
            // listen to the resize events  监听窗体大小事件
            window.addEventListener('resize', onResize, false);
            var uniforms; //音量调节
            var fftSize = 0.2;
            var stats = initStats();
 
            //声音
            var audioListener = new THREE.AudioListener();
 
            // create a scene, that will hold all our elements such as objects, cameras and lights.
            var scene = new THREE.Scene();
 
            // create a camera, which defines where we're looking at.
            var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
 
            // create a render and set the size
            var renderer = new THREE.WebGLRenderer();
 
            renderer.setClearColor(new THREE.Color(0x000000));
            renderer.setSize(window.innerWidth, window.innerHeight);
            renderer.shadowMap.enabled = true;
 
            // create the ground plane
            var planeGeometry = new THREE.PlaneGeometry(60, 20, 1, 1);
            var planeMaterial = new THREE.MeshLambertMaterial({ color: 0xffffff });
            var plane = new THREE.Mesh(planeGeometry, planeMaterial);
            plane.receiveShadow = true;
 
            // rotate and position the plane
            plane.rotation.x = -0.5 * Math.PI;
            plane.position.x = 15;
            plane.position.y = 0;
            plane.position.z = 0;
 
            // add the plane to the scene
            scene.add(plane);
 
            // create a cube
            var cubeGeometry = new THREE.BoxGeometry(4, 4, 4);
            var cubeMaterial = new THREE.MeshLambertMaterial({ color: 0xff0000 });
            var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
            cube.castShadow = true;
            // position the cube
            cube.position.x = -4;
            cube.position.y = 3;
            cube.position.z = 0;
 
            // add the cube to the scene
            scene.add(cube);
 
            var sphereGeometry = new THREE.SphereGeometry(4, 20, 20);
            var sphereMaterial = new THREE.MeshLambertMaterial({ color: 0x7777ff });
            var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
 
            // position the sphere
            sphere.position.x = 20;
            sphere.position.y = 0;
            sphere.position.z = 2;
            sphere.castShadow = true;
 
            // add the sphere to the scene
            scene.add(sphere);
 
            // position and point the camera to the center of the scene
            camera.position.x = -30;
            camera.position.y = 40;
            camera.position.z = 30;
            camera.lookAt(scene.position);
 
 
 
 
            // 设置声音add the listener to the camera
            camera.add(audioListener);
            // instantiate audio object
            var oceanAmbientSound = new THREE.Audio(audioListener);
            // add the audio object to the scene
            scene.add(oceanAmbientSound);  
 
            // instantiate a loader
            var loader = new THREE.AudioLoader();
            // load a resource
            loader.load(
                // resource URL
                '../assets/audio/ping_pong.mp3',
                // Function when resource is loaded
                function (audioBuffer) {
                    // set the audio object buffer to the loaded object
                    oceanAmbientSound.setBuffer(audioBuffer);
                    oceanAmbientSound.setLoop(true); // 一次
                     
                    oceanAmbientSound.setVolume(0.1);
                    // play the audio
                    oceanAmbientSound.play();
                    //oceanAmbientSound.stop();  //停止
                },
                // Function called when download progresses
                function (xhr) {
                    console.log((xhr.loaded / xhr.total * 100) + '% loaded');
                },
                // Function called when download errors
                function (xhr) {
                    console.log('An error happened');
                }
            );
 
 
            // create an AudioAnalyser, passing in the sound and desired fftSize
            var analyser = new THREE.AudioAnalyser(oceanAmbientSound, 32);          
            //
            const format = (renderer.capabilities.isWebGL2) ? THREE.RedFormat : THREE.LuminanceFormat;
            uniforms = {
                tAudioData: { value: new THREE.DataTexture(analyser.data, fftSize / 2, 1, format) }
            };
 
            // get the average frequency of the sound
            var data = analyser.getAverageFrequency();
            var listener = new THREE.AudioListener();
            camera.add(listener);
            //
 
 
            // add subtle ambient lighting
            var ambienLight = new THREE.AmbientLight(0x353535);
            scene.add(ambienLight);
 
            // add spotlight for the shadows
            var spotLight = new THREE.SpotLight(0xffffff);
            spotLight.position.set(-10, 20, -5);
            spotLight.castShadow = true;
            scene.add(spotLight);
 
            // add the output of the renderer to the html element
            document.getElementById("webgl-output").appendChild(renderer.domElement);
 
            // call the render function
            var step = 0;
            var num = 0;
            //添加控件
            var controls = new function () {
                this.rotationSpeed = 0.02;
                this.bouncingSpeed = 0.03;
                this.SoundSpeed = 0.1;
            };
 
            var gui = new dat.GUI();
            gui.add(controls, 'rotationSpeed', 0, 0.5);
            gui.add(controls, 'bouncingSpeed', 0, 0.5);
            gui.add(controls, 'SoundSpeed', 0, 0.5);  //音量调节
 
            // attach them here, since appendChild needs to be called first
            var trackballControls = initTrackballControls(camera, renderer);
            var clock = new THREE.Clock();
 
            render();
 
            function render() {
                // update the stats and the controls
                trackballControls.update(clock.getDelta());
                stats.update();
 
                //声音音量调节
                num += controls.SoundSpeed;
                oceanAmbientSound.setVolume(num);
                if (num = 0)
                    oceanAmbientSound.stop();  //停止
               // analyser.getFrequencyData();
                uniforms.tAudioData.value.needsUpdate = true;
 
 
                // rotate the cube around its axes
                cube.rotation.x += controls.rotationSpeed;
                cube.rotation.y += controls.rotationSpeed;
                cube.rotation.z += controls.rotationSpeed;
 
                // bounce the sphere up and down
                step += controls.bouncingSpeed;
 
                sphere.position.x = 20 + (10 * (Math.cos(step)));
                sphere.position.y = 2 + (10 * Math.abs(Math.sin(step)));
 
                // render using requestAnimationFrame
                requestAnimationFrame(render);
                renderer.render(scene, camera);
            }
 
            //根据窗体的大小改变,有一定的算法
            function onResize() {
                camera.aspect = window.innerWidth / window.innerHeight;
                camera.updateProjectionMatrix();
                renderer.setSize(window.innerWidth, window.innerHeight);
            }
        }
    </script>
    <link rel="stylesheet" href="../css/default.css">
</head>
<body>
    <div id="webgl-output"></div>
 
    <!-- Javascript code that runs our Three.js examples -->
    <script type="text/javascript">
        (function () {
            // your page initialization code here
            // the DOM will be available here
            init()
        })();
    </script>
</body>
</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值