three.js WebAudio -2 Audio(全局音频)

Audio(全局音频)

创建一个(全局)audio对象.
实例化:(需要传入listener对象,具体查看上篇文章)

var sound=new THREE.Audio(listener);

属性:
(1).autoplay : Boolean
是否自动开始播放. 默认为 false.

(2).hasPlaybackControl : Boolean
是否可以使用 play(), pause()等方法控制播放. 默认为 true.

(3).playbackRate : Number
播放速率. 默认为 1.

方法:
(1).getPlaybackRate () : Float
返回playbackRate的值.

(2).getVolume ( value ) : Float
返回当前对象音量.

(3).setVolume ( value : Float ) : Audio
设置当前对象音量.

(4).play () : Audio
如果hasPlaybackControl是true, 开始播放.

(5).pause () : Audio
如果hasPlaybackControl是true, 暂停播放.

(6).stop () : Audio
如果hasPlaybackControl是true, 停止播放, 重新设置startTime为 0 和 设置 isPlaying为false.

(7).onEnded () : null
播放完成后自动调用. 如果isPlaying设置为false.

(8).setBuffer ( audioBuffer ) : Audio
给一个加载器对象设置音频对象的缓存。
设置source给audioBuffer, 和设置sourceType给’buffer’.
如果autoplay为true, 也开始播放.

(9).setLoop ( value : Boolean ) : Audio
设置source.loop 的值 (是否循环播放).

(10).setMediaElementSource ( mediaElement ) : Audio
应用HTMLMediaElement类型对象作为音源.
并且设置hasPlaybackControl为false.

加载音频的两种方式

①通过html标签加载
先创建标签

		<audio loop id="music" preload="auto" style="display: none;">
			<source src="img/sounds/test1.mp3"></source>
			<source src="img/sounds/test1.ogg"></source>
		</audio>

然后通过js获取对象

                var music=document.getElementById("music");
				music.play();
				sound.setMediaElementSource(music);

②通过音频加载器(AudioLoader)缓存

				// 初始化一个加载器,然后加载资源
				var auLoader=new THREE.AudioLoader();
				auLoader.load("sounds/test1.ogg",function(buffer){
					sound.setBuffer(buffer);// 给一个加载器对象设置音频对象的缓存
					sound.play();// 播放音频
				},function(xhr){// onProgress回调
					console.log("audio "+(xhr.loaded/xhr.total)*100+" % loaded");
				},function(error){// onError回调
					console.error("an error happened !");
				});

效果例子查看地址(音频加载需要一定时间!)

示例代码:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>threejs加载全局音频对象</title>
		<script type="text/javascript" src="js/three.js" ></script>
		<script type="text/javascript" src="js/controls/OrbitControls.js" ></script>
		<script type="text/javascript" src="js/libs/stats.min.js" ></script>
		<script type="text/javascript" src="js/libs/dat.gui.min.js" ></script>
		<script type="text/javascript" src="js/WebGL.js" ></script>
		<style>
			body{
				padding: 0;
				margin: 0;
				overflow: hidden;
			}
			#overlay{
				position:absolute;
				z-index: 100;
				width: 100%;
				height: 100%;
				background-color: #000000;
				color:#ffffff;
				text-align: center;
			}
			#start_btn{
				margin-top: 300px;
				height: 20px;
				width: 100px;
				color:#ffffff;
				border:0px;
				outline: 1px solid #ffffff;
				background: transparent;
				cursor: pointer;
			}
		</style>
	</head>
	<body>
