Перейти к содержимому

Как писать файл sounds json

  • автор:

Sounds

This JSON defines sound events, and defines which sound files they play, the subtitle, etc. Sound events are identified with ResourceLocation s. sounds.json should be located at the root of a resource namespace ( assets/<namespace>/sounds.json ), and it defines sound events in that namespace ( assets/<namespace>/sounds.json defines sound events in the namespace namespace .).

A full specification is available on the vanilla wiki, but this example highlights the important parts:

Underneath the top-level object, each key corresponds to a sound event. Note that the namespace is not given, as it is taken from the namespace of the JSON itself. Each event specifies a localization key to be shown when subtitles are enabled. Finally, the actual sound files to be played are specified. Note that the value is an array; if multiple sound files are specified, the game will randomly choose one to play whenever the sound event is triggered.

The two examples represent two different ways to specify a sound file. The wiki has precise details, but generally, long sound files such as background music or music discs should use the second form, because the “stream” argument tells Minecraft to not load the entire sound file into memory but to stream it from disk. The second form can also specify the volume, pitch, and weight of a sound file.

In all cases, the path to a sound file for namespace namespace and path path is assets/<namespace>/sounds/<path>.ogg . Therefore mymod:open_chest_sound_file points to assets/mymod/sounds/open_chest_sound_file.ogg , and mymod:music/epic_music points to assets/mymod/sounds/music/epic_music.ogg .

A sounds.json can be data generated.

Creating Sound Events

In order to reference sounds on the server, a SoundEvent holding a corresponding entry in sounds.json must be created. This SoundEvent must then be registered. Normally, the location used to create a sound event should be set as it’s registry name.

The SoundEvent acts as a reference to the sound and is passed around to play them. If a mod has an API, it should expose its SoundEvent s in the API.

As long as a sound is registered within the sounds.json , it can still be referenced on the logical client regardless of whether there is a referencing SoundEvent .

Playing Sounds

Vanilla has lots of methods for playing sounds, and it is unclear which to use at times.

Note that each takes a SoundEvent , the ones registered above. Additionally, the terms “Server Behavior” and “Client Behavior” refer to the respective logical side.

Level

playSound(Player, BlockPos, SoundEvent, SoundSource, volume, pitch)

  • Simply forwards to overload (2), adding 0.5 to each coordinate of the BlockPos given.

playSound(Player, double x, double y, double z, SoundEvent, SoundSource, volume, pitch)

  • Client Behavior: If the passed in player is the client player, plays the sound event to the client player.
  • Server Behavior: Plays the sound event to everyone nearby except the passed in player. Player can be null .
  • Usage: The correspondence between the behaviors implies that these two methods are to be called from some player-initiated code that will be run on both logical sides at the same time: the logical client handles playing it to the user, and the logical server handles everyone else hearing it without re-playing it to the original user. They can also be used to play any sound in general at any position server-side by calling it on the logical server and passing in a null player, thus letting everyone hear it.

playLocalSound(double x, double y, double z, SoundEvent, SoundSource, volume, pitch, distanceDelay)

Sounds

This json should be located in the assets directory of a mod: src/main/resources/assets/<modid>/sounds.json . This file declares sound events and identifies which sound files they use.

A full specification is available on the vanilla wiki, but this example highlights the important parts:

Like the rest of the resource system, everything_should_be_in_snake_case.

Underneath the top-level object, each key corresponds to a sound event. Note that they are written in the sounds.json without the modid. Each event specifies its category, and a localization key to be shown when subtitles are enabled. Finally, the actual sound files to be played are specified. Note that the value is an array; if multiple sound files are specified then the game will randomly choose one to play whenever the sound event is triggered.

The two examples represent two different ways to specify a sound file. The wiki has precise details, but generally, long sound files such as BGM or music discs should use the second form, because the “stream” argument tells Minecraft to not load the entire sound file into memory but instead to stream it from disk. The second form can also specify the volume, pitch, and random weight of that sound file.

In all cases, the path to a sound file for domain domain and path path is assets/<domain>/sounds/<path>.ogg . Therefore mymod:open_chest_sound_file points to assets/mymod/sounds/open_chest_sound_file.ogg , and mymod:music/epic_music points to assets/mymod/sounds/music/epic_music.ogg .

Creating Sound Events

In order to actually be able to play sounds, a SoundEvent corresponding to an entry in sounds.json must be created. This SoundEvent must then be registered. Normally, the location used to create a sound event should be set as it’s registry name.

Creating a SoundEvent :

