Howto:Play sound using Nasal script

From FlightGear wiki
Jump to navigation Jump to search

This works via property-fgcommands as per $FG_ROOT/Docs/README.commands:

var sound = {
    path  : DIRECTORYPATH, 
    file  : FILENAME, 
    volume: VOLUME,
    queue : "instant", # Other optional choices, do not include queue for default, or user defined queue name
};

fgcommand("play-audio-sample", props.Node.new(sound));

You'll want to adjust the capital variables with your own path/file name and volume, e.g. using a helper class :

var Sound = {
    # static
    default_path: getprop("/sim/fg-root") ~ '/Sounds', 
    
    # constructor
    new: func(filename, volume = 0.5, path = nil) {
        var m = Props.Node.new({
            path  : path or default_path,
            file  : filename,
            volume: volume,
        });

        return m;
    },
};

fgcommand("play-audio-sample", Sound.new(filename: 'blade_vortex.wav', volume: 0.8));


# You could put your sound file in the same folder and load it from there, 
# if you aren't using an existing sound:

var node = Sound.new(
    filename: 'mySoundFile.wav',
    volume: 0.8,
    path: getprop("/sim/fg-root") ~ '/Aircraft/Foo/Sounds',
);

fgcommand("play-audio-sample", node);

The same way one would do animations using Nasal:The current sound model is property-driven. You can create a new sound event (see the *-sound.xml files under Aircraft for examples) and drive it from a given set of properties. You can then set those properties from Nasal.

Adjust properties in Nasal (they may be "private" properties in your own subtree of the property list, say /tmp/<aircraft>) and let the sound configuration file act on those properties. (from flightgear-devel).

If your sounds are aircraft-specific, then the mechanism of putting it into the -sound.xml file is probably exactly what you want. Things like playing sounds from the UI are more problematic from the current interface.

Start with a single beep.wav with an XML definition like:

<sim>
...
<fx>
 ...
 <beep>
  <name>engstart</name>
  <path>Sounds/beep.wav</path>
  <property>/tmp/somewhere/beep</property>
 </beep>

Now you can trigger the beep by toggling the property from false to true. With a little work with settimer(), you can get it to beep with different patterns and frequencies, etc...

For additional information, you'll want to check out $FG_ROOT/Docs/README.xmlsound

Using cmdarg()

cmdarg() returns the listened-to property as props.Node object, so you can use it with all its methods (see $FG_ROOT/Nasal/props.nas), for example:

 print(cmdarg().getPath(), " has been changed to ", cmdarg().getValue())