200 words
1 minutes
07 注册和播放声音
07 注册和播放声音
public class ModSounds {
public static DeferredRegister<SoundEvent> SOUNDS = DeferredRegister.create(net.minecraft.core.registries.Registries.SOUND_EVENT, NeoMafishMod.MODID);
public static final DeferredHolder<SoundEvent,SoundEvent> METAL_DETECTOR_FOUND_ORE = registerSoundEvent("metal_detector_found_ore");
public static final DeferredHolder<SoundEvent,SoundEvent> SOUND_BLOCK_BREAK = registerSoundEvent("sound_block_break");
public static DeferredHolder<SoundEvent,SoundEvent> registerSoundEvent(String name){
return SOUNDS.register(name,()-> SoundEvent.createVariableRangeEvent(ResourceLocation.fromNamespaceAndPath(NeoMafishMod.MODID,name)));
}
public static void register(IEventBus eventBus){
SOUNDS.register(eventBus);
}
}
注册到总线
// The value here should match an entry in the META-INF/neoforge.mods.toml file
@Mod(NeoMafishMod.MODID)
public class NeoMafishMod
{
// Define mod id in a common place for everything to reference
public static final String MODID = "neomafishmod";
private static final Logger LOGGER = LogUtils.getLogger();
public NeoMafishMod(IEventBus modEventBus, ModContainer modContainer)
{
ModSounds.register(modEventBus);
}
}
{ // resources/assets/neomafishmod/sounds.json
"metal_detector_found_ore": {
"subtitle": "sounds.mafishmod.metal_detector_found_ore",
"sounds": [
"neomafishmod:metal_detector_found_ore"
]
},
"sound_block_break": {
"subtitle": "mafishmod.sound_block_break",
"sounds": [
"neomafishmod:sound_block_break"
]
},
}
resources/assets/neomafishmod/sounds/metal_detector_found_ore.ogg
播放声音
// 添加了一个方块右键播发声音。
public class SoundBlock extends Block {
public SoundBlock(Properties properties) {
super(properties);
}
@Override
protected ItemInteractionResult useItemOn(ItemStack stack, BlockState state, Level level, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hitResult) {
level.playSound(
player,
pos,
SoundEvents.NOTE_BLOCK_XYLOPHONE.value(),
SoundSource.BLOCKS,
1.0f, // volume
1.0f// pitch
);
return super.useItemOn(stack, state, level, pos, player, hand, hitResult);
}
}