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>

  

 

//

				const listener = new THREE.AudioListener();

				const audio = new THREE.Audio( listener );
				const file = './sounds/376737_Skullbeatz___Bad_Cat_Maste.mp3';

				if ( /(iPad|iPhone|iPod)/g.test( navigator.userAgent ) ) {

					const loader = new THREE.AudioLoader();
					loader.load( file, function ( buffer ) {

						audio.setBuffer( buffer );
						audio.play();

					} );

				} else {

					const mediaElement = new Audio( file );
					mediaElement.play();

					audio.setMediaElementSource( mediaElement );

				}

				analyser = new THREE.AudioAnalyser( audio, fftSize );

				//

				const format = ( renderer.capabilities.isWebGL2 ) ? THREE.RedFormat : THREE.LuminanceFormat;

				uniforms = {

					tAudioData: { value: new THREE.DataTexture( analyser.data, fftSize / 2, 1, format ) }

				};

  

 增加一个bottom按扭操作关开声音

<!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>Example 12.07 - Audio</title>
    <meta content=" Three.js r95" name="keywords">
    <meta content=" Three.js r95" 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/FirstPersonControls.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();


            // create a scene, that will hold all our elements such as objects, cameras and lights.
            var scene = new THREE.Scene();


            //声音
            var audioListener = new THREE.AudioListener();


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



            // Buttons startButton and resetButton
            //var startButton = document.getElementById('buttonaudioButton');
            //startButton.addEventListener('click', init);





            // call the render function
            var step = 0;
            var ro = 0;
            var controls = new function () {
                this.rotationSpeed = 0.02;
                this.bouncingSpeed = 0.03;
            };

            var gui = new dat.GUI();
            gui.add(controls, 'rotationSpeed', 0, 0.5);
            gui.add(controls, 'bouncingSpeed', 0, 0.5);


            // attach them here, since appendChild needs to be called first
            //  var trackballControls = initTrackballControls(camera, renderer);
            var clock = new THREE.Clock();

            // Boolean for start and restart
            var initAnim = true;
            var runAnim = false;

            var startButton = document.getElementById('buttonaudioButton');
            // startButton.addEventListener('click', init, false); //加载
            //bdat.gui.js.map
            startButton.innerHTML = '<img src="../../gui/volumeOff.png">';
            // Start Button
            startButton.onclick = function StartAnimation() {
                if (initAnim) {
                    initAnim = false;
                    runAnim = true;
                    theta = 0;
                    startButton.innerHTML = '<img src="../../gui/volumeOff.png">';
                }
                // Start and Pause
                if (runAnim) {
                    startButton.innerHTML = '<img src="../../gui/volumeOff.png">';
                    runAnim = false;

                } else {
                    startButton.innerHTML = '<img src="../../gui/volumeOn.png">';
                    runAnim = true;

                }
            }
            /**/


            //

            var audio = new THREE.Audio(audioListener);

            analyser = new THREE.AudioAnalyser(audio, 32);
            //
            var file = '../assets/audio/ping_pong.mp3';

            if (/(iPad|iPhone|iPod)/g.test(navigator.userAgent)) {

                const loader = new THREE.AudioLoader();
                loader.load(file, function (buffer) {

                    audio.setBuffer(buffer);
                    audio.setLoop(true); // 一次
                    audio.setVolume(0.5);
                    audio.play();

                });

            } else {

                const loader = new THREE.AudioLoader();
                loader.load(file, function (buffer) {

                    audio.setBuffer(buffer);
                    audio.setLoop(true); // 重复 false一次
                    audio.setVolume(0.5);
                    audio.play();

                });


                /*
                //2 不可以连续播放
                const mediaElement = new Audio(file);
               // mediaElement.setBuffer(buffer);
                mediaElement.play();
                audio.setMediaElementSource(mediaElement);
                */

            }

            /**/
            var format = (renderer.capabilities.isWebGL2) ? THREE.RedFormat : THREE.LuminanceFormat;

            uniforms = {

                tAudioData: { value: new THREE.DataTexture(analyser.data, fftSize / 2, 1, format) }

            };

            animate();
            //render();


            function animate() {

                requestAnimationFrame(animate);
                render();

            }


            function render() {

                //  // update the stats and the controls
                //trackballControls.update(clock.getDelta());
                // stats.update();
                //
                if (runAnim) {
                    audio.play();
                }
                else {
                    audio.stop();  //停止}
                }


                analyser.getFrequencyData();
                uniforms.tAudioData.value.needsUpdate = true;



                ro += controls.rotationSpeed;
                // rotate the cube around its axes
                cube.rotation.x += controls.rotationSpeed;
                cube.rotation.y += controls.rotationSpeed;
                cube.rotation.z += controls.rotationSpeed;
                console.log("ro:" + ro);
                // 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)));
                console.log("setp:" + 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">
    <style>
        div {
            display: block;
        }

        #fwa {
            width: 100px;
            height: 100px;
            left: 0;
            bottom: 0;
            position: absolute;
            opacity: 0;
            z-index: 10
        }

        .buttonBG {
            z-index: 2;
            background-color: #000;
            position: absolute;
            border: 1px solid #fff;
        }

        .button {
            text-align: center;
            font-size: 1em;
            color: #eee;
            line-height: 40px;
            z-index: 40;
            position: absolute;
        }

        #topLeft {
            left: 15px;
        }

        #topLeft, #topRight {
            width: 130px;
            height: 40px;
            position: absolute;
            z-index: 2;
            top: 150px;
        }


        #topRight {
            right: 15px;
        }

        #topLeft, #topRight {
            width: 130px;
            height: 40px;
            position: absolute;
            z-index: 2;
            top: 150px;
        }

        #toolBar {
            width: 590px;
            height: 40px;
            left: 50%;
            margin-left: -145px;
            bottom: 40px;
            z-index: 2;
            position: absolute;
            color: #ff0000;
        }
    </style>