The SoundEvent acts as a reference to the sound, and is passed around to actually play sounds. Therefore, the SoundEvent should be stored somewhere. If a mod has an API, it should expose its SoundEvent s in the API.

Playing Sounds

Vanilla has lots of methods for playing sounds, and it’s unclear which to use at times.

This information was gathered by looking at these various methods, analyzing their usage and categorizing them accordingly. It is up-to-date as of Forge 1907, please let someone know if it is out of date!

Note that each takes a SoundEvent , the ones registered above. Additionally, the terms “Server Behavior” and “Client Behavior” refer to the respective logical side.

World

playSound(EntityPlayer, BlockPos, SoundEvent, SoundCategory, volume, pitch)

  • Simply forwards to overload (2), adding 0.5 to each coordinate of the BlockPos given.

playSound(EntityPlayer, double x, double y, double z, SoundEvent, SoundCategory, volume, pitch)

  • Client Behavior: If the passed in player is the client player, plays the sound event to the client player.
  • Server Behavior: Plays the sound event to everyone nearby except the passed in player. Player can be null .
  • Usage: The correspondence between the behaviors implies that these two methods are to be called from some player-initiated code that will be run on both logical sides at the same time — the logical client handles playing it to the user and the logical server handles everyone else hearing it without re-playing it to the original user. They can also be used to play any sound in general at any position server-side by calling it on the logical server and passing in a null player, thus letting everyone hear it.

playSound(double x, double y, double z, SoundEvent, SoundCategory, volume, pitch, distanceDelay)

sounds.json

sounds.json (sound_definitions.json в Bedrock Edition) — файл, который используется звуковой системой в пакетах ресурсов и который говорит, какой звуковой файл нужно проигрывать, когда звуковое событие вызывается одним или несколькими игровыми событиями. Этот файл находится в assets/minecraft в пакетах ресурсов, стандартный файл находится в .minecraft/assets/objects ( minecraft/assets/objects для Mac, . /assets/resource_packs/vanilla/sounds для Bedrock Edition). Размер файла и его хешированное имя может быть найдено в .minecraft/assets/indexes/<версия>.json .

Содержание

Структура файла [ ]

