デモ:https://mo49.github.io/qiita/20160908/audio.html
まずデータを用意
SOUNDBOX_DATA
const SOUNDBOX_DATA = [
{
imgSrc: './img/rad.png',
audioSrc: './sound/rad.mp3',
pos: {
x:0,
y:15,
z:0
}
},
{
imgSrc: './img/utada.jpg',
audioSrc: './sound/utada.mp3',
pos: {
x:0,
y:15,
z:100
}
},
{
imgSrc: './img/yonezu.jpg',
audioSrc: './sound/yonezu.mp3',
pos: {
x:0,
y:15,
z:-100
}
}
]
続いて、音源を置く箱を作成
createSoundBox
createSoundBox(src, pos) {
const geom = new THREE.BoxGeometry(30,30,30);
const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load(src);
texture.minFilter = texture.magFilter = THREE.LinearFilter;
const mat = new THREE.MeshBasicMaterial({
color:0xffffff,
side:THREE.DoubleSide,
map:texture
})
const mesh = new THREE.Mesh(geom, mat);
mesh.position.set(pos.x, pos.y, pos.z);
return mesh;
}
作成した箱に音源を紐付ける
setAudio
setAudio(src, mesh, refDis, rolloff, volume) {
const listener = new THREE.AudioListener();
this.camera.add(listener);
const sound = new THREE.PositionalAudio(listener);
const audioLoader = new THREE.AudioLoader();
refDis = refDis || 10; // 音量が下がり始める距離
rolloff = rolloff || 2; // 音源から遠ざかった時にどのくらいすぐに音量が下がるか
volume = volume || 1;
audioLoader.load(src, (buffer) => {
sound.autoplay = true;
sound.setBuffer(buffer);
sound.setRefDistance(refDis);
sound.setLoop(true);
sound.setRolloffFactor(rolloff);
sound.setVolume(volume);
mesh.add(sound);
})
}
シーンに音源を追加
for (let data of SOUNDBOX_DATA) {
const mesh = this.createSoundBox(data.imgSrc, data.pos);
this.scene.add(mesh);
this.setAudio(data.audioSrc, mesh);
}