Generated sound effects, made from code instead of sound files
libstormgames.sfx makes sound effects with numpy and scipy, so a game can use them without shipping sound files, and every game that asks for the same sound with the same seed gets exactly the same samples. The sounds come from Grave Racer and match it sample for sample. The modules are synth (waves, filters, envelopes, loops), impacts, ui, rewards, materials, creatures, babble, vehicles, ambience and alerts. sfx.make_sound turns a sound into a pygame Sound for the mixer as it is set up, turning down only a sound that would go past full scale. sfx.add_sounds adds generated sounds by name, keeping any sound file of the same name. The menus' menu-move and menu-select sounds are generated when a game has no file for them. sfx and scipy are only imported then, so a game that ships both files, or never uses sfx, is not slowed down or made to need scipy. The tests check every sound against a stored fingerprint, so none can change by accident; tools/update-sfx-fingerprints.py remakes them after a deliberate change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
31e7472fd1
commit
f164697cf6
19 files changed
+2084
No files matched your search
+108
@@ -0,0 +1,108 @@
|
||||
"""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.
|
||||
|
||||
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.
|
||||
|
||||
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 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 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}
|
||||
Reference in new issue
Block a user