<!--	<audio loop id="music" preload="auto" style="display: none;">
			<source src="sounds/test1.ogg"></source>
		</audio>-->
		
		<div id="overlay">
			<button id="start_btn">点击播放</button>
			<p>Automatic audio playback requires a user interaction.</p>
		</div>
		
		<script>
			if(WEBGL.isWebGLAvailable()===false){alert("该浏览器不支持WebGL!");document.body.appendChild(WEBGL.getErrorMessage());}
			
			document.getElementById("start_btn").addEventListener("click",init,false);
			
			var scene,renderer,camera,controls,stats;		
			function init(){
				document.getElementById("overlay").remove();
				
				scene=new THREE.Scene();
				
				renderer=new THREE.WebGLRenderer({
					antialias:true,
				});
				renderer.setSize(window.innerWidth,window.innerHeight);
				renderer.setPixelRatio(window.devicePixelRatio);
				renderer.shadowMap.enabled=true;
				renderer.shadowMap.type=THREE.PCFSoftShadowMap;
				document.body.appendChild(renderer.domElement);
				
				camera=new THREE.PerspectiveCamera(60,window.innerWidth/window.innerHeight,0.1,1000);
				camera.position.set(0,20,50);
				camera.lookAt(scene.position);
				
				controls=new THREE.OrbitControls(camera,renderer.domElement);
				controls.enableDamping=true;
				controls.minDistance=0.1;
				controls.maxDistance=1000;
				
				stats=new Stats();
				document.body.appendChild(stats.domElement);
				
				scene.add(new THREE.AmbientLight(0x404040));
				
				var dLight=new THREE.DirectionalLight(0xffffff,1.5);
				dLight.position.set(10,10,0);
				dLight.castShadow = true;
				dLight.shadow.camera.top = 10;
				dLight.shadow.camera.bottom = - 10;
				dLight.shadow.camera.left = - 10;
				dLight.shadow.camera.right = 10;
				dLight.shadow.camera.near = 10;
				dLight.shadow.camera.far = 50;
				scene.add(dLight);
				
				initModel();
				initGui();
				animate();
			};
			
			var axes;var mesh;			
			function initModel(){
				axes=new THREE.AxesHelper(30);
				axes.visible=false;
				scene.add(axes);
				
				var grid=new THREE.GridHelper(50,50,0xff00ff,0xffff00);
				grid.material.transparent=true;
				grid.material.opacity=0.5;
				scene.add(grid);
				
				var ground=new THREE.Mesh(new THREE.PlaneBufferGeometry(50,50,1),new THREE.MeshPhongMaterial({
					color:0x999999
				}));
				ground.rotation.x=-Math.PI/2;
				ground.receiveShadow=true;
				scene.add(ground);
				
				//建立球模型
				mesh=new THREE.Mesh(new THREE.SphereBufferGeometry(2,15,15),new THREE.MeshPhongMaterial({
					color:0xffffff*Math.random(),
					flatShading:true
				}));
				mesh.position.set(0,3,0);
				mesh.castShadow=true;
				scene.add(mesh);
				
				// 初始化一个监听
				var listener=new THREE.AudioListener();
				camera.add(listener);// 把监听添加到camera
				
				// 初始化音频对象,并加入监听
				var sound=new THREE.Audio(listener);
				//scene.add(sound);// 添加一个音频对象到场景中
				
				// 初始化一个加载器,然后加载资源
				var auLoader=new THREE.AudioLoader();
				auLoader.load("sounds/test1.ogg",function(buffer){
					sound.setBuffer(buffer);// 给一个加载器对象设置音频对象的缓存
					sound.play();// 播放音频
				},function(xhr){// onProgress回调
					console.log("audio "+(xhr.loaded/xhr.total)*100+" % loaded");
				},function(error){// onError回调
					console.error("an error happened !");
				});
				mesh.add(sound);
								
				//不使用threejs加载器播放音频
/*				var music=document.getElementById("music");
				music.play();
				sound.setMediaElementSource(music);
				mesh.add(sound);*/
				
			}
			
			var setting;			
			function initGui(){
				setting={
					axesVisible:false,
				};
				var gui=new dat.GUI();
				gui.add(setting,"axesVisible").onChange(function(e){
					axes.visible=e;
				});
			}
			
			
			function onWindowResize(){
				camera.aspect=window.innerWidth/window.innerHeight;
				camera.updateProjectionMatrix();
				renderer.setSize(window.innerWidth,window.innerHeight);
			}
			
			function animate(){
				renderer.render(scene,camera);
				stats.update();
				mesh.rotation.y+=0.01;
				controls.update();		
				window.onresize=onWindowResize();
				requestAnimationFrame(animate);
			}
		</script>
	</body>
</html>

你可能感兴趣的:(threejs-音频和辅助线)