Files
Storm DragonandClaude Opus 5.5 962f695226 Generated footsteps on grass, leaves, gravel, snow, wood and concrete
movement.footstep(surface, seed) makes one footstep, and each seed gives a
slightly different step, so a game can register several and play them at
random. Every surface except grass is the heel landing and then the toe:

- leaves: bright crisp crackles that spread out, over a soft rustle.
- gravel: dozens of small stones knocking under the heel and toe, over a
  low grind.
- snow: a muffled crunch that gets denser as the foot packs it down.
- wood: a hollow knock with the boards ringing, and on some steps a creak.
- concrete: a hard heel and a scuff of grit on the toe.

Grass is one swish instead, with blades flicking off the shoe, as a foot
swings through. The loose surfaces are built from many tiny filtered
bursts of noise, and how many there are, how bright, and how they spread
over the step is what tells stones from snow or leaves. Each surface was
tuned by ear against how real footsteps sound.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 22:00:22 -05:00

142 lines
6.1 KiB
Python

"""Generated sound effects for Storm Games.
Every sound is made from code, so a game can use one without shipping a sound
file, and every game that asks for the same sound gets the same sound: the
same seed always gives the same samples.
from libstormgames import sfx
from libstormgames.sfx import impacts
sounds = initialize_gui("My Game")
sfx.add_sounds(sounds, {"thunder": impacts.thunder(), "explosion": impacts.explosion(seed=2)})
sounds["thunder"].play()
Generators return numpy arrays of float samples at sfx.synth.sampleRate, and
make_sound turns one into a pygame Sound for the mixer as it is set up, and
make_music turns one into background music for play_bgm.
The modules:
- synth: building blocks (waves, filters, envelopes, assembly, loops).
- impacts: thunder, explosions, booms, thuds and shattering.
- ui: beeps, menu sounds, confirmations and on/off sweeps.
- rewards: sparkles, chimes, charges, beacons and items spilling.
- materials: snaps, clanks, rattles, knocks, squelches, splashes and a wooden launch.
- creatures: a horse's whinny and a witch's cackle.
- babble: beeps for a character speaking a line.
- vehicles: skids, and live voices for road surfaces and wind.
- ambience: loops such as bubbling, dripping and repeating patterns.
- alerts: live voices for warnings, falling screams, whistles and chattering.
- movement: a jump, and footsteps on grass, leaves, gravel, snow, wood and concrete.
- music: looping background music pieces, each loaded only when a game asks for it.
Generated sounds need numpy and scipy. Nothing else in libstormgames imports
this package, so a game that does not use it does not need scipy.
"""
import io
import wave
import numpy as np
import pygame
from .synth import sampleRate
def make_sound(sound, volume=1.0):
"""A pygame Sound from a generated sound, for the mixer as it is set up.
sound is a mono array or a (frames, 2) stereo array at sampleRate. It is
resampled if the mixer runs at another rate, and a sound that would go past
full scale is turned down to just fit, so nothing clips; every other sound
keeps its own level, so sounds keep their loudness relative to each other.
The mixer must already be set up, as initialize_gui and Sound do.
"""
mixerSetup = pygame.mixer.get_init()
if mixerSetup is None:
raise RuntimeError("Set up the pygame mixer before making generated sounds.")
frequency, sampleFormat, channels = mixerSetup
samples = np.asarray(sound, dtype=np.float64) * volume
if samples.ndim == 1:
samples = samples[:, None]
if frequency != sampleRate and len(samples) > 1:
frameCount = max(1, int(round(len(samples) * frequency / sampleRate)))
sourceTimes = np.arange(len(samples)) / sampleRate
targetTimes = np.arange(frameCount) / frequency
samples = np.column_stack([np.interp(targetTimes, sourceTimes, samples[:, index])
for index in range(samples.shape[1])])
if channels == 1:
samples = samples.mean(axis=1, keepdims=True)
elif samples.shape[1] == 1:
samples = np.repeat(samples, channels, axis=1)
elif samples.shape[1] != channels:
raise ValueError(f"A stereo sound cannot play on a mixer with {channels} channels.")
peak = np.abs(samples).max() if samples.size else 0.0
if peak > 1.0:
samples = samples / peak
if abs(sampleFormat) == 8:
if sampleFormat > 0:
data = np.round(samples * 127.0 + 128.0).astype(np.uint8)
else:
data = np.round(samples * 127.0).astype(np.int8)
elif abs(sampleFormat) == 16:
if sampleFormat > 0:
data = np.round(samples * 32767.0 + 32768.0).astype(np.uint16)
else:
data = np.round(samples * 32767.0).astype(np.int16)
elif abs(sampleFormat) == 32:
data = samples.astype(np.float32)
else:
raise ValueError(f"Generated sounds do not support the mixer's sample format {sampleFormat}.")
if channels == 1:
data = data[:, 0]
return pygame.sndarray.make_sound(np.ascontiguousarray(data))
def make_music(sound, volume=1.0):
"""Background music from a generated sound: the bytes of a WAV file, for play_bgm.
sound is a mono array or a (frames, 2) stereo array at sampleRate, such as
a piece from libstormgames.sfx.music. play_bgm plays the bytes just as it
plays a music file, so the music loops, pauses for dialogue, fades and
follows the music volume the same way. Like make_sound, it turns down only
music that would go past full scale. It needs no mixer, so music can be
made before the game starts; make it once and keep the bytes, since
making a piece takes a second or so.
"""
samples = np.asarray(sound, dtype=np.float64) * volume
if samples.ndim == 1:
samples = samples[:, None]
peak = np.abs(samples).max() if samples.size else 0.0
if peak > 1.0:
samples = samples / peak
data = np.ascontiguousarray(np.round(samples * 32767.0).astype("<i2"))
output = io.BytesIO()
with wave.open(output, "wb") as wavFile:
wavFile.setnchannels(samples.shape[1])
wavFile.setsampwidth(2)
wavFile.setframerate(sampleRate)
wavFile.writeframes(data.tobytes())
return output.getvalue()
def add_sounds(sounds, generated, replace=False):
"""Add generated sounds to a game's sounds by name; a sound already there, such as from a file, is kept.
sounds is the dictionary from initialize_gui or a Sound's sounds;
generated maps names to generated arrays, or to functions that make them,
which are only called for names not already there. Pass replace=True to
put the generated sound in place of one loaded from a file.
"""
for name, sound in generated.items():
if name in sounds and not replace:
continue
sounds[name] = make_sound(sound() if callable(sound) else sound)
return sounds
def default_sounds():
"""The generated sounds the library itself uses when a game has no file for them."""
from . import ui
return {"menu-move": ui.menu_move, "menu-select": ui.confirm_chime}