</head>
<body>
    <div id="webgl-output"></div>
    <div id="toolBar"><div id="audioButton" style="visibility: visible; left: 255px;"><div id="backgroundaudioButton" class="buttonBG" style="width: 40px; height: 40px; opacity: 0.5; left: 255px;"></div><div id="buttonaudioButton" class="button" style="width: 40px; height: 40px; left: 255px;"><img src="../../gui/volumeOn.png"></div></div></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>

  

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



            // Boolean for start and restart
            var initAnim = true;
            var runAnim = false;

            // Buttons startButton and resetButton
            var startButton = document.getElementById('buttonaudioButton');
            //startButton.addEventListener('click', init);

            //开始加载时
            startButton.innerHTML = '<img src="../../gui/volumeOff.png" alt="关" title="关">';
            // Start Button
            startButton.onclick = function StartAnimation() {

                if (initAnim) {
                    initAnim = false;
                    runAnim = true;
                    theta = 0;
                    startButton.innerHTML = '<img src="../../gui/volumeOff.png" alt="关"   title="关">';
                    //render();
                }
                // Start and Pause
                if (runAnim) {
                    startButton.innerHTML = '<img src="../../gui/volumeOff.png" alt="关" title="关">';
                    runAnim = false;
                    // render();
                } else {
                    startButton.innerHTML = '<img src="../../gui/volumeOn.png" alt="开" title="开">';
                    runAnim = true;
                    // render();
                }
            }


            // 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, 5.0);  //音量调节最高值

            // attach them here, since appendChild needs to be called first
            var trackballControls = initTrackballControls(camera, renderer);
            var clock = new THREE.Clock();




            animate();
            //render();


            function animate() {

                requestAnimationFrame(animate);
                render();

            }



            //render();

            function render() {
                // update the stats and the controls
               // trackballControls.update(clock.getDelta());
                //stats.update();


                if (runAnim)
                    oceanAmbientSound.play()
                else
                    oceanAmbientSound.stop();  //停止

                //声音音量调节
                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">
    <style>
        div {
            display: block;
        }

        #fwa {
            width: 100px;
            height: 100px;
            left: 0;
            bottom: 0;
            position: absolute;
            opacity: 0;
            z-index: 10
        }

        .buttonBG {
            z-index: 2;
            background-color: #000;
            position: absolute;
            border: 1px solid #fff;
        }

        .button {
            text-align: center;
            font-size: 1em;
            color: #eee;
            line-height: 40px;
            z-index: 40;
            position: absolute;
        }

        #topLeft {
            left: 15px;
        }

        #topLeft, #topRight {
            width: 130px;
            height: 40px;
            position: absolute;
            z-index: 2;
            top: 150px;
        }


        #topRight {
            right: 15px;
        }

        #topLeft, #topRight {
            width: 130px;
            height: 40px;
            position: absolute;
            z-index: 2;
            top: 150px;
        }

        #toolBar {
            width: 590px;
            height: 40px;
            left: 50%;
            margin-left: -145px;
            bottom: 40px;
            z-index: 2;
            position: absolute;
            color: #ff0000;
        }
    </style>
</head>
<body>
    <div id="webgl-output"></div>
    <div id="toolBar"><div id="audioButton" style="visibility: visible; left: 255px;"><div id="backgroundaudioButton" class="buttonBG" style="width: 40px; height: 40px; opacity: 0.5; left: 255px;"></div><div id="buttonaudioButton" class="button" style="width: 40px; height: 40px; left: 255px;"><img src="../../gui/volumeOn.png" alt="开" title="开"></div></div></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>

  

 

posted @ 2021-03-04 11:24  ®Geovin Du Dream Park™  阅读(126)  评论(0编辑  收藏  举报