跳到主要内容

25自定义声音

自定义声音

新建一个自定义声音类:

public class ModSounds {
public static final SoundEvent METAL_DETECTOR_FOUND_ORE = registerSoundEvent("metal_detector_found_ore");

public static final SoundEvent SOUND_BLOCK_BREAK = registerSoundEvent("sound_block_break");
public static final SoundEvent SOUND_BLOCK_STEP = registerSoundEvent("sound_block_step");
public static final SoundEvent SOUND_BLOCK_PLACE = registerSoundEvent("sound_block_place");
public static final SoundEvent SOUND_BLOCK_HIT = registerSoundEvent("sound_block_hit");
public static final SoundEvent SOUND_BLOCK_FALL = registerSoundEvent("sound_block_fall");


public static final BlockSoundGroup SOUND_BLOCK_SOUNDS = new BlockSoundGroup(1f, 1f,
ModSounds.SOUND_BLOCK_BREAK, ModSounds.SOUND_BLOCK_STEP, ModSounds.SOUND_BLOCK_PLACE,
ModSounds.SOUND_BLOCK_HIT, ModSounds.SOUND_BLOCK_FALL);


private static SoundEvent registerSoundEvent(String name) {
Identifier id = new Identifier(TutorialMod.MOD_ID, name);
return Registry.register(Registries.SOUND_EVENT, id, SoundEvent.of(id));
}

public static void registerSounds() {
TutorialMod.LOGGER.info("Registering Sounds for " + TutorialMod.MOD_ID);
}
}

在主类TutorialMod中注册:

        ModSounds.registerSounds();

修改金属探测器MetalDetectorItem中的声音:

context.getWorld().playSound(null, positionClicked, ModSounds.METAL_DETECTOR_FOUND_ORE,
SoundCategory.BLOCKS, 1f, 1f);

修改ModBlocks中声音块的声音:

public static final Block SOUND_BLOCK = registerBlock("sound_block",
new SoundBlock(FabricBlockSettings.copyOf(Blocks.IRON_BLOCK).sounds(ModSounds.SOUND_BLOCK_SOUNDS)));

resources/assets/tutorialmod中新建一个sound.json文件

{
"metal_detector_found_ore": {
"subtitle": "sounds.tutorialmod.metal_detector_found_ore",
"sounds": [
"tutorialmod:metal_detector_found_ore"
]
},
"sound_block_break": {
"subtitle": "tutorialmod.sound_block_break",
"sounds": [
"tutorialmod:sound_block_break"
]
},
"sound_block_step": {
"subtitle": "tutorialmod.sound_block_step",
"sounds": [
"tutorialmod:sound_block_step"
]
},
"sound_block_place": {
"subtitle": "tutorialmod.sound_block_place",
"sounds": [
"tutorialmod:sound_block_place"
]
},
"sound_block_hit": {
"subtitle": "tutorialmod.sound_block_hit",
"sounds": [
"tutorialmod:sound_block_hit"
]
},
"sound_block_fall": {
"subtitle": "tutorialmod.sound_block_fall",
"sounds": [
"tutorialmod:sound_block_fall"
]
}
}

具体的声音放到sounds文件夹中,格式为ogg

效果

当使用金属探测器发现矿物时,会发出声音