效果:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>音频与场景关联(音源、监听者)</title>
<script src="../three.js"></script>
<script src="../OrbitControls.js"></script>
</head>
<body>
<script>
let N = 128;
let analyser = null;
// 1,创建场景
var scene = new THREE.Scene();
// 2, 创建多个网格模型组成组对象
var group = new THREE.Group();
var material = new THREE.MeshPhongMaterial({color:0x0000ff});
for (let index = 0; index < N / 2; index++) {
var box = new THREE.BoxGeometry(5,100,5);
var mesh = new THREE.Mesh(box,material);
mesh.position.set(20*index-N/2*10,0,0);
group.add(mesh);
}
scene.add(group);
// 加载音乐部分
var listener = new THREE.AudioListener(); // 创建音频监听器
var audio = new THREE.Audio(listener) // 创建音频,参数是音频监听器
var loader = new THREE.AudioLoader(); // 创建音频加载器
loader.load("./Honor.mp3",audioBuffer => {
audio.setBuffer(audioBuffer); // 设置音频源
audio.setLoop(true); // 设置循环播放
audio.setVolume(0.5); // 设置音量
audio.play();
// 创建音频分析器;参数是音频
analyser = new THREE.AudioAnalyser(audio);
})
// 3,创建灯光
var ambient = new THREE.AmbientLight(0xffffff);
scene.add(ambient);
// 4,创建相机对象
var width = window.innerWidth;
var height = window.innerHeight;
var k = width / height;
var s = 200;
var camera = new THREE.OrthographicCamera(-s*k,s*k,s,-s,-2000,2000);
camera.position.set(0,100,1200);
camera.lookAt(scene.position);
// 5,创建渲染器
var renderer = new THREE.WebGLRenderer();
renderer.setSize(width,height);
document.body.appendChild(renderer.domElement);
function render(){
renderer.render(scene,camera);
requestAnimationFrame(render);
if(analyser){
var arr = analyser.getFrequencyData(); // 获得频率数据
// 遍历组数据,设置每个mesh的 y 方向数值,颜色的 r 值
group.children.forEach((ele, index) => {
ele.scale.y = arr[index] / 80;
ele.material.color.r = arr[index] / 200;
});
}
}
var controls = new THREE.OrbitControls(camera,renderer.domElement);
render();
</script>
</body>
</html>