Forum Discussion

InaCentaur's avatar
8 months ago
Solved

How to play a sound fx by script? AudioGizmo does not show in Gizmos? Only Sound Recorder

How to play a sound fx by script?

 

Trying to have a machine play a sound effect and after going down some attempts to getComponent Sound, it seems that you need a special AudioGizmo to do this? 

I don't see an AudioGizmo in my gizmos? 

 

 

  • AudioGizmo is just the name of the TypeScript class that represents the sound recorder gizmo and any other audio related gizmos in Horizon.

5 Replies

  • AudioGizmo is just the name of the TypeScript class that represents the sound recorder gizmo and any other audio related gizmos in Horizon.

    • InaCentaur's avatar
      InaCentaur
      Member

      got it, so AudioGizmo is not an entity found in the Gizmos menu in Desktop Editor? 

      • OverTheEdge's avatar
        OverTheEdge
        Member

        You drag the audio clip straight from your assets into the scene and then you attach your script to that in order to control the AudioGizmo.

  • You can play a sound gizmo in TypeScript like this:

    this.entity.as(AudioGizmo).play();

    That line tells the entity to cast itself as an AudioGizmo and then run the play() method.

    If you want a step-by-step walkthrough, i broke it down in this video:  https://youtu.be/nFMWiJHWPnY

  • Here is another common use case: 
    You attach this script to a trigger gizmo in your scene and drag your audioGizmo from the Hierarchy into the AudioSource slot in the Properties panel. 
    When the player enters the trigger, the SFX plays.

    You can also use a cooldown to prevent the audio from triggering too frequently. The cooldown is 2000 milliseconds by default. 

    import * as hz from "horizon/core";
    
    class AudioOnTrigger extends hz.Component<typeof AudioOnTrigger> {
      static propsDefinition = {
        // Assign an entity that has an Audio gizmo
        audioSource: { type: hz.PropTypes.Entity },
        // Optional: prevent rapid re-triggers (ms)
        cooldownMs: { type: hz.PropTypes.Number, default: 2000 },
      };
    
      private lastTriggerTime = 0;
    
      start(): void {
        this.connectCodeBlockEvent(
          this.entity,
          hz.CodeBlockEvents.OnPlayerEnterTrigger,
          (_player: hz.Player) => {
            const now = Date.now();
            if (now - this.lastTriggerTime < (this.props.cooldownMs ?? 0)) return; // cooldown
            this.lastTriggerTime = now;
    
            const src = this.props.audioSource;
            if (!src) { console.warn("[AudioOnTrigger] Assign audioSource."); return; }
    
            const audio = src.as(hz.AudioGizmo);
            if (!audio) { console.warn("[AudioOnTrigger] audioSource has no Audio gizmo."); return; }
    
            try { audio.play(); } catch (e) { console.warn("[AudioOnTrigger] play failed:", e); }
          }
        );
      }
    }
    
    hz.Component.register(AudioOnTrigger);