如何在三.Js中停止声音

时间:2019-01-25 16:30:33

标签: javascript three.js

我正在使用Three Js应用程序,它使用位置音频,可以播放声音,但是然后我想与按钮进行交互以便停止它。但即使在此之前,stop方法也无法工作,并告诉我声音对象未定义。我需要在哪里告诉如何停止声音?

import * as THREE from 'three';
import { Howl, Howler } from 'howler';


class World {

    private scene: THREE.Scene;
    private camera: THREE.PerspectiveCamera;
    private controls: THREE.PointerLockControls;

    private listener: THREE.AudioListener;
    private zSound: THREE.PositionalAudio;
    private audioLoader: THREE.AudioLoader;

    /**
     * World constructor
     * @param {THREE.Scene} scene
     * @param {THREE.Camera} camera
     * @param {THREE.PointerLockControls}  controls
     */
    constructor(scene: THREE.Scene, camera: THREE.PerspectiveCamera, controls: THREE.PointerLockControls) {
        this.scene = scene;
        this.camera = camera;
        this.controls = controls;

        this.listener = new THREE.AudioListener();
        this.camera.add(this.listener);
        this.zSound = new THREE.PositionalAudio(this.listener);
        this.audioLoader = new THREE.AudioLoader();
    }

    init(){
        this.initAudio();
    }

    private initAudio() {
        const mySound = this.generator.getBiome().getSound();
        this.audioLoader.load(mySound, (buffer) => {
            this.zSound.setBuffer(buffer);

            this.zSound.setNodeSource(mySound);
            this.zSound.setRefDistance(2500);
            this.zSound.setLoop(true);
            this.zSound.setVolume(1);
            this.zSound.play();
        }, () => { }, () => { });


        // create an object for the sound to play from
        const sphere = new THREE.SphereGeometry(500, 32, 16);
        const material = new THREE.MeshPhongMaterial({ color: 0xff2200 });
        const mesh = new THREE.Mesh(sphere, material);
        this.scene.add(mesh);

        // finally add the sound to the mesh
        mesh.add(this.zSound);
        mesh.position.set(0, Terrain.SIZE_Y / 2, Terrain.SIZE_Z / 2);

    }

    // Will be called later, on click on a button on my interface
    private pauseAudio() {
        this.zSound.pause();
    }
}

export default World;

pauseAudio函数不会因为未定义而暂停我的音频。我只尝试致电.pause().stop()

0 个答案:

没有答案