声音提供器

声音定义生成

继承 SoundDefinitionsProvider 并实现 #registerSounds,即可为模组生成 sounds.json。实现后,必须将提供者添加到 DataGenerator。

SoundDefinitionsProvider 将声音名称和 SoundDefinition 写入 sounds.json;SOUND 引用 ogg 文件,EVENT 引用另一个声音定义。

原创说明图,依据 Forge 1.21.x 官方文档 绘制。

// 在模组事件总线上
@SubscribeEvent
public void gatherData(GatherDataEvent event) {
  event.getGenerator().addProvider(
    event.includeClient(), // 仅在生成客户端资源时运行
    output -> new MySoundDefinitionsProvider(output, MOD_ID, event.getExistingFileHelper())
  );
}

添加声音

通过 #add 指定声音名称和定义,即可生成声音定义。名称可来自 SoundEvent、ResourceLocation 或字符串。

警告:提供的声音名称始终假定使用传入提供者构造函数的模组 ID 作为命名空间,不会验证声音名称的命名空间!

SoundDefinition

使用 #definition 创建 SoundDefinition,其中包含定义声音实例的数据。定义提供以下方法:

方法 说明
with 添加选中该定义时可能播放的声音。
subtitle 设置定义的翻译键。
replace 为 true 时,移除其他 sounds.json 已为该定义指定的声音,而不是追加。

SoundDefinition$Sound

传给 SoundDefinition 的声音可通过 SoundDefinitionsProvider#sound 指定。这些方法接受声音引用以及可选的 SoundType。

声音类型 说明
SOUND 引用 assets/<namespace>/sounds/<path>.ogg 的声音。
EVENT 引用 sounds.json 定义的另一个声音名称。

每个由 SoundDefinitionsProvider#sound 创建的 Sound 可进一步配置加载和播放方式:

方法 说明
volume 设置音量倍率,必须大于 0。
pitch 设置音调倍率,必须大于 0。
weight 设置选中该声音时的播放概率权重。
stream 为 true 时从文件流式读取,而不是加载到内存。推荐用于背景音乐、唱片等长声音。
attenuationDistance 设置能听到该声音的方块距离。
preload 为 true 时,资源包加载后立即将声音加载到内存。
// 在 SoundDefinitionsProvider#registerSounds 中
this.add(EXAMPLE_SOUND_EVENT, definition()
  .subtitle("sound.examplemod.example_sound") // 设置翻译键
  .with(
    sound(ResourceLocation.fromNamespaceAndPath(MODID, "example_sound_1"))
      .weight(4) // 播放概率为 4 / 5 = 80%
      .volume(0.5), // 所有该声音的音量减半
    sound(ResourceLocation.fromNamespaceAndPath(MODID, "example_sound_2"))
      .stream() // 流式播放
  )
);
this.add(EXAMPLE_SOUND_EVENT_2, definition()
  .subtitle("sound.examplemod.example_sound")
  .with(
    sound(EXAMPLE_SOUND_EVENT.getLocation(), SoundType.EVENT) // 添加 EXAMPLE_SOUND_EVENT 的声音
      .pitch(0.5) // 所有该声音的音调减半
  )
);

原文:Sound Definition Generation。