babylonjs note 05 build a village (03) Adding Sound

64 阅读1分钟

Adding Sound

const sound = new BABYLON.Sound("name", "url to sound file", scene, null, { loop: true, autoplay: true });

To play a sound once we use

const sound = new BABYLON.Sound("sound", "url to sound file", scene,()=>{
  //Leave time for the sound file to load before playing it
  sound.play();
});

play the sound every 3 seconds

import { ArcRotateCamera, HemisphericLight, MeshBuilder, Scene, Sound, Vector3 } from "@babylonjs/core";
import { createApp } from "../utils";

const app = createApp((canvas, engine) => {
    const scene = new Scene(engine);

    const camera = new ArcRotateCamera("camera", -Math.PI/2, Math.PI/2.5, 15, Vector3.Zero(), scene);
    camera.attachControl(canvas, true);

    const light = new HemisphericLight('light', new Vector3(1, 1, 0), scene);

    // customize your scene here
    const ground = MeshBuilder.CreateGround("ground", {width: 10, height: 10}, scene);

    const box = MeshBuilder.CreateBox("box", {width: 1, height: 1, depth: 1}, scene);

    box.position.y = 0.5;

    const bounce = new Sound('bounce', '/assets/sound/bounce.wav', scene, () => {
        setInterval(() => {

            bounce.play();
        }, 3000)
    })

    return scene;
})

app.run();