three.js: Control gui or play sound

时间:2021-03-04 13:32:30   收藏:0   阅读:0

 

<!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</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/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/cow.ogg‘,
                // 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 ) }

				};

  

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!