Audio parameter

It is possible to pass in an audio asset to an actor as a parameter in the editor. This makes it possible to easily change the sound that an actor plays from the editor.

The code below illustrates how to define an audio parameter.

  1. First define the parameter. Read more about parameters in Actor parameters

  2. Inject the View controller to access the global audio listener.

  3. Create the instance of a new sound instance to be able to play the audio clip.

  4. Set the sound buffer using the value of the audio parameter in the onInit function. At this point the parameters are set. Read more about actors lifecycle functions in Actor lifecycle

  5. Finally, we define a function that can be called on the actor to play the sound which could be called whenever the sound should play.

import { Actor, BaseActor, ViewController, inject } from "@hology/core/gameplay";
import { Parameter } from "@hology/core/shader/parameter";
import * as THREE from 'three'

@Actor()
class ExampleActor extends BaseActor {
  @Parameter() audio: AudioBuffer;
  private view = inject(ViewController)
  private sound = new THREE.Audio(this.view.audioListener)

  onInit() {
    this.sound.setBuffer(this.audio)
  }
  
  playSound() {
    this.sound.play()
  }

}

export default ExampleActor

Last updated