Files
Storm DragonandClaude Opus 5.5 f164697cf6 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>
2026-11-28 15:03:48 -05:00

69 lines
3.0 KiB
Python

"""Babble: a burst of beeps for a character speaking, like characters talking in an old role-playing game.
There is about one beep for each syllable of the text, wandering over a
pentatonic scale. The same text always gives the same tune, so a line sounds
the same every time it is said.
"""
import math
import re
import zlib
import numpy as np
from .synth import rng_from, sampleRate
# Notes of a pentatonic scale, in semitones above the lowest, for the beeps to wander between.
scaleSteps = (0, 2, 4, 7, 9, 12)
waves = ("round", "buzzy", "warble", "reedy")
def count_syllables(text):
"""About how many syllables text has: groups of vowels, or one for each word if it has none
the pattern knows, as in a language that does not use Latin letters."""
groups = re.findall(r"[aeiouyàáâãäåèéêëìíîïòóôõöùúûüýÿæœ]+", text.lower())
return len(groups) if groups else len(text.split())
def beep_wave(wave, frequency, seconds):
"""One beep: wave is "round" (soft), "buzzy", "warble" (high and quavering) or "reedy" (bright chirp)."""
times = np.arange(int(sampleRate * seconds)) / sampleRate
if wave == "buzzy":
tone = np.tanh(4.0 * np.sin(2.0 * math.pi * frequency * times))
elif wave == "warble":
wobble = 1.0 + 0.05 * np.sin(2.0 * math.pi * 11.0 * times)
phases = np.cumsum(frequency * wobble) / sampleRate
tone = np.sin(2.0 * math.pi * phases) + 0.25 * np.sin(4.0 * math.pi * phases)
elif wave == "round":
tone = np.sin(2.0 * math.pi * frequency * times) + 0.3 * np.sin(4.0 * math.pi * frequency * times)
elif wave == "reedy":
sine = np.sin(2.0 * math.pi * frequency * times)
tone = 0.5 * np.sign(sine) + 0.5 * sine
else:
raise ValueError(f"Unknown babble wave {wave!r}; choose one of {', '.join(waves)}.")
envelope = np.minimum(1.0, times / 0.005) * np.minimum(1.0, (seconds - times) / 0.02)
return tone * envelope
def babble(text, base=600.0, beepSeconds=0.075, gapSeconds=0.035, wave="round", seedKey=None,
level=0.35, fewestBeeps=4, mostBeeps=12):
"""The burst of beeps before a character's line.
base is the lowest note in cycles a second; each beep lasts beepSeconds,
with gapSeconds of quiet after it. A line ending in "!" ends on the top
note. seedKey, if given, chooses the tune in place of the text, so two
characters can say the same line to different tunes.
"""
count = min(mostBeeps, max(fewestBeeps, count_syllables(text)))
rng = rng_from(zlib.crc32((text if seedKey is None else seedKey).encode("utf-8")))
gap = np.zeros(int(sampleRate * gapSeconds))
parts = []
for number in range(count):
step = rng.choice(scaleSteps)
if number == count - 1 and text.rstrip().endswith("!"):
# An exclamation ends on the top note.
step = scaleSteps[-1]
parts.append(beep_wave(wave, base * 2.0 ** (step / 12.0), beepSeconds))
parts.append(gap)
return level * np.concatenate(parts)