Этот файл хранится в формате JSON, но здесь представлен в формате NBT.

  • Корневой объект
    • Звуковое событие. Название этого объекта — это название звукового события, которое сделано по образцу пути к звуковому файлу (как «random.break»). Все стандартные звуки находятся в таблице ниже.
      • category : Категория, к которой относится этот звук. Возможные названия категорий:
        ambient (окружение), weather (погода), player (игроки), neutral (дружелюбные существа), hostile (враждебные существа), block (блоки), record (музыкальные блоки), music (музыка), master (общее) и voice (голос/речь).
        Эта строка даёт звуковой системе понять к какой категории относится то или иное звуковое событие, так что громкость может быть отрегулирована на основании того, какие параметры звука устанавливаются для каждой категории.
      • replace : true/false. Используется только в ресурспаках. Если true, то звук, записанный в sounds, заменит звуки, записанные в стандартном файле sounds.json для этого звукового события. Если false, то записанные звуки будут добавлены в стандартный список звуков. Необязательно. Если нет, по стандарту устанавливается значение false. В версиях до 1.7.6-pre1 эта строка проигнорирована из-за ошибки.
      • sounds : Звуковые файлы, которые использует это звуковое событие. Один из звуков случайно выбирается для проигрывания когда звуковое событие запущено. Изменяемо.
        • Путь до звукового файла из папки «sounds». Использует «/».
        • Звуковой файл. Этот объект используется только в случае, если звуку нужны дополнительные строки.
          • name : Путь до этого звукового файла из папки «sounds». Использует «/» вместо «\». Также может быть названием другого звукового события. Для того чтобы громкость звука имела значение, требуется чтобы звуковой файл имел один канал (моно).
          • volume : Громкость с которой будет воспроизведён этот звук. Значение от 0.0 до 1.0. Если нет, по стандарту 1.0.
          • pitch : Изменяет высоту звука. Если нет, по стандарту 1.0, но могут быть выбраны значения выше и ниже.
          • weight : Шанс, с которым этот звук будет выбран для воспроизведения, если произошло звуковое событие. По умолчанию 1. Пример: при значении 2 звук будет воспроизводится в 2 раза чаще. Допускаются только целые значения.
          • stream : true/false. Если true, то этот звук будет передаваться прямо из файла. Рекомендуется устанавливать значение true для всех длинных звуков, чтобы предотвратить падение производительности. Используется для всех звуков в категориях «music» и «record» (кроме звуков нотного блока), так как почти все звуки этих категорий длятся более минуты. Необязательно. По умолчанию false.
          • type : Возможны два значения: «sound» и «event»; «sound» воспроизводится с именем файла, в то время как «event» воспроизводится с уже определённым событием. Если значение не установлено, устанавливается «sound».

          Пример файла sounds.json может быть найден здесь.

          Звуковые события [ ]

          Звуковое событие связано с одним или с несколькими игровыми событиями. Два события могут иметь один и тот же звуковой файл, но соответствовать различным внутриигровым событиям и/или относятся к разным категориям звука. Несколько доступных звуковых событий не включены в sounds.json, в то время как некоторые другие не имеют в игре события, связанные с ними. Любое звуковое событие, для которого нет внутриигрового события могут быть воспроизведены только с помощью /playsound .

          Cписок звуковых событий можно посмотреть в этом списке. Все звуковые события, звуки, которыми они пользуются, субтитрами, которые показываются на экране во время этого события, перечислены ниже.

          How to add custom sounds to resource pack

          Adding sounds to a Minecraft resource pack isn’t that complicated but these are some rookie mistakes you can do and should avoid.

          Step 1: Add your own sounds.json

          To avoid having to merge sounds.json files you should create your own namespace.

          In this example we will create one that’s called “yoursound”, let’s start with creating this file:

          Here’s we’re telling the game that we have 2 new sounds that are called “example.sound.name_1” and “example.sound.name_2”.

          Step 2: Add your sound files

          In step 1 we defined 2 new sounds but we need to add the actual sound files, here are the paths:

          You can also just put these in your namespace folder and not in the minecraft folder by defining the namespace in the file path.

          Step 3: Test your new sounds

          Type this command in-game:

          If you can hear the sound, you’ve done it all correct and you’re done!

          Step 4: More advanced settings

          In your sounds.json you can define a ton of settings in each new defined sound, for example we could add a subtitle that shows to the player when they hear the sound:

          Now when the player hears example.sound.name_1 they will also get a subtitle above their action bar saying “hello”.

          There are only 3 main settings which are:

          • replace – if this should replace the sounds in default sounds.json
          • subtitle – shows subtitle to the player
          • sounds – The sound files this sound event uses. One of the listed sounds is randomly selected to play when this sound event is triggered. Optional.

          But within the sounds setting you can also add a bunch of settings:

          • name – the url of the sound file excluding the .ogg extension.
          • volume – the volume betweenn 0.0 and 1.0, default is 1.0
          • pitch – plays the sound at specific pitch, if not defined it will always be 1.0
          • weight – the chance that this sound is selected when multiple sounds are defined, default is 1
          • stream (true/false) – True if this sound should be streamed directly from the file, set to true if the sound is longer then a few seconds to avoid lag. This is typically used for all the sounds in music and record categories.
          • attenuation_distance – Sound reduction rate based on distance, typically used by beacons, portals and conduits. Default is 16.
          • preload (true/false) – True if the sound should be loaded when the resource pack is loaded instead of when the sound plays to the user. Defaults to false.
          • type (sound or event) – Sound causes the value of “name” to be interpreted as the name of the file path, while event causes the value of “name” to be read as a predefined event in the game. Set to “sound” by default.

          Let’s add a more advanced example to our sounds.json

          Now we’ve added a third custom sound that does these things:

          • Plays 1 out of the 3 .ogg files specified randomly.
          • Defaults as a hostile mob sound.
          • Each of the .ogg files has it’s own defined volume and pitch.
          • The third sound/ogg is 3 times more likely to be played thanks to it’s weight.

          If you need more guidance you can read the minecraft wiki sounds.json article, or read more MC Models tutorials.

          MC Models is a quality controlled marketplace for primarily 3d models! You can read more about us here.

          Mcmodels.net is in no way connected or associated with Minecraft, Mojang or any other game company. Our products are made to be used within a wide range of programs and games. Not specifically Minecraft. Read more in our terms.

          Any questions or business requests can be sent to [email protected] or discuss on our Discord.

          Greetings Adventurer!
          By accepting our cookies you will help all the creators you like on this website and allow you to find exactly what you want by analyzing what you do. We never share your data with third parties (except that we use third parties for specific functionalities, like embedded Youtube videos). By clicking “Accept all cookies”, you consent to the use of all the cookies.

          You can go back and change these settings from our Privacy Policy page that you find in the footer on the whole website.

          Clicking «Reject all cookies» will make you lose out on website features. We instead recommend that you use Cookie Settings to turn off specific cookie types.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Школа онлайн с государственным аттестатом