S&box Wiki

Revision Difference

Creating_Sounds#544241

<cat>Dev.Sound</cat>⤶ <title>Creating Sounds</title>⤶ ⤶ In order to play a sound in your game, you must first import it as an asset and compile it. This process results in a `.vsnd` asset for the actual sound, and a `.sound` asset for metadata.⤶ ⤶ In this example, we will create a sound named `explode`.⤶ ⤶ ⤶ #Creating and Compiling the .vsnd asset⤶ ⤶ This is fairly easy to do: all you need is to drop your sound file into the appropraite folder in your addon: `sbox/addons/myAddon/sounds/`. Supported formats are `.wav` and `.mp3`; you can convert other formats with a tool like [Audacity](https://www.audacityteam.org/)⤶ ⤶ Once the file is placed, open the asset browser and search for the sound name. You'll notice it already shows up with a `.vsnd` suffix.⤶ ⤶ The next step is to compile it. To do so, simply right click it in the asset browser and choose whether to compile it as a looping sound or not.⤶ ⤶ <upload src="3db07/8d944929fa6b471.png" size="13062" name="compiling_a_sound.png" />⤶ ⤶ This will create a `.vsnd_c` file next to your sound file.⤶ ⤶ #Creating the Metadata⤶ ⤶ The next step is to create a `.sound` file with some metadata for your sound. To do this, right click the `.vsnd` file again and choose `Create Sound for 'sound_name'`.⤶ ⤶ This will open the inspector with the file name already set and a bunch of values you can modify to tweak how your sound behaves in the game. Once done, click `File` -> `Save` and save it near your compiled sound file.⤶ ⤶ <upload src="3db07/8d944931fd71c29.png" size="14683" name="sbox-dev_8pYzdWOBUL.png" />⤶ ⤶ #Playing the Sound from Your Code⤶ ⤶ To play the sound in-game, you should use one of the static methods from the `Sound` class:⤶ ⤶ ```cs⤶ public override void Spawn()⤶ {⤶ // Plays the sound from an entity and follows it⤶ Sound.FromEntity("explode", this);⤶ ⤶ // Plays the sound from a position in the world⤶ Sound.FromWorld("explode", new Vector(0, 0, 0));⤶ ⤶ // Plays the sound from a position on your screen, useful for UI interactions⤶ Sound.FromScreen("explode", 0.5f, 0.5f);⤶ }⤶ ```⤶ ⤶ <warning>Only use the sound name when referring to it in your code; don't add the path to it or the `.vsnd` suffix, otherwise it won't play at all!</warning>⤶ ⤶ <note>While playing the sound in the server realm usually works, there are some situations where it fails. In these cases, it may be necessary to play the sound in the client realm instead. You can do so with <page>RPCs</page>.</note>