S&box Wiki

Revision Difference


<cat>Dev.Sound</cat> <title>Creating Sounds</title> #Creating a sound asset type # Creating a sound asset type Following a common file structure, we will create a `.sound` file called `example_pistol.shoot` inside your addon under `sounds/weapons/pistol/`. The original sound file (`.wav` or `.mp3`) will be called `pistol.shoot01.wav` inside the same folder. A single `.sound` asset can contain multiple different sounds which will be picked from randomly on every play. For looping sounds you will have to either place loop markers inside your sound file or compile the sound as a looping sound beforehand. To do this, you right-click the sound in the asset browser and select the appropriate option. This will only work with `.wav` and `.mp3` files. To create the actual `.sound` file, you open the [Inspector](https://wiki.facepunch.com/sbox/Inspector_-_Decals_SurfaceProperties_&_Sound) using the asset browser and switch the asset type to `sound`. <image src="https://i.imgur.com/53zP51P.png"/> Inside the inspector you can now select your sound file and set values such as Volume, Pitch, Random Volume, Random Pitch and audible distance. If your sound is supposed to be a screen sound, you will also need to select the `2D` option. <image src="https://i.imgur.com/72q2WLI.png"/> Saving this file via `Ctrl+s` or `File > Save` will result on a `.sound_c` asset for the metadata and a `.vsnd_c` file for the actual sound file, if you haven't compiled your sound already in a previous step. <image src="https://i.imgur.com/hI0my0i.png"/> Equivalent is just the addon name in this example, the path will differ per addon of course. #Playing the Sound from Your Code # Playing the Sound from Your Code To play the sound in-game, you should use one of the static methods from the `Sound` class, using the name of the `.sound` asset type without the extension: ```cs public override void Spawn() { // Plays the sound from an entity's position Sound.FromEntity("example_pistol.shoot", this); // Plays the sound from a position in the world Sound.FromWorld("example_pistol.shoot", new Vector3(0, 0, 0)); // Plays the sound from a position on your screen, useful for UI interactions // Make sure your .sound file has "2D" enabled Sound.FromScreen("example_pistol.shoot"); } ``` <note>To reliably play sounds from the server, it is recommended to send players <page>RPCs</page> instead and have them play the sound on their end.</note> <note>Sounds can be [predicted](Prediction) - if you're playing a sound in a predicted method such as Simulate you should make sure your logic is predictable, if it isn't you should appropriately wrap it with Prediction.Off otherwise you will hear nothing.</note>