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:
Storm DragonandClaude Opus 5.5 committed 2026-11-28 15:03:48 -05:00
1 parent 31e7472fd1
commit f164697cf6
19 files changed
+2084

No files matched your search

+70
View File
@@ -27,6 +27,7 @@ A Python library to make creating audio games easier.
- setproctitle>=1.2.0
- numpy>=1.19.0
- wxpython
- scipy (only for generated sounds, `libstormgames.sfx`)
#### Speech Providers (one required)
@@ -129,6 +130,7 @@ The library is organized into modules, each with a specific focus:
- **display**: Text display and GUI functionality
- **menu**: Menu systems
- **utils**: Utility functions and Game class
- **sfx**: Generated sound effects, made from code instead of sound files
## Core Classes
@@ -584,6 +586,74 @@ sg.cut_scene(sounds, "intro_speech")
channel = sg.play_random_falling(sounds, "rock", player_x=5, object_x=8, start_y=10, currentY=5)
```
### Generated Sounds
`libstormgames.sfx` makes sound effects from code, so a game can use them
without shipping sound files. The same sound with the same seed is always the
same, so every game, or every part of a large game, that uses `thunder` hears
the same thunder.
```python
import libstormgames as sg
from libstormgames import sfx
from libstormgames.sfx import impacts, ui, rewards
sounds = sg.initialize_gui("My Game")
# Add generated sounds by name. A sound file with the same name, such as
# sounds/thunder.ogg, is kept instead, so any generated sound can be replaced.
sfx.add_sounds(sounds, {
"thunder": impacts.thunder,
"thunder2": lambda: impacts.thunder(seed=2), # a variant
"collect": rewards.sparkle,
"beep": lambda: ui.beep(880, 0.15),
})
sounds["thunder"].play()
```
Every generator takes a `seed`: the default always gives the same sound, a
different number a variant, and `None` a new variant each time.
Generators return numpy arrays at 44,100 samples a second, and
`sfx.make_sound(array)` turns one into a pygame Sound for the mixer as it is
set up. A sound that would go past full scale is turned down just enough to
fit; every other sound keeps its level.
The modules:
- `impacts`: `thunder`, `explosion`, `heavy_boom`, `thud`, `shatter`
- `ui`: `beep`, `fanfare`, `toggle_sweep`, `denied_click`, `menu_move`, `confirm_chime`
- `rewards`: `sparkle`, `bell_chime`, `beacon_blip`, `power_charge`, `bonus_run`, `rising_sweep`, `item_spill`
- `materials`: `finger_snap`, `metal_clank`, `rattle`, `hollow_knock`, `squelch`, `wet_splat`, `thick_splash`,
`wooden_launch`
- `creatures`: `horse_whinny`, `witch_cackle`
- `babble`: `babble(text, ...)`, beeps for a character speaking a line; the same line always gets the same tune
- `vehicles`: `whoosh`, `skid_spin`, `tyre_scrub_turn`, and the live voices `TyreSquealVoice`, `GravelVoice`,
`RumbleStripVoice`, `WindRushVoice`
- `ambience`: looping voices `BubblingVoice`, `DrippingVoice`, `GurglingVoice`, `BouncingSpringVoice`,
`RatchetVoice`, and `PatternVoice` for any repeating pattern of sounds
- `alerts`: live voices `ProximityWarningVoice`, `FallingScreamVoice`, `WhistlingFallVoice`, `ChatteringVoice`
- `synth`: the building blocks, for making new sounds
Voices make sound a block at a time, for a game with its own live mixer. To
use one as an ordinary looping sound, record it and make it loop:
```python
from libstormgames.sfx import ambience, synth
bubbling = synth.make_loop(synth.render_voice(ambience.BubblingVoice(), 4.0, fadeSeconds=0))
sfx.add_sounds(sounds, {"cauldron": bubbling})
sg.obj_play(sounds, "cauldron", playerPos, cauldronPos)
```
The menus use `menu-move` and `menu-select` sounds. A game with no files for
them gets generated ones (`ui.menu_move` and `ui.confirm_chime`), so they only
need a file to replace them.
The tests check every generated sound against a stored fingerprint, so a sound
cannot change by accident. To change one on purpose, listen to it, then run
`python tools/update-sfx-fingerprints.py`.
### Utility Functions
```python
+3
View File
@@ -89,6 +89,9 @@ def initialize_gui(gameTitle):
Speech.get_instance().speak("Error loading sounds.", False)
soundData = {}
from .sound import add_default_sounds
add_default_sounds(soundData)
# Play intro sound if available, optionally with visual logo
from .sound import cut_scene
if 'game-intro' in soundData:
+1
View File
@@ -4,4 +4,5 @@ requests>=2.25.0
pyxdg>=0.27
setproctitle>=1.2.0
numpy>=1.19.0
scipy
accessible-output2>=0.14
+108
View File
@@ -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}
+142
View File
@@ -0,0 +1,142 @@
"""Live alert voices that follow the game: a proximity warning, a falling scream, a falling whistle and chattering.
Each makes sound a block at a time through render(frameCount); set its
attributes between blocks. Without a live mixer, record one with
synth.render_voice and a change function that moves its attributes.
"""
import math
import numpy as np
from scipy.signal import lfilter
from .synth import Biquad, Oscillator, Ramp, rng_from, sampleRate, saw_wave
class ProximityWarningVoice:
"""Beeps for something closing in: faster and higher as it nears, then one solid tone once it locks on.
Set active to sound it, urgency from 0 (just noticed) to 1 (about to
arrive), and locked for the solid tone. kind is "soft" for a round tone or
"buzzy" for a harsher one, so two kinds of threat can be told apart.
"""
def __init__(self):
self.active = False
self.urgency = 0.0
self.locked = False
self.kind = "soft"
self.tone = Oscillator()
self.beepPhase = 0.0
self.levelRamp = Ramp(0.0)
self.gateState = np.zeros(1)
def render(self, frameCount):
urgency = min(max(self.urgency, 0.0), 1.0)
if self.locked:
frequency = 1500.0
gate = np.ones(frameCount)
else:
frequency = 600.0 + 700.0 * urgency
# From about 2.5 beeps a second to 12, each lasting 40 percent of its cycle.
beepRate = 2.5 + 9.5 * urgency ** 1.5
steps = self.beepPhase + np.cumsum(np.full(frameCount, beepRate / sampleRate))
self.beepPhase = steps[-1] % 1.0
gate = (steps % 1.0 < 0.4).astype(float)
phases, _ = self.tone.advance(np.full(frameCount, frequency))
wave = np.sin(2.0 * math.pi * phases)
if self.kind == "buzzy":
wave = np.tanh(4.0 * wave) * 0.7
# A short ramp on the gate keeps each beep from clicking.
level = self.levelRamp.to(1.0 if self.active else 0.0, frameCount)
gate, self.gateState = lfilter([0.02], [1.0, -0.98], gate, zi=self.gateState)
return 0.5 * level * wave * gate
class FallingScreamVoice:
"""Something falling from the sky, screaming.
The scream is a buzzing voice shaped by three formant filters into an
"aah", with a ragged, wavering pitch. Set progress from 0 to 1 as it
falls: the scream slides down and grows louder.
"""
# Formants of a screamed "aah": centre, sharpness and level.
formants = [(850.0, 6.0, 1.0), (1250.0, 7.0, 0.7), (2900.0, 8.0, 0.35)]
def __init__(self, seed=0):
self.rng = rng_from(seed)
self.voice = Oscillator()
self.filters = [Biquad("bandpass") for _ in self.formants]
self.breathFilter = Biquad("bandpass")
self.startPitch = self.rng.uniform(820.0, 1050.0)
self.vibratoRate = self.rng.uniform(5.0, 7.0)
self.time = 0.0
self.progress = 0.0
def render(self, frameCount):
progress = min(max(self.progress, 0.0), 1.0)
times = self.time + np.arange(frameCount) / sampleRate
self.time += frameCount / sampleRate
# The scream falls by about a fifth as it comes down, with a wild vibrato.
vibrato = 1.0 + 0.04 * np.sin(2.0 * math.pi * self.vibratoRate * times) + 0.015 * self.rng.standard_normal()
pitch = self.startPitch * (1.0 - 0.3 * progress) * vibrato
phases, phaseStep = self.voice.advance(pitch)
buzz = saw_wave(phases, phaseStep)
# A rasp in the throat: the buzz is roughened, more so as it screams louder.
buzz *= 1.0 + 0.3 * self.rng.standard_normal(frameCount) * (0.4 + 0.6 * progress)
scream = np.zeros(frameCount)
for (centre, quality, level), formantFilter in zip(self.formants, self.filters):
# The mouth opens wider as it screams, lifting the first formants.
scream += level * formantFilter.process(buzz, centre * (1.0 + 0.12 * progress), quality)
breath = self.breathFilter.process(self.rng.standard_normal(frameCount), 1800.0, 1.0)
swell = 0.35 + 0.65 * progress
# A short fade in, so the scream does not start with a click.
fadeIn = min(1.0, self.time / 0.08)
return 0.75 * fadeIn * swell * (scream + 0.08 * breath)
class WhistlingFallVoice:
"""Something thrown or dropped, in flight: a falling whistle over rushing air.
pitchFactor bends the pitch, such as for Doppler: above 1 while it closes
on you, below 1 as it moves away.
"""
def __init__(self, seed=0):
self.rng = rng_from(seed)
self.pitchFactor = 1.0
self.pitchRamp = Ramp(1.0)
self.whistle = Oscillator()
self.air = Biquad("bandpass")
self.time = 0.0
def render(self, frameCount):
times = self.time + np.arange(frameCount) / sampleRate
self.time += frameCount / sampleRate
pitch = self.pitchRamp.to(self.pitchFactor, frameCount)
frequency = (1400.0 - 250.0 * np.minimum(times, 4.0)) * pitch
phases, _ = self.whistle.advance(frequency)
rush = self.air.process(self.rng.standard_normal(frameCount), 900.0, 0.8)
return 0.25 * np.sin(2.0 * math.pi * phases) + 0.5 * rush
class ChatteringVoice:
"""Teeth chattering about twelve times a second, such as a skull flying at you.
pitchFactor (0.5 to 2) speeds and raises the chatter, such as for Doppler.
"""
def __init__(self, seed=0):
self.rng = rng_from(seed)
self.pitchFactor = 1.0
self.chatter = Oscillator()
self.clickFilter = Biquad("bandpass")
def render(self, frameCount):
pitch = min(max(self.pitchFactor, 0.5), 2.0)
phases, _ = self.chatter.advance(np.full(frameCount, 12.0 * pitch))
# Longer clicks, driven into soft clipping, carry much further than bare ticks without harsh peaks.
envelope = np.exp(-phases * 12.0)
clicks = self.clickFilter.process(self.rng.standard_normal(frameCount), 2200.0 * pitch, 3.0)
return 0.9 * np.tanh(6.6 * clicks * envelope)
+208
View File
@@ -0,0 +1,208 @@
"""Ambient loops: bubbling, dripping, gurgling, bouncing, a ratchet, and repeating patterns.
These are live voices with nothing for a game to set while they play, so they
can be recorded once into a loop:
loop = make_loop(render_voice(BubblingVoice(), 4.0, fadeSeconds=0))
A game with its own live mixer can also play them directly through render(frameCount).
"""
import math
import numpy as np
from .materials import squelch
from .synth import Biquad, OneShotPlayer, Oscillator, rng_from, sampleRate
class PatternVoice:
"""Plays short sounds over and over in a fixed rhythm: each entry is (sound, seconds until the next).
Good for an item waiting to be found by ear, such as a beacon blip or two
finger snaps and a rest.
"""
def __init__(self, pattern):
self.pattern = pattern
self.player = OneShotPlayer()
self.time = 0.0
self.nextSound = 0.0
self.index = 0
def render(self, frameCount):
if self.time >= self.nextSound:
sound, gap = self.pattern[self.index % len(self.pattern)]
self.player.add(sound)
self.nextSound += gap
self.index += 1
self.time += frameCount / sampleRate
return self.player.render(frameCount)
class BubblingVoice:
"""A bubbling pot or cauldron: quick rising blips over a low simmer."""
def __init__(self, seed=0):
self.rng = rng_from(seed)
self.bubbles = OneShotPlayer()
self.simmer = Biquad("lowpass")
def render(self, frameCount):
# A new bubble about eight times a second, each a quick rising blip.
if self.rng.random() < 8.0 * frameCount / sampleRate:
length = int(sampleRate * self.rng.uniform(0.05, 0.09))
times = np.arange(length) / sampleRate
start = self.rng.uniform(180.0, 320.0)
phase = 2.0 * math.pi * np.cumsum(start * (1.0 + 4.0 * times / times[-1])) / sampleRate
self.bubbles.add(0.5 * np.sin(phase) * np.sin(math.pi * times / times[-1]))
simmer = self.simmer.process(self.rng.standard_normal(frameCount), 300.0, 0.7)
return self.bubbles.render(frameCount) + 0.15 * simmer
class DrippingVoice:
"""Thick, slow drips into a puddle over a dark, sloshing swell.
Each drip is a low plop whose pitch rises as it lands, slower and lower
than water, so it sounds heavy and sticky, like blood or mud.
"""
def __init__(self, seed=0):
self.rng = rng_from(seed)
self.drips = OneShotPlayer()
self.sloshFilter = Biquad("lowpass")
self.tickFilter = Biquad("lowpass")
self.time = 0.0
self.nextDrip = 0.0
def make_drip(self):
length = int(sampleRate * 0.16)
times = np.arange(length) / sampleRate
start = self.rng.uniform(170.0, 230.0)
# The plop: the pitch climbs fast, then settles, like a heavy drop closing over.
pitch = start * (1.0 + 2.2 * (1.0 - np.exp(-times / 0.03)))
plop = np.sin(2.0 * math.pi * np.cumsum(pitch) / sampleRate)
envelope = np.minimum(1.0, times / 0.004) * np.exp(-times / 0.045)
# A tiny wet tick as the drop lands.
tick = self.tickFilter.process(self.rng.standard_normal(length), 2500.0, 0.7) * np.exp(-times / 0.004)
return 0.75 * plop * envelope + 0.15 * tick
def render(self, frameCount):
if self.time >= self.nextDrip:
self.drips.add(self.make_drip())
# Drips come unevenly, sometimes two close together.
self.nextDrip += self.rng.choice([0.18, 0.55, 0.7, 0.9])
times = self.time + np.arange(frameCount) / sampleRate
self.time += frameCount / sampleRate
# The slosh rocks back and forth a little under once a second.
swell = 0.5 + 0.5 * np.sin(2.0 * math.pi * 0.7 * times) * np.sin(2.0 * math.pi * 0.31 * times + 1.0)
slosh = self.sloshFilter.process(self.rng.standard_normal(frameCount), 260.0 + 140.0 * swell[0], 1.2)
return self.drips.render(frameCount) + 0.35 * slosh * swell
class GurglingVoice:
"""Something wet and alive: squelches now and then, over a low, bubbling gurgle like a stomach."""
def __init__(self, seed=0):
self.rng = rng_from(seed)
self.squelches = OneShotPlayer()
self.gurgle = Oscillator()
self.gurgleFilter = Biquad("lowpass")
self.time = 0.0
self.nextSquelch = 0.0
self.wobble = 0.0
def render(self, frameCount):
if self.time >= self.nextSquelch:
seconds = self.rng.uniform(0.14, 0.26)
low = self.rng.uniform(220.0, 320.0)
high = self.rng.uniform(700.0, 1000.0)
self.squelches.add(1.6 * squelch(seconds, low, high, seed=self.rng))
self.nextSquelch += self.rng.uniform(0.45, 1.1)
self.time += frameCount / sampleRate
# The gurgle's pitch wanders and bubbles, from about 60 to 120 cycles a second.
self.wobble = min(1.0, max(-1.0, self.wobble + self.rng.uniform(-0.3, 0.3)))
times = np.arange(frameCount) / sampleRate
bubble = np.sin(2.0 * math.pi * 9.0 * (self.time + times)) * np.sin(2.0 * math.pi * 2.3 * (self.time + times))
phases, _ = self.gurgle.advance(90.0 + 30.0 * self.wobble + 20.0 * bubble)
gurgle = np.sin(2.0 * math.pi * phases) * (0.5 + 0.5 * np.abs(bubble))
murk = self.gurgleFilter.process(self.rng.standard_normal(frameCount), 180.0, 0.9)
return self.squelches.render(frameCount) + 0.35 * gurgle + 0.25 * murk
class BouncingSpringVoice:
"""Something hollow bouncing on a spring: a springy boing over a hollow thump.
It bounces three times, each lower and quicker, then gets kicked back up
again. gaps and pitches can be changed for a different bounce.
"""
gaps = [0.36, 0.3, 0.25, 0.55]
pitches = [262.0, 233.0, 208.0, 185.0]
def __init__(self, seed=0):
self.rng = rng_from(seed)
self.bounces = OneShotPlayer()
self.time = 0.0
self.nextBounce = 0.0
self.index = 0
def make_bounce(self, frequency, size):
length = int(sampleRate * 0.22)
times = np.arange(length) / sampleRate
# The boing: a swoop down onto the note, then a wobble like a spring.
wobble = 1.0 + 0.1 * np.sin(2.0 * math.pi * 16.0 * times) * np.exp(-times / 0.08)
pitch = frequency * (1.0 + 0.6 * np.exp(-times / 0.025)) * wobble
boing = np.sin(2.0 * math.pi * np.cumsum(pitch) / sampleRate) * np.exp(-times / 0.09)
# The thump of something hollow landing.
thumpPitch = 110.0 * (1.0 + np.exp(-times / 0.01))
thump = np.sin(2.0 * math.pi * np.cumsum(thumpPitch) / sampleRate) * np.exp(-times / 0.03)
attack = np.minimum(1.0, times / 0.002)
return 1.3 * size * attack * (0.45 * boing + 0.5 * thump)
def render(self, frameCount):
if self.time >= self.nextBounce:
step = self.index % len(self.gaps)
size = 1.0 - 0.15 * step
self.bounces.add(self.make_bounce(self.pitches[step], size))
self.nextBounce += self.gaps[step]
self.index += 1
self.time += frameCount / sampleRate
return self.bounces.render(frameCount)
class RatchetVoice:
"""A wooden ratchet winding back, click by click, then a rest, over and over.
The knock of each click rises a little as it winds tighter.
"""
clicksPerWind = 8
clickSeconds = 0.11
restSeconds = 0.6
def __init__(self, seed=0):
self.rng = rng_from(seed)
self.player = OneShotPlayer()
self.clickFilter = Biquad("bandpass")
self.time = 0.0
self.nextClick = 0.0
self.index = 0
def make_click(self, tension):
length = int(sampleRate * 0.06)
times = np.arange(length) / sampleRate
snap = self.clickFilter.process(self.rng.standard_normal(length), 1500.0 + 600.0 * tension, 5.0)
snap *= np.exp(-times / 0.006)
knock = np.sin(2.0 * math.pi * (240.0 + 80.0 * tension) * times) * np.exp(-times / 0.02)
return 0.6 * snap + 0.5 * knock
def render(self, frameCount):
if self.time >= self.nextClick:
step = self.index % self.clicksPerWind
self.player.add(self.make_click(step / (self.clicksPerWind - 1)))
self.index += 1
last = step == self.clicksPerWind - 1
self.nextClick += self.clickSeconds + (self.restSeconds if last else 0.0)
self.time += frameCount / sampleRate
return self.player.render(frameCount)
+68
View File
@@ -0,0 +1,68 @@
"""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)
+107
View File
@@ -0,0 +1,107 @@
"""Creature voices: a horse's whinny and a witch's cackle.
Each call with the same seed gives the same call. echo adds a short, ghostly
double echo after it, for a skeleton or a haunted place.
"""
import math
import numpy as np
from .synth import Biquad, breath_shape, buzz_wave, formant_filter, glide, rng_from, sampleRate
# A whinny lasts this long, before its echo, which repeats it this many seconds later, twice.
whinnySeconds = 1.7
whinnyEcho = 0.16
# A cackle is runs of "heh" syllables, each run starting high again; the last, full run falls all the way.
cackleRuns = (3, 3, 11)
cackleRate = 7.5
cackleHighPitch = 620.0
cackleLowPitch = 430.0
# A short breath before each run starts over.
cacklePause = 0.03
cackleEcho = 0.14
def _finish(sound, echoSeconds, echoLevels):
"""Normalise to full scale, after adding the echoes if there are any."""
if echoLevels:
delay = int(echoSeconds * sampleRate)
echoed = np.concatenate((sound, np.zeros(len(echoLevels) * delay)))
for index, level in enumerate(echoLevels, start=1):
echoed[index * delay:index * delay + len(sound)] += level * sound
sound = echoed
return sound / np.max(np.abs(sound))
def horse_whinny(seed=0, echo=False):
"""A horse's whinny: a squeal that falls away in a shaking trill, then a fluttering snort.
Horses sound two pitches at once, so a low voice sits under the squeal.
"""
rng = rng_from(seed)
times = np.arange(int(whinnySeconds * sampleRate)) / sampleRate
lift = rng.uniform(0.93, 1.07)
pitch = glide(times, [(0.0, 700), (0.07, 1150), (0.25, 1050), (0.75, 720), (1.05, 480), (1.25, 330)]) * lift
trillRate = glide(times, [(0.0, 17), (0.6, 15), (1.2, 9)]) * rng.uniform(0.92, 1.08)
trill = np.sin(2.0 * math.pi * np.cumsum(trillRate / sampleRate))
shake = 1.0 - 0.55 * (0.5 + 0.5 * trill) * glide(times, [(0.0, 0.2), (0.3, 1.0), (1.25, 1.0)])
neighLevel = glide(times, [(0.0, 0.0), (0.03, 1.0), (0.9, 0.85), (1.2, 0.5), (1.3, 0.0)])
high = buzz_wave(pitch * (1.0 + 0.07 * trill))
low = buzz_wave(glide(times, [(0.0, 300), (1.25, 262)]) * (1.0 + 0.04 * trill))
source = (high + 0.5 * low) * shake * neighLevel
nasal = (Biquad("bandpass").process(source, 950.0, 2.5)
+ 0.8 * Biquad("bandpass").process(source, 1800.0, 3.5)
+ 0.4 * Biquad("bandpass").process(source, 3000.0, 4.0))
breath = Biquad("highpass").process(rng.standard_normal(len(times)), 2500.0, 0.7) * 0.06 * neighLevel
snortLevel = glide(times, [(0.0, 0.0), (1.28, 0.0), (1.33, 1.0), (1.55, 0.4), (1.7, 0.0)])
flutter = 0.5 + 0.5 * np.sin(2.0 * math.pi * 30.0 * times)
snort = Biquad("bandpass").process(rng.standard_normal(len(times)), 1200.0, 1.0) * flutter * snortLevel * 0.6
sound = nasal + breath + snort
return _finish(sound, whinnyEcho, (0.3, 0.12) if echo else ())
def witch_cackle(seed=0, echo=False):
"""A witch's cackle: two false starts of "heh heh heh", then a full run falling in pitch.
Each "heh" starts with a breathy "h", breath through the same mouth shape
as the vowel, which keeps it from sounding like "ch". The voice is old and
shaky, with a creaky rasp.
"""
rng = rng_from(seed)
syllableGap = 1.0 / cackleRate
longestRun = max(cackleRuns)
starts = []
clock = 0.0
for runIndex, count in enumerate(cackleRuns):
if runIndex > 0:
clock += cacklePause
for index in range(count):
starts.append((clock, index))
clock += syllableGap
times = np.arange(int((clock + 0.15) * sampleRate)) / sampleRate
pitch = np.full(len(times), cackleLowPitch)
voiced = np.zeros(len(times))
breathy = np.zeros(len(times))
for syllableStart, index in starts:
start = syllableStart + rng.uniform(-0.008, 0.008)
base = cackleHighPitch + (cackleLowPitch - cackleHighPitch) * index / (longestRun - 1)
base *= rng.uniform(0.97, 1.03)
length = syllableGap * rng.uniform(0.55, 0.7)
inside = (times >= start) & (times < start + length)
local = (times[inside] - start) / length
# Each "heh" jumps up, then sags.
pitch[inside] = base * (1.08 - 0.15 * local)
voiced[inside] = np.minimum(1.0, local / 0.15) * np.clip((1.0 - local) / 0.3, 0.0, 1.0)
onset = (times >= start - 0.05) & (times < start + 0.03)
breathy[onset] = np.maximum(breathy[onset], breath_shape(onset.sum()))
jitter = 1.0 + 0.012 * Biquad("lowpass").process(rng.standard_normal(len(times)), 60.0, 0.7)
tremble = 1.0 + 0.03 * np.sin(2.0 * math.pi * 11.0 * times)
source = buzz_wave(pitch * jitter * tremble)
# The rasp: every other pulse of the voice weaker.
halfPhase = np.cumsum(pitch / sampleRate / 2.0) % 1.0
source *= (1.0 - 0.35 * (halfPhase < 0.5)) * voiced
noise = Biquad("lowpass").process(rng.standard_normal(len(times)), 3500.0, 0.7)
sound = formant_filter(source + noise * (0.35 * breathy + 0.04 * voiced), "pinched_eh")
return _finish(sound, cackleEcho, (0.25, 0.1) if echo else ())
+99
View File
@@ -0,0 +1,99 @@
"""Impacts and weather: thunder, explosions, booms, thuds and things smashing.
Each takes a seed: the same seed always gives the same sound, a different seed
a variant of it, and None a new variant every time.
"""
import math
import numpy as np
from .synth import Biquad, blockSize, rng_from, sampleRate, sweep_filtered
def thunder(seed=0):
"""A crack of thunder and a long rolling rumble, about three seconds."""
rng = rng_from(seed)
length = int(sampleRate * 3.0)
times = np.arange(length) / sampleRate
blockCount = (length + blockSize - 1) // blockSize
blockTimes = np.arange(blockCount) * blockSize / sampleRate
# The rumble rolls: its brightness rises and falls a few times as it dies away.
centres = 120.0 + 900.0 * np.exp(-blockTimes / 0.25) + 150.0 * (1.0 + np.sin(2.0 * math.pi * 1.7 * blockTimes))
rumble = sweep_filtered(rng.standard_normal(length), "lowpass", centres, 0.8)
roll = 0.6 + 0.4 * np.sin(2.0 * math.pi * 1.3 * times + 1.0) ** 2
rumble *= np.minimum(1.0, times / 0.02) * np.exp(-times / 1.0) * roll
crack = Biquad("highpass").process(rng.standard_normal(length), 800.0) * np.exp(-times / 0.05)
return np.tanh(1.5 * (0.9 * rumble + 0.4 * crack)) * 0.8
def explosion(seed=0):
"""A crack and a rumbling boom, a little under a second and a half."""
rng = rng_from(seed)
length = int(sampleRate * 1.4)
sampleIndex = np.arange(length)
times = sampleIndex / sampleRate
noise = rng.standard_normal(length)
boomFilter = Biquad("lowpass")
boom = np.zeros(length)
for blockStart in range(0, length, blockSize):
blockEnd = min(blockStart + blockSize, length)
cutoff = 3000.0 * math.exp(-blockStart / sampleRate * 4.0) + 150.0
boom[blockStart:blockEnd] = boomFilter.process(noise[blockStart:blockEnd], cutoff, 0.8)
boom *= np.exp(-times / 0.4)
thump = np.sin(2.0 * math.pi * 55.0 * times) * np.exp(-times / 0.15)
crack = noise * np.exp(-times / 0.01)
return 0.45 * boom + 0.4 * thump + 0.15 * crack
def heavy_boom(seed=0):
"""Something huge coming to rest: a deep thump that drops in pitch, then a long rolling rumble."""
rng = rng_from(seed)
length = int(sampleRate * 2.2)
times = np.arange(length) / sampleRate
noise = rng.standard_normal(length)
# The thump falls from 95 to 32 cycles a second, felt as much as heard.
thumpPitch = 32.0 + 63.0 * np.exp(-times / 0.08)
thump = np.sin(2.0 * math.pi * np.cumsum(thumpPitch) / sampleRate) * np.exp(-times / 0.35)
rumbleFilter = Biquad("lowpass")
rumble = np.zeros(length)
for blockStart in range(0, length, blockSize):
blockEnd = min(blockStart + blockSize, length)
cutoff = 1800.0 * math.exp(-blockStart / sampleRate * 3.0) + 90.0
rumble[blockStart:blockEnd] = rumbleFilter.process(noise[blockStart:blockEnd], cutoff, 0.9)
rumble *= np.exp(-times / 0.7)
crack = noise * np.exp(-times / 0.015)
attack = np.minimum(1.0, times / 0.002)
# Driving it into soft clipping gives the grit, and keeps it loud without harsh peaks.
boom = np.tanh(1.8 * (1.0 * thump + 0.8 * rumble + 0.25 * crack)) * attack
return 0.95 * boom
def thud(seed=0):
"""Two solid things bumping: a dull knock with a scrape."""
rng = rng_from(seed)
length = int(sampleRate * 0.25)
sampleIndex = np.arange(length)
knock = np.sin(2.0 * math.pi * 70.0 * sampleIndex / sampleRate) * np.exp(-sampleIndex / (sampleRate * 0.05))
scrape = Biquad("bandpass").process(rng.standard_normal(length), 1200.0, 1.0)
scrape *= np.exp(-sampleIndex / (sampleRate * 0.08))
return 0.6 * knock + 0.25 * scrape
def shatter(seed=0):
"""Something brittle hitting the ground: a hard crack and a thud, then pieces clattering away."""
rng = rng_from(seed)
length = int(sampleRate * 0.6)
times = np.arange(length) / sampleRate
crack = Biquad("highpass").process(rng.standard_normal(length), 1500.0) * np.exp(-times / 0.006)
thudPart = np.sin(2.0 * math.pi * np.cumsum(85.0 * (1.0 + 0.8 * np.exp(-times / 0.015))) / sampleRate)
thudPart *= np.exp(-times / 0.06)
clatter = np.zeros(length)
for _ in range(6):
start = int(sampleRate * rng.uniform(0.04, 0.4))
pieceLength = int(sampleRate * 0.05)
pieceTimes = np.arange(pieceLength) / sampleRate
piece = np.sin(2.0 * math.pi * rng.uniform(700.0, 1600.0) * pieceTimes) * np.exp(-pieceTimes / 0.008)
end = min(length, start + pieceLength)
clatter[start:end] += rng.uniform(0.2, 0.5) * piece[:end - start]
return 0.35 * crack + 0.4 * thudPart + 0.3 * clatter
+126
View File
@@ -0,0 +1,126 @@
"""Materials: snaps, clanks, rattles, knocks, wet squelches and splashes, and a wooden launch."""
import math
import numpy as np
from .synth import Biquad, blockSize, rng_from, sampleRate, sweep_filtered
def finger_snap(pitch=1.0, seed=0):
"""A finger snap: a sharp bright crack with a short hollow knock under it."""
rng = rng_from(seed)
times = np.arange(int(sampleRate * 0.09)) / sampleRate
crack = Biquad("bandpass").process(rng.standard_normal(len(times)), 2600.0 * pitch, 1.4) * np.exp(-times / 0.012)
knock = np.sin(2.0 * math.pi * 900.0 * pitch * times) * np.exp(-times / 0.008)
return 0.5 * (crack + 0.4 * knock) * np.minimum(1.0, times / 0.0005)
def metal_clank(pitch=820.0, seed=0):
"""A metal tool dropped in a metal box: a hard clank with a short, clangy ring."""
rng = rng_from(seed)
times = np.arange(int(sampleRate * 0.16)) / sampleRate
ring = np.zeros_like(times)
for partial, level, decay in ((1.0, 1.0, 0.05), (1.58, 0.7, 0.04), (2.31, 0.5, 0.03), (3.93, 0.3, 0.02)):
ring += level * np.sin(2.0 * math.pi * pitch * partial * times) * np.exp(-times / decay)
hit = Biquad("bandpass").process(rng.standard_normal(len(times)), 3000.0, 1.0) * np.exp(-times / 0.004)
return 0.3 * (ring + 0.8 * hit) * np.minimum(1.0, times / 0.0005)
def rattle(seconds=0.07, seed=0):
"""One shake of seeds in a gourd: a quick dry hiss of tiny clicks."""
rng = rng_from(seed)
length = int(sampleRate * seconds)
times = np.arange(length) / sampleRate
grains = rng.standard_normal(length) * (rng.random(length) < 0.25)
hiss = Biquad("highpass").process(grains, 3500.0, 0.8)
body = Biquad("bandpass").process(rng.standard_normal(length), 700.0, 2.0)
envelope = np.sin(math.pi * times / times[-1]) ** 0.7
return 0.19 * (hiss + 0.25 * body) * envelope
def hollow_knock(frequency):
"""A hollow bone or wooden bar struck once, like one note of a xylophone."""
length = int(sampleRate * 0.18)
times = np.arange(length) / sampleRate
knock = (np.sin(2.0 * math.pi * frequency * times)
+ 0.4 * np.sin(2.0 * math.pi * frequency * 3.9 * times) * np.exp(-times / 0.01))
return 0.5 * knock * np.exp(-times / 0.04)
def squelch(seconds, low, high, quality=4.0, seed=0):
"""A wet squelch: noise through a narrow filter that swoops up from low to high and back down."""
rng = rng_from(seed)
length = int(sampleRate * seconds)
times = np.arange(length) / sampleRate
blockCount = (length + blockSize - 1) // blockSize
shape = np.sin(math.pi * np.linspace(0.0, 1.0, blockCount)) ** 0.7
squelchSound = sweep_filtered(rng.standard_normal(length), "bandpass", low + (high - low) * shape, quality)
envelope = np.minimum(1.0, times / 0.012) * (1.0 - times / times[-1]) ** 1.3
return squelchSound * envelope
def wet_splat(seed=0):
"""Landing in something soft and wet: a big squelch with a slap, over a low thump."""
rng = rng_from(seed)
squelchSound = 1.8 * squelch(0.45, 200.0, 1100.0, quality=3.0, seed=rng)
length = len(squelchSound)
times = np.arange(length) / sampleRate
slap = Biquad("lowpass").process(rng.standard_normal(length), 2500.0) * np.exp(-times / 0.02)
thump = np.sin(2.0 * math.pi * np.cumsum(70.0 * (1.0 + np.exp(-times / 0.02))) / sampleRate) * np.exp(-times / 0.08)
return 0.6 * squelchSound + 0.4 * slap + 0.5 * thump
def thick_splash(seed=0):
"""Driving or stepping through a thick liquid: a heavy wet smack, a short sheet of spray,
then slow drops pattering back down."""
rng = rng_from(seed)
length = int(sampleRate * 0.65)
times = np.arange(length) / sampleRate
# The smack of hitting the puddle: a dull wet body and a low thump.
body = Biquad("bandpass").process(rng.standard_normal(length), 450.0, 1.2) * np.exp(-times / 0.035)
thump = np.sin(2.0 * math.pi * np.cumsum(75.0 * (1.0 + np.exp(-times / 0.01))) / sampleRate) * np.exp(-times / 0.05)
# The sheet thrown up: noise whose band sweeps up and back down over a fifth of a second.
sheetLength = int(sampleRate * 0.2)
blockCount = (sheetLength + blockSize - 1) // blockSize
shape = np.sin(math.pi * np.linspace(0.0, 1.0, blockCount))
sheet = sweep_filtered(rng.standard_normal(sheetLength), "bandpass", 500.0 + 1700.0 * shape, 1.8)
sheetTimes = np.arange(sheetLength) / sampleRate
sheet *= np.minimum(1.0, sheetTimes / 0.01) * (1.0 - sheetTimes / sheetTimes[-1]) ** 1.5
# Drops falling back: each a short plop that rises in pitch, thinning out as the splash settles.
drops = np.zeros(length)
for _ in range(22):
start = int(sampleRate * (0.05 + 0.5 * rng.random() ** 1.8))
dropLength = int(sampleRate * rng.uniform(0.015, 0.035))
dropTimes = np.arange(dropLength) / sampleRate
pitch = rng.uniform(450.0, 1300.0) * (1.0 + 1.2 * dropTimes / dropTimes[-1])
drop = np.sin(2.0 * math.pi * np.cumsum(pitch) / sampleRate) * np.sin(math.pi * dropTimes / dropTimes[-1])
end = min(length, start + dropLength)
# Later drops are smaller.
drops[start:end] += rng.uniform(0.3, 1.0) * (1.0 - start / length) * drop[:end - start]
output = 0.55 * body + 0.45 * thump + 0.25 * drops
output[:sheetLength] += 0.5 * sheet
return 1.1 * output
def wooden_launch(seed=0):
"""A wooden throwing arm flinging something: a heavy thunk, a creak, and a rush of air rising away."""
rng = rng_from(seed)
length = int(sampleRate * 1.3)
times = np.arange(length) / sampleRate
thunkPitch = 70.0 + 60.0 * np.exp(-times / 0.05)
thunk = np.sin(2.0 * math.pi * np.cumsum(thunkPitch) / sampleRate) * np.exp(-times / 0.15)
crack = rng.standard_normal(length) * np.exp(-times / 0.01)
# The arm creaks as it swings: a rough low buzz that wavers.
creakPitch = 140.0 + 25.0 * np.sin(2.0 * math.pi * 7.0 * times)
creakPhases = (np.cumsum(creakPitch) / sampleRate) % 1.0
creak = (2.0 * creakPhases - 1.0) * np.exp(-((times - 0.12) / 0.08) ** 2)
rushFilter = Biquad("bandpass")
noise = rng.standard_normal(length)
rush = np.zeros(length)
for blockStart in range(0, length, blockSize):
blockEnd = min(blockStart + blockSize, length)
progress = blockStart / length
rush[blockStart:blockEnd] = rushFilter.process(noise[blockStart:blockEnd], 400.0 * 8.0 ** progress, 1.0)
rush *= np.sin(math.pi * np.minimum(times / 1.3, 1.0)) ** 2
return np.tanh(1.2 * (0.9 * thunk + 0.25 * crack + 0.3 * creak + 0.7 * rush)) * 0.8
+121
View File
@@ -0,0 +1,121 @@
"""Rewards and pickups: sparkles, chimes, charges, beacons and items spilling."""
import math
import numpy as np
from .synth import Biquad, pulse_wave, rng_from, sampleRate, soften, square_wave
def sparkle():
"""Collecting something: quick rising twinkles and a ringing top note."""
parts = []
for frequency in (1318.5, 1568.0, 2093.0):
times = np.arange(int(sampleRate * 0.07)) / sampleRate
parts.append(np.sin(2.0 * math.pi * frequency * times) * np.exp(-times / 0.03))
tail = np.arange(int(sampleRate * 0.4)) / sampleRate
parts.append(np.sin(2.0 * math.pi * 2637.0 * tail) * np.exp(-tail / 0.12))
return 0.4 * np.concatenate(parts)
def bell_chime(count=1):
"""A high bell struck count times in quick succession, such as one to three for how hard a bend is."""
gap = int(sampleRate * 0.13)
ringLength = int(sampleRate * 0.7)
output = np.zeros(gap * (count - 1) + ringLength)
times = np.arange(ringLength) / sampleRate
ring = np.zeros(ringLength)
for partial, level, decay in ((1.0, 1.0, 0.35), (2.76, 0.5, 0.2), (5.4, 0.25, 0.1)):
ring += level * np.sin(2.0 * math.pi * 1046.5 * partial * times) * np.exp(-times / decay)
ring *= np.minimum(1.0, times / 0.002)
for index in range(count):
output[index * gap:index * gap + ringLength] += ring
return 0.3 * output
def beacon_blip():
"""One short square blip, for repeating quickly so a waiting item is easy to find by ear."""
blip = square_wave(500.0, 0.07)
attack = int(sampleRate * 0.003)
blip[:attack] *= np.linspace(0.0, 1.0, attack)
release = int(sampleRate * 0.01)
blip[-release:] *= np.linspace(1.0, 0.0, release)
return 0.22 * soften(blip)
def power_charge():
"""A square wave charging up, rising and pulsing faster, then a bright ping."""
seconds = 0.9
times = np.arange(int(sampleRate * seconds)) / sampleRate
progress = times / seconds
# The pitch climbs from 250 to 1500 cycles, faster towards the end.
frequency = 250.0 * 6.0 ** (progress ** 1.6)
phaseStep = frequency / sampleRate
phases = np.cumsum(phaseStep) % 1.0
charge = 2.0 * pulse_wave(phases, phaseStep, 0.5)
# It pulses ever faster as it fills, from 8 to 40 pulses a second.
pulseRate = 8.0 + 32.0 * progress
pulses = 0.6 + 0.4 * np.sin(2.0 * math.pi * np.cumsum(pulseRate) / sampleRate)
charge *= pulses * (0.5 + 0.5 * progress)
pingTimes = np.arange(int(sampleRate * 0.5)) / sampleRate
ping = square_wave(2000.0, 0.5) * np.exp(-pingTimes / 0.12)
sound = np.concatenate((charge, ping))
attack = int(sampleRate * 0.005)
sound[:attack] *= np.linspace(0.0, 1.0, attack)
return 0.22 * soften(sound)
def bonus_run():
"""A quick rising run of square notes ending on a long high tone: a bigger reward than confirm_chime."""
parts = []
for frequency in (500.0, 630.0, 750.0, 1000.0):
note = square_wave(frequency, 0.06)
note[-int(sampleRate * 0.005):] *= np.linspace(1.0, 0.0, int(sampleRate * 0.005))
parts.append(note)
tail = square_wave(1500.0, 0.5) * (1.0 - np.arange(int(sampleRate * 0.5)) / (sampleRate * 0.5)) ** 2.5
sound = np.concatenate(parts + [tail])
sound[:int(sampleRate * 0.003)] *= np.linspace(0.0, 1.0, int(sampleRate * 0.003))
return 0.22 * soften(sound)
def rising_sweep():
"""A quick bright sweep upwards, for repeating while an item waits to be picked up."""
length = int(sampleRate * 0.35)
times = np.arange(length) / sampleRate
frequency = 700.0 * 3.0 ** (times / times[-1])
phases = np.cumsum(frequency) / sampleRate
sweep = np.sin(2.0 * math.pi * phases) + 0.3 * np.sin(4.0 * math.pi * phases)
envelope = np.minimum(1.0, times / 0.01) * (1.0 - times / times[-1]) ** 1.5
return 0.35 * sweep * envelope
def item_spill(count, seed=0):
"""Items spilling out: a quick run of falling plinks, one for each item lost (at most 10),
then a light patter as the pieces bounce and settle."""
rng = rng_from(seed)
plinks = max(1, min(10, count))
plinkSeconds = 0.09
gap = 0.05
patterStart = (plinks - 1) * gap + plinkSeconds
output = np.zeros(int(sampleRate * (patterStart + 0.45)))
times = np.arange(int(sampleRate * plinkSeconds)) / sampleRate
for index in range(plinks):
# Each plink drops in pitch as it falls, and each starts a little lower than the one before.
start = 1900.0 * 2.0 ** (-index * 1.5 / 12.0)
frequency = start * (1.0 - 0.35 * times / times[-1])
phases = np.cumsum(frequency) / sampleRate
tone = np.sin(2.0 * math.pi * phases) + 0.25 * np.sin(6.0 * math.pi * phases)
envelope = np.minimum(1.0, times / 0.003) * (1.0 - times / times[-1]) ** 2
offset = int(sampleRate * index * gap)
output[offset:offset + len(tone)] += tone * envelope
# The pieces landing: a few short ticks, quieter and further apart as they settle.
tickFilter = Biquad("bandpass")
tickLength = int(sampleRate * 0.012)
moment = patterStart
for index in range(min(6, 2 + plinks // 2)):
tick = tickFilter.process(rng.standard_normal(tickLength), 3200.0, 4.0)
tick *= np.linspace(1.0, 0.0, tickLength) * 0.9 ** index
offset = int(sampleRate * moment)
output[offset:offset + tickLength] += 0.8 * tick[:len(output) - offset]
moment += rng.uniform(0.04, 0.08)
return 0.3 * output / max(1e-9, np.abs(output).max())
+287
View File
@@ -0,0 +1,287 @@
"""Building blocks for generated sounds: waves, filters, envelopes and assembly.
Every generator in libstormgames.sfx returns a numpy array of float samples at
sampleRate: one dimension for mono, two (frames, 2) for stereo, roughly from -1
to 1. Nothing here touches pygame; libstormgames.sfx.make_sound turns an array
into a pygame Sound.
Sounds that change their filter over time do so once per blockSize samples, so
blockSize is part of how they sound and is fixed here, never taken from a game.
"""
import math
import numpy as np
from scipy.signal import lfilter
try:
# lfilter's own checks cost more than the filtering itself on a block this short, and a live voice
# runs several filters a block, so the filter is called directly where this SciPy has it.
from scipy.signal._sigtools import _linear_filter
except ImportError:
_linear_filter = None
sampleRate = 44100
blockSize = 512
def run_filter(numerator, denominator, signal, state):
"""lfilter, with the filter's state carried in and out."""
if _linear_filter is not None:
return _linear_filter(np.array(numerator), np.array(denominator), np.asarray(signal, dtype=float), -1, state)
return lfilter(numerator, denominator, signal, zi=state)
def rng_from(seed):
"""A random generator from seed: a number, None for a different sound every time, or a generator to share."""
return np.random.default_rng(seed)
def poly_blep(phase, phaseStep):
"""Correction that removes most aliasing from a sawtooth's jump."""
correction = np.zeros_like(phase)
low = phase < phaseStep
x = phase[low] / phaseStep[low]
correction[low] = x + x - x * x - 1.0
high = phase > 1.0 - phaseStep
x = (phase[high] - 1.0) / phaseStep[high]
correction[high] = x * x + x + x + 1.0
return correction
def saw_wave(phase, phaseStep):
"""Band-limited sawtooth from phases (0 to 1) and the phase step of each sample."""
return 2.0 * phase - 1.0 - poly_blep(phase, phaseStep)
def pulse_wave(phase, phaseStep, width):
"""Pulse wave with no DC offset, high for `width` of each cycle."""
shifted = (phase + width) % 1.0
return 0.5 * (saw_wave(phase, phaseStep) - saw_wave(shifted, phaseStep))
def square_wave(frequency, seconds):
"""A band-limited square wave, from -1 to 1."""
length = int(sampleRate * seconds)
phaseStep = np.full(length, frequency / sampleRate)
phases = np.cumsum(phaseStep) % 1.0
return 2.0 * pulse_wave(phases, phaseStep, 0.5)
def buzz_wave(frequency):
"""A buzzy sawtooth voice following a changing pitch, one frequency per sample."""
phaseStep = frequency / sampleRate
return saw_wave(np.cumsum(phaseStep) % 1.0, phaseStep)
def smooth_step(edgeLow, edgeHigh, values):
"""Hermite step of an array: 0 below edgeLow, 1 above edgeHigh, smooth between."""
position = np.clip((values - edgeLow) / (edgeHigh - edgeLow), 0.0, 1.0)
return position * position * (3.0 - 2.0 * position)
def glide(times, points):
"""Values gliding in straight lines between (time, value) points."""
pointTimes, values = zip(*points)
return np.interp(times, pointTimes, values)
def breath_shape(count):
"""Breath that swells gently, then fades as a voice takes over."""
position = np.linspace(0.0, 1.0, count)
return np.where(position < 0.6, np.sin(0.5 * math.pi * position / 0.6) ** 2,
np.cos(0.5 * math.pi * (position - 0.6) / 0.4) ** 2)
class Ramp:
"""Moves linearly from the last value to a new target across one block."""
# The fraction of the way along at each frame, kept for each block length.
stepsByLength = {}
def __init__(self, value=0.0):
self.value = value
def to(self, target, frameCount):
steps = Ramp.stepsByLength.get(frameCount)
if steps is None:
steps = np.arange(1, frameCount + 1) / frameCount
Ramp.stepsByLength[frameCount] = steps
values = self.value + (target - self.value) * steps
self.value = target
return values
class Oscillator:
"""Keeps its phase between blocks, so pitch changes never click."""
def __init__(self, startPhase=0.0):
self.phase = startPhase
def advance(self, frequency):
"""Phases and phase steps for one block, from a frequency for each sample."""
phaseStep = np.maximum(frequency, 1.0) / sampleRate
phases = (self.phase + np.cumsum(phaseStep)) % 1.0
self.phase = phases[-1]
return phases, phaseStep
class Biquad:
"""Second-order lowpass, highpass or bandpass filter whose settings may change every block."""
def __init__(self, kind="lowpass"):
self.kind = kind
self.state = np.zeros(2)
def process(self, signal, cutoff, quality=0.707):
cutoff = min(max(cutoff, 20.0), sampleRate * 0.45)
omega = 2.0 * math.pi * cutoff / sampleRate
alpha = math.sin(omega) / (2.0 * quality)
cosOmega = math.cos(omega)
if self.kind == "lowpass":
numerator = [(1.0 - cosOmega) / 2.0, 1.0 - cosOmega, (1.0 - cosOmega) / 2.0]
elif self.kind == "highpass":
numerator = [(1.0 + cosOmega) / 2.0, -(1.0 + cosOmega), (1.0 + cosOmega) / 2.0]
else:
numerator = [alpha, 0.0, -alpha]
denominator = [1.0 + alpha, -2.0 * cosOmega, 1.0 - alpha]
output, self.state = run_filter(numerator, denominator, signal, self.state)
return output
def sweep_filtered(signal, filterKind, centres, quality):
"""Filter a signal in blocks, with the filter's centre following centres (one per block)."""
output = np.zeros(len(signal))
sweepFilter = Biquad(filterKind)
for index, start in enumerate(range(0, len(signal), blockSize)):
output[start:start + blockSize] = sweepFilter.process(signal[start:start + blockSize], centres[index], quality)
return output
# Formants as (centre, sharpness, level), for formant_filter.
vowels = {
# A pinched, nasal "eh", like an old crone's.
"pinched_eh": ((650.0, 4.0, 1.0), (1900.0, 5.0, 1.0), (2900.0, 6.0, 0.7), (4000.0, 6.0, 0.3)),
}
def formant_filter(signal, formants):
"""Shape a buzzy signal into a vowel: formants is a vowels entry or (centre, sharpness, level) bands."""
if isinstance(formants, str):
formants = vowels[formants]
output = None
for centre, quality, level in formants:
band = Biquad("bandpass").process(signal, centre, quality)
if level != 1.0:
band = level * band
output = band if output is None else output + band
return output
def soften(sound):
"""Take the harsh edge off a square wave with a gentle one-pole lowpass."""
return lfilter([0.35], [1.0, -0.65], sound)
def note_frequency(midiNote):
"""Frequency of a MIDI note number, where 69 is A at 440."""
return 440.0 * 2.0 ** ((midiNote - 69) / 12.0)
def pan_gains(pan):
"""Equal-power left and right gains for pan, from -1 (left) to 1 (right)."""
angle = (min(max(pan, -1.0), 1.0) + 1.0) * math.pi / 4.0
return math.cos(angle), math.sin(angle)
def place(output, sound, startSeconds):
"""Add sound into output at startSeconds; whatever runs past the end of output is cut off."""
offset = int(startSeconds * sampleRate)
end = min(len(output), offset + len(sound))
output[offset:end] += sound[:end - offset]
def place_looped(track, sound, offset, gain=1.0):
"""Add sound into a looping track at frame offset, wrapping anything past the end round to the start."""
for start in range(0, len(sound), len(track)):
piece = sound[start:start + len(track)]
position = (offset + start) % len(track)
count = min(len(piece), len(track) - position)
track[position:position + count] += piece[:count] * gain
if count < len(piece):
track[:len(piece) - count] += piece[count:] * gain
def join(*sounds):
"""Sounds one after another, as stereo; a mono sound is put in the centre."""
stereo = [sound if sound.ndim == 2 else np.column_stack((sound, sound)) * 0.7071 for sound in sounds]
return np.concatenate(stereo)
def normalize(sound, peak=0.6):
"""Scale sound so its loudest sample is peak."""
return sound * (peak / max(1e-9, np.abs(sound).max()))
class OneShotPlayer:
"""Plays short pre-rendered sounds inside a live voice, across blocks."""
def __init__(self):
self.active = []
def add(self, sound):
self.active.append([sound, 0])
def render(self, frameCount):
output = np.zeros(frameCount)
stillPlaying = []
for item in self.active:
sound, position = item
chunk = sound[position:position + frameCount]
output[:len(chunk)] += chunk
item[1] = position + frameCount
if item[1] < len(sound):
stillPlaying.append(item)
self.active = stillPlaying
return output
def render_voice(voice, seconds, change=None, fadeSeconds=0.05):
"""Record a live voice for some seconds, in blocks of blockSize.
change(voice, progress), if given, is called before each block with progress
from 0 towards 1, to move the voice's settings. The last fadeSeconds fade
out, so a recording cut off mid-sound does not click; pass 0 to keep the
raw end, as make_loop wants.
"""
blockCount = int(seconds * sampleRate / blockSize)
blocks = []
for index in range(blockCount):
if change is not None:
change(voice, index / blockCount)
blocks.append(voice.render(blockSize))
output = np.concatenate(blocks)
fade = int(sampleRate * fadeSeconds)
if fade > 0:
output[-fade:] *= np.linspace(1.0, 0.0, fade)
return output
def make_loop(sound, crossfadeSeconds=0.1):
"""Make a recording loop seamlessly: its end is faded into its start.
The result is crossfadeSeconds shorter than sound. The fade keeps equal
power, which suits noisy sounds such as bubbling or wind.
"""
fade = int(sampleRate * crossfadeSeconds)
if fade <= 0:
return sound.copy()
if fade * 2 > len(sound):
raise ValueError("The crossfade must be no more than half the sound.")
angles = np.linspace(0.0, math.pi / 2.0, fade)
fadeIn, fadeOut = np.sin(angles), np.cos(angles)
if sound.ndim == 2:
fadeIn, fadeOut = fadeIn[:, None], fadeOut[:, None]
loop = sound[:len(sound) - fade].copy()
loop[:fade] = sound[:fade] * fadeIn + sound[len(sound) - fade:] * fadeOut
return loop
+67
View File
@@ -0,0 +1,67 @@
"""Interface sounds: beeps, menu moves, confirmations and on/off sweeps."""
import math
import numpy as np
from .synth import sampleRate, soften, square_wave
def beep(frequency, seconds):
"""A clean beep with a touch of its octave, clickless at both ends."""
times = np.arange(int(sampleRate * seconds)) / sampleRate
envelope = np.minimum(1.0, times / 0.005) * np.minimum(1.0, (seconds - times) / 0.03)
tone = np.sin(2.0 * math.pi * frequency * times) + 0.3 * np.sin(4.0 * math.pi * frequency * times)
return 0.25 * tone * envelope
def fanfare():
"""A quick rising C major arpeggio of beeps, holding the top note."""
notes = [523.3, 659.3, 784.0, 1046.5]
parts = [beep(frequency, 0.14) for frequency in notes[:-1]] + [beep(notes[-1], 0.5)]
return np.concatenate(parts)
def toggle_sweep(rising, seconds=0.14, low=500.0, high=1000.0):
"""A short triangle tone gliding up an octave for something turning on, or down for turning off."""
times = np.arange(int(sampleRate * seconds)) / sampleRate
progress = times / seconds
if not rising:
progress = 1.0 - progress
frequency = low * (high / low) ** progress
phases = np.cumsum(frequency) / sampleRate
triangle = 2.0 * np.abs(2.0 * (phases % 1.0) - 1.0) - 1.0
envelope = np.minimum(1.0, times / 0.005) * np.minimum(1.0, (seconds - times) / 0.03)
return 0.3 * triangle * envelope
def denied_click():
"""A dull click: nothing to use, or not allowed."""
times = np.arange(int(sampleRate * 0.06)) / sampleRate
return 0.3 * np.sin(2.0 * math.pi * 180.0 * times) * np.exp(-times / 0.012)
def menu_move():
"""Moving between menu items: a short hollow knock, like tapping a bone."""
times = np.arange(int(sampleRate * 0.08)) / sampleRate
tone = np.sin(2.0 * math.pi * 620.0 * times) + 0.4 * np.sin(2.0 * math.pi * 1710.0 * times)
return 0.2 * tone * np.exp(-times / 0.018) * np.minimum(1.0, times / 0.001)
def confirm_chime(step=0):
"""Choosing or confirming: a short low square blip, then a tone an octave up that fades slowly away.
step raises it by that many semitones, so a count can be heard, such as
one step higher for each item held.
"""
lift = 2.0 ** (step / 12.0)
blip = square_wave(500.0 * lift, 0.07)
tone = square_wave(1000.0 * lift, 0.8)
# The tail falls steeply at first, then lingers quietly.
tailProgress = np.arange(len(tone)) / len(tone)
tone *= (1.0 - tailProgress) ** 2.5
chime = np.concatenate((blip, tone))
# Soften the very start and the join, so neither clicks.
attack = int(sampleRate * 0.003)
chime[:attack] *= np.linspace(0.0, 1.0, attack)
return 0.22 * soften(chime)
+158
View File
@@ -0,0 +1,158 @@
"""Vehicle sounds: skids and tyre scrubs, and live voices for road surfaces and wind.
The live voices make sound a block at a time through render(frameCount), for a
game's own live mixer; set their attributes, such as speed, between blocks.
Without a live mixer, record one with synth.render_voice, and make it loop
with synth.make_loop.
"""
import math
import numpy as np
from scipy.signal import lfilter
from .synth import Biquad, Oscillator, Ramp, blockSize, rng_from, sampleRate, sweep_filtered
def skid_spin(seed=0):
"""Stereo spin-out: a swirling skid that circles your head and slows down."""
rng = rng_from(seed)
length = int(sampleRate * 1.8)
times = np.arange(length) / sampleRate
noise = rng.standard_normal(length)
sweepFilter = Biquad("bandpass")
skid = np.zeros(length)
for blockStart in range(0, length, blockSize):
blockEnd = min(blockStart + blockSize, length)
progress = blockStart / length
centre = 2600.0 * (1.0 - progress) + 400.0 * progress
skid[blockStart:blockEnd] = sweepFilter.process(noise[blockStart:blockEnd], centre, 1.5)
skid *= np.minimum(1.0, times / 0.03) * np.exp(-times / 0.8)
# Turns slow from three a second to one as the spin dies away.
turnPhase = 2.0 * math.pi * (3.0 * times - 0.55 * times ** 2)
angles = (np.sin(turnPhase) + 1.0) * math.pi / 4.0
return 0.9 * np.column_stack((skid * np.cos(angles), skid * np.sin(angles)))
def whoosh(rising, seed=0):
"""Air rushing past, as something passes you.
Falling, for passing something that drops behind you, or rising, for
something overtaking you and pulling away ahead.
"""
rng = rng_from(seed)
length = int(sampleRate * 0.45)
times = np.arange(length) / sampleRate
noise = rng.standard_normal(length)
sweepFilter = Biquad("bandpass")
output = np.zeros(length)
for blockStart in range(0, length, blockSize):
blockEnd = min(blockStart + blockSize, length)
progress = blockStart / length
if not rising:
progress = 1.0 - progress
centre = 500.0 * (6.0 ** progress)
output[blockStart:blockEnd] = sweepFilter.process(noise[blockStart:blockEnd], centre, 1.2)
envelope = np.sin(math.pi * times / times[-1]) ** 2
return 0.8 * output * envelope
def tyre_scrub_turn(seed=0):
"""Turning round on the spot: tyres scrubbing as the sound swings from your left, past the front, to your right."""
rng = rng_from(seed)
length = int(sampleRate * 1.0)
times = np.arange(length) / sampleRate
blockCount = (length + blockSize - 1) // blockSize
# The scrub judders, like a tyre gripping and letting go as it swings round.
scrub = sweep_filtered(rng.standard_normal(length), "bandpass",
700.0 + 300.0 * np.sin(np.linspace(0.0, math.pi, blockCount)), 2.0)
judder = 0.6 + 0.4 * np.sin(2.0 * math.pi * 14.0 * times)
scrub *= judder * np.minimum(1.0, times / 0.05) * np.minimum(1.0, (times[-1] - times) / 0.15)
angles = times / times[-1] * math.pi / 2.0
return np.column_stack((scrub * np.cos(angles), scrub * np.sin(angles)))
class TyreSquealVoice:
"""A wavering squeal for tyres at the limit of grip."""
def __init__(self, seed=0):
self.rng = rng_from(seed)
self.time = 0.0
self.tone = Oscillator()
self.hissFilter = Biquad("bandpass")
def render(self, frameCount):
times = self.time + np.arange(frameCount) / sampleRate
self.time += frameCount / sampleRate
wobble = 120.0 * np.sin(2.0 * math.pi * 7.0 * times) + 60.0 * np.sin(2.0 * math.pi * 2.3 * times)
phases, _ = self.tone.advance(1300.0 + wobble)
hiss = self.hissFilter.process(self.rng.standard_normal(frameCount), 2500.0, 2.0)
return 0.3 * np.sin(2.0 * math.pi * phases) + 0.5 * hiss
class GravelVoice:
"""Crunching stones under the wheels, busier the faster you go.
speed runs from 0 (stopped) to 1 (top speed); it is loudest from a quarter speed up.
"""
def __init__(self, seed=0):
self.speed = 0.0
self.rng = rng_from(seed)
self.grainState = np.zeros(1)
self.crunchFilter = Biquad("bandpass")
self.rumbleFilter = Biquad("lowpass")
def render(self, frameCount):
speedNow = max(self.speed, 0.0)
density = 40.0 + 400.0 * speedNow
grains = (self.rng.random(frameCount) < density / sampleRate) * self.rng.uniform(0.3, 1.0, frameCount)
grainEnvelope, self.grainState = lfilter([1.0], [1.0, -0.995], grains, zi=self.grainState)
noise = self.rng.standard_normal(frameCount)
crunch = self.crunchFilter.process(noise * grainEnvelope * 0.45, 1800.0, 0.7)
rumble = self.rumbleFilter.process(self.rng.standard_normal(frameCount), 400.0, 0.7)
return (crunch + 0.3 * rumble) * min(1.0, speedNow * 4.0)
class RumbleStripVoice:
"""A thump for every strip passed, which becomes a growl at speed.
topSpeedMetres is how far the vehicle goes in a second at top speed, and
speed runs from 0 (stopped) to 1 (top speed). Strips are stripSpacing metres apart.
"""
stripSpacing = 0.7
def __init__(self, topSpeedMetres, seed=0):
self.topSpeedMetres = topSpeedMetres
self.speed = 0.0
self.rng = rng_from(seed)
self.speedRamp = Ramp(0.0)
self.strips = Oscillator()
self.body = Oscillator()
self.noiseFilter = Biquad("lowpass")
def render(self, frameCount):
speedValues = self.speedRamp.to(max(self.speed, 0.0), frameCount)
stripRate = speedValues * self.topSpeedMetres / self.stripSpacing
stripPhases, _ = self.strips.advance(stripRate)
# A very short attack keeps each thump punchy without a hard click.
envelope = np.exp(-stripPhases * 6.0) * np.minimum(1.0, stripPhases * 40.0)
bodyPhases, _ = self.body.advance(np.full(frameCount, 75.0))
noise = self.noiseFilter.process(self.rng.standard_normal(frameCount), 500.0, 0.8)
thump = 0.8 * np.sin(2.0 * math.pi * bodyPhases) + 0.6 * noise
return thump * envelope * np.minimum(1.0, speedValues * 5.0)
class WindRushVoice:
"""Air rushing past: amount runs from 0 (a low rush) to 1 (a high roar)."""
def __init__(self, seed=0):
self.rng = rng_from(seed)
self.filter = Biquad("bandpass")
self.amount = 0.0
def render(self, frameCount):
amount = min(max(self.amount, 0.0), 1.0)
noise = self.rng.standard_normal(frameCount)
return 0.6 * self.filter.process(noise, 700.0 + 1800.0 * amount, 0.8)
+24
View File
@@ -19,6 +19,29 @@ from .services import VolumeService
# Global instance for backward compatibility
volumeService = VolumeService.get_instance()
# Sounds the library itself plays, made by libstormgames.sfx when a game has no file for them.
defaultSoundNames = ("menu-move", "menu-select")
def add_default_sounds(sounds):
"""Fill in the library's own sounds, such as the menu sounds, that a game has no file for.
A game's own sound file always wins. The generated sounds need scipy;
without it, the missing sounds stay missing and are silent, as before.
"""
missing = [name for name in defaultSoundNames if name not in sounds]
if not missing or not pygame.mixer.get_init():
return sounds
try:
from .sfx import add_sounds, default_sounds
generated = default_sounds()
add_sounds(sounds, {name: generated[name] for name in missing})
except ImportError:
pass
except Exception as e:
print(f"Error making default sounds: {e}")
return sounds
class Sound:
"""Handles sound loading and playback."""
@@ -51,6 +74,7 @@ class Sound:
self.sounds[soundKey] = pygame.mixer.Sound(fullPath)
except Exception as e:
print(f"Error loading sounds: {e}")
add_default_sounds(self.sounds)
def _find_matching_sound(self, pattern):
"""Find a random sound matching the pattern."""
Binary file not shown.
+200
View File
@@ -0,0 +1,200 @@
"""Every generated sound checked by test_sfx.py, each made with fixed settings.
cases(modules) takes the loaded sfx modules by name ("synth", "impacts", ...)
and returns {case name: function making the sound}. The fingerprints in
tests/data/sfx_fingerprints.npz were made from these by
tools/update-sfx-fingerprints.py; a case changes only if its sound changes.
"""
import numpy as np
def cases(modules):
synth = modules["synth"]
impacts = modules["impacts"]
ui = modules["ui"]
rewards = modules["rewards"]
materials = modules["materials"]
creatures = modules["creatures"]
babble = modules["babble"]
vehicles = modules["vehicles"]
ambience = modules["ambience"]
alerts = modules["alerts"]
sampleRate = synth.sampleRate
blockSize = synth.blockSize
def record(voice, seconds, change=None):
return synth.render_voice(voice, seconds, change, fadeSeconds=0)
def ramp(attribute, start, end):
def change(voice, progress):
setattr(voice, attribute, start + (end - start) * progress)
return change
def warning(kind, locks):
def change(voice, progress):
voice.active = True
voice.kind = kind
voice.urgency = min(1.0, progress / 0.8)
voice.locked = locks and progress >= 0.8
return change
def inactive(voice, progress):
voice.active = False
noiseSource = np.random.default_rng(1234).standard_normal(sampleRate // 2)
sweepPhaseStep = np.linspace(50.0, 5000.0, sampleRate) / sampleRate
sweepPhases = np.cumsum(sweepPhaseStep) % 1.0
def biquad(kind, cutoff, quality):
filterObject = synth.Biquad(kind)
return np.concatenate([filterObject.process(noiseSource[start:start + blockSize], cutoff, quality)
for start in range(0, len(noiseSource), blockSize)])
def oscillator_glide():
oscillator = synth.Oscillator(0.25)
blocks = []
for index in range(40):
phases, phaseStep = oscillator.advance(np.full(blockSize, 100.0 + 40.0 * index))
blocks.append(synth.saw_wave(phases, phaseStep))
return np.concatenate(blocks)
def ramp_values():
rampObject = synth.Ramp(0.0)
return np.concatenate([rampObject.to(target, blockSize) for target in (1.0, 0.25, 0.75, 0.0)])
def knocks():
pattern = [(materials.hollow_knock(synth.note_frequency(note)), gap)
for note, gap in ((76, 0.15), (79, 0.15), (76, 0.15), (72, 0.6))]
return ambience.PatternVoice(pattern)
return {
"synth.saw_wave": lambda: synth.saw_wave(sweepPhases, sweepPhaseStep),
"synth.pulse_wave_10": lambda: synth.pulse_wave(sweepPhases, sweepPhaseStep, 0.1),
"synth.pulse_wave_50": lambda: synth.pulse_wave(sweepPhases, sweepPhaseStep, 0.5),
"synth.smooth_step": lambda: synth.smooth_step(0.2, 0.8, np.linspace(0.0, 1.0, 1000)),
"synth.ramp": ramp_values,
"synth.oscillator": oscillator_glide,
"synth.biquad_lowpass": lambda: biquad("lowpass", 800.0, 0.707),
"synth.biquad_highpass": lambda: biquad("highpass", 3000.0, 0.8),
"synth.biquad_bandpass": lambda: biquad("bandpass", 1500.0, 3.0),
"synth.sweep_filtered": lambda: synth.sweep_filtered(
noiseSource, "bandpass", np.linspace(300.0, 4000.0, (len(noiseSource) + blockSize - 1) // blockSize), 2.0),
"synth.square_wave": lambda: synth.square_wave(440.0, 0.3),
"synth.buzz_wave": lambda: synth.buzz_wave(np.linspace(200.0, 800.0, sampleRate // 2)),
"synth.glide": lambda: synth.glide(np.linspace(0.0, 1.0, 1000), [(0.0, 1.0), (0.3, 5.0), (1.0, 2.0)]),
"synth.breath_shape": lambda: synth.breath_shape(1000),
"synth.formant_filter": lambda: synth.formant_filter(synth.buzz_wave(np.full(sampleRate // 2, 300.0)),
"pinched_eh"),
"impacts.thunder": lambda: impacts.thunder(1),
"impacts.thunder_seed2": lambda: impacts.thunder(2),
"impacts.explosion": lambda: impacts.explosion(1),
"impacts.heavy_boom": lambda: impacts.heavy_boom(1),
"impacts.thud": lambda: impacts.thud(1),
"impacts.shatter": lambda: impacts.shatter(1),
"ui.beep": lambda: ui.beep(880.0, 0.15),
"ui.fanfare": ui.fanfare,
"ui.toggle_sweep_rising": lambda: ui.toggle_sweep(True),
"ui.toggle_sweep_falling": lambda: ui.toggle_sweep(False),
"ui.denied_click": ui.denied_click,
"ui.menu_move": ui.menu_move,
"ui.confirm_chime_0": lambda: ui.confirm_chime(0),
"ui.confirm_chime_3": lambda: ui.confirm_chime(3),
"ui.confirm_chime_9": lambda: ui.confirm_chime(9),
"rewards.sparkle": rewards.sparkle,
"rewards.bell_chime_1": lambda: rewards.bell_chime(1),
"rewards.bell_chime_2": lambda: rewards.bell_chime(2),
"rewards.bell_chime_3": lambda: rewards.bell_chime(3),
"rewards.beacon_blip": rewards.beacon_blip,
"rewards.power_charge": rewards.power_charge,
"rewards.bonus_run": rewards.bonus_run,
"rewards.rising_sweep": rewards.rising_sweep,
"rewards.item_spill_1": lambda: rewards.item_spill(1, 6),
"rewards.item_spill_6": lambda: rewards.item_spill(6, 6),
"rewards.item_spill_10": lambda: rewards.item_spill(10, 6),
"materials.finger_snap": lambda: materials.finger_snap(1.0, 1),
"materials.finger_snap_high": lambda: materials.finger_snap(1.12, 2),
"materials.metal_clank": lambda: materials.metal_clank(820.0, 1),
"materials.metal_clank_low": lambda: materials.metal_clank(610.0, 3),
"materials.rattle": lambda: materials.rattle(seed=1),
"materials.rattle_long": lambda: materials.rattle(0.1, 2),
"materials.squelch": lambda: materials.squelch(0.3, 220.0, 900.0, seed=5),
"materials.wet_splat": lambda: materials.wet_splat(1),
"materials.thick_splash": lambda: materials.thick_splash(1),
"materials.wooden_launch": lambda: materials.wooden_launch(1),
"creatures.horse_whinny_echo": lambda: creatures.horse_whinny(1, echo=True),
"creatures.horse_whinny_echo_seed2": lambda: creatures.horse_whinny(2, echo=True),
"creatures.horse_whinny": lambda: creatures.horse_whinny(1),
"creatures.witch_cackle_echo": lambda: creatures.witch_cackle(1, echo=True),
"creatures.witch_cackle_echo_seed2": lambda: creatures.witch_cackle(2, echo=True),
"creatures.witch_cackle": lambda: creatures.witch_cackle(1),
"babble.buzzy": lambda: babble.babble("All your candy are belong to us!", 600.0, 0.075, 0.035, "buzzy",
"coffin:All your candy are belong to us!"),
"babble.warble": lambda: babble.babble("Hello there, my pretty.", 1050.0, 0.08, 0.03, "warble",
"witch:Hello there, my pretty."),
"babble.round": lambda: babble.babble("Keep your head.", 420.0, 0.09, 0.04, "round",
"pumpkin:Keep your head."),
"babble.reedy": lambda: babble.babble("Guess my name", 1300.0, 0.05, 0.025, "reedy", "goblin:Guess my name"),
"babble.text_seed": lambda: babble.babble("Welcome back!"),
"vehicles.whoosh_falling": lambda: vehicles.whoosh(False, 1),
"vehicles.whoosh_rising": lambda: vehicles.whoosh(True, 1),
"vehicles.skid_spin": lambda: vehicles.skid_spin(1),
"vehicles.tyre_scrub_turn": lambda: vehicles.tyre_scrub_turn(1),
"vehicles.tyre_squeal": lambda: record(vehicles.TyreSquealVoice(1), 2.0),
"vehicles.gravel": lambda: record(vehicles.GravelVoice(1), 2.0, ramp("speed", 0.1, 1.0)),
"vehicles.rumble_strip": lambda: record(vehicles.RumbleStripVoice(30.0, 1), 2.0, ramp("speed", 0.1, 1.0)),
"vehicles.wind_rush": lambda: record(vehicles.WindRushVoice(1), 3.0, ramp("amount", 1.0, 0.0)),
"ambience.bubbling": lambda: record(ambience.BubblingVoice(1), 3.0),
"ambience.dripping": lambda: record(ambience.DrippingVoice(1), 4.0),
"ambience.gurgling": lambda: record(ambience.GurglingVoice(1), 4.0),
"ambience.bouncing_spring": lambda: record(ambience.BouncingSpringVoice(1), 3.0),
"ambience.ratchet": lambda: record(ambience.RatchetVoice(1), 3.0),
"ambience.pattern_knocks": lambda: record(knocks(), 3.0),
"ambience.pattern_sweep": lambda: record(ambience.PatternVoice([(rewards.rising_sweep(), 1.2)]), 3.6),
"ambience.pattern_blip": lambda: record(ambience.PatternVoice([(rewards.beacon_blip(), 0.3)]), 3.0),
"ambience.pattern_snaps": lambda: record(ambience.PatternVoice(
[(materials.finger_snap(1.0, 1), 0.22), (materials.finger_snap(1.12, 2), 0.5)]), 3.0),
"ambience.pattern_rattles": lambda: record(ambience.PatternVoice(
[(materials.rattle(seed=1), 0.13), (materials.rattle(0.1, 2), 0.47)]), 3.0),
"ambience.pattern_clanks": lambda: record(ambience.PatternVoice(
[(materials.metal_clank(820.0, 1), 0.12), (materials.metal_clank(820.0, 2), 0.12),
(materials.metal_clank(610.0, 3), 0.5)]), 3.0),
"alerts.warning_soft": lambda: record(alerts.ProximityWarningVoice(), 3.5, warning("soft", True)),
"alerts.warning_buzzy": lambda: record(alerts.ProximityWarningVoice(), 3.5, warning("buzzy", False)),
"alerts.warning_inactive": lambda: record(alerts.ProximityWarningVoice(), 0.5, inactive),
"alerts.falling_scream": lambda: record(alerts.FallingScreamVoice(1), 1.6, ramp("progress", 0.0, 1.0)),
"alerts.whistling_fall": lambda: record(alerts.WhistlingFallVoice(1), 2.0, ramp("pitchFactor", 1.2, 0.8)),
"alerts.chattering": lambda: record(alerts.ChatteringVoice(1), 2.0, ramp("pitchFactor", 1.3, 0.7)),
"synth.make_loop": lambda: synth.make_loop(record(ambience.BubblingVoice(3), 2.0), 0.2),
"synth.join": lambda: synth.join(ui.menu_move(), vehicles.tyre_scrub_turn(1)),
}
def fingerprint(sound, blockSize=512, bandCount=32):
"""A compact summary of a sound: its shape, how loud each block is, and how its energy spreads over frequency.
Two sounds with the same fingerprint, within a small tolerance, sound the same.
"""
samples = np.asarray(sound, dtype=np.float64)
if samples.ndim == 1:
samples = samples[:, None]
frameCount = len(samples)
padded = np.zeros(((frameCount + blockSize - 1) // blockSize * blockSize, samples.shape[1]))
padded[:frameCount] = samples
blocks = padded.reshape(-1, blockSize, samples.shape[1])
loudness = np.sqrt(np.mean(blocks ** 2, axis=1)).ravel()
spectrum = np.abs(np.fft.rfft(samples, axis=0)) ** 2
edges = np.unique(np.geomspace(1, len(spectrum), bandCount + 1).astype(int))
bands = np.array([spectrum[low:high].sum() for low, high in zip(edges[:-1], edges[1:])])
bands = np.sqrt(bands / max(1, frameCount))
return np.concatenate(([frameCount, samples.shape[1]], loudness, bands))
+253
View File
@@ -0,0 +1,253 @@
"""Generated sound regressions: every sound still sounds the same, and plays through pygame safely.
Run from the library root: python -m unittest discover -s tests -v
If a sound was changed on purpose, listen to it, then remake the fingerprints
with tools/update-sfx-fingerprints.py.
"""
import importlib
import os
from pathlib import Path
import sys
from types import ModuleType
import unittest
import numpy as np
os.environ.setdefault("SDL_AUDIODRIVER", "dummy")
import pygame # noqa: E402
sys.path.insert(0, str(Path(__file__).resolve().parent))
import sfx_cases # noqa: E402
libraryRoot = Path(__file__).resolve().parents[1]
moduleNames = ("synth", "impacts", "ui", "rewards", "materials", "creatures", "babble", "vehicles", "ambience",
"alerts")
def load_sfx():
packageName = "_sfx_test_library"
if packageName not in sys.modules:
package = ModuleType(packageName)
package.__path__ = [str(libraryRoot)]
sys.modules[packageName] = package
sfx = importlib.import_module(f"{packageName}.sfx")
modules = {name: importlib.import_module(f"{packageName}.sfx.{name}") for name in moduleNames}
return sfx, modules
class SoundsUnchangedTests(unittest.TestCase):
def test_every_sound_matches_its_fingerprint(self):
_, modules = load_sfx()
cases = sfx_cases.cases(modules)
with np.load(libraryRoot / "tests" / "data" / "sfx_fingerprints.npz") as stored:
self.assertEqual(sorted(stored.files), sorted(cases), "Every case needs a fingerprint, and no more.")
for name, make in cases.items():
with self.subTest(sound=name):
actual = sfx_cases.fingerprint(make())
expected = stored[name]
self.assertEqual(actual.shape, expected.shape, "The sound's length or channels changed.")
np.testing.assert_allclose(actual, expected, rtol=1e-4, atol=1e-7)
def test_every_sound_is_finite_and_repeatable(self):
_, modules = load_sfx()
for name, make in sfx_cases.cases(modules).items():
with self.subTest(sound=name):
first = make()
self.assertTrue(np.isfinite(first).all())
np.testing.assert_array_equal(first, make())
def test_fingerprint_notices_a_small_change(self):
_, modules = load_sfx()
sound = modules["impacts"].thunder(1)
louder = sound * 1.01
self.assertFalse(np.allclose(sfx_cases.fingerprint(sound), sfx_cases.fingerprint(louder),
rtol=1e-4, atol=1e-7))
class SeedTests(unittest.TestCase):
def test_default_seed_is_fixed_and_other_seeds_vary(self):
_, modules = load_sfx()
impacts = modules["impacts"]
np.testing.assert_array_equal(impacts.explosion(), impacts.explosion())
self.assertFalse(np.array_equal(impacts.explosion(0), impacts.explosion(1)))
def test_no_seed_gives_a_new_variant(self):
_, modules = load_sfx()
impacts = modules["impacts"]
self.assertFalse(np.array_equal(impacts.thud(None), impacts.thud(None)))
def test_a_shared_generator_moves_on(self):
_, modules = load_sfx()
materials = modules["materials"]
rng = np.random.default_rng(4)
first = materials.squelch(0.2, 200.0, 800.0, seed=rng)
second = materials.squelch(0.2, 200.0, 800.0, seed=rng)
self.assertFalse(np.array_equal(first, second))
class LoopTests(unittest.TestCase):
def test_loop_is_shorter_by_the_crossfade_and_joins_smoothly(self):
_, modules = load_sfx()
synth = modules["synth"]
sound = synth.render_voice(modules["ambience"].BubblingVoice(2), 2.0, fadeSeconds=0)
loop = synth.make_loop(sound, 0.1)
fade = int(synth.sampleRate * 0.1)
self.assertEqual(len(loop), len(sound) - fade)
# Round the loop, the last sample runs straight into the first: both come from neighbouring raw samples.
self.assertAlmostEqual(loop[-1], sound[len(sound) - fade - 1])
self.assertAlmostEqual(loop[0], sound[len(sound) - fade])
def test_stereo_loop_keeps_its_channels(self):
_, modules = load_sfx()
synth = modules["synth"]
loop = synth.make_loop(modules["vehicles"].skid_spin(1), 0.05)
self.assertEqual(loop.ndim, 2)
self.assertEqual(loop.shape[1], 2)
def test_crossfade_longer_than_half_is_refused(self):
_, modules = load_sfx()
synth = modules["synth"]
with self.assertRaises(ValueError):
synth.make_loop(np.zeros(1000), 0.02)
def test_render_voice_fades_its_end_unless_asked_not_to(self):
_, modules = load_sfx()
synth = modules["synth"]
faded = synth.render_voice(modules["vehicles"].WindRushVoice(1), 0.5)
raw = synth.render_voice(modules["vehicles"].WindRushVoice(1), 0.5, fadeSeconds=0)
self.assertEqual(faded[-1], 0.0)
self.assertNotEqual(raw[-1], 0.0)
class BabbleTests(unittest.TestCase):
def test_same_line_same_tune_and_seed_key_changes_it(self):
_, modules = load_sfx()
babble = modules["babble"]
np.testing.assert_array_equal(babble.babble("Hello there"), babble.babble("Hello there"))
self.assertFalse(np.array_equal(babble.babble("Hello there"), babble.babble("Hello there", seedKey="other")))
def test_unknown_wave_is_refused(self):
_, modules = load_sfx()
with self.assertRaises(ValueError):
modules["babble"].babble("Hello", wave="square")
class PygameTests(unittest.TestCase):
def tearDown(self):
pygame.mixer.quit()
def start_mixer(self, frequency=44100, size=-16, channels=2):
pygame.mixer.quit()
pygame.mixer.init(frequency, size, channels)
return pygame.mixer.get_init()
def test_without_a_mixer_it_says_so(self):
sfx, modules = load_sfx()
pygame.mixer.quit()
with self.assertRaises(RuntimeError):
sfx.make_sound(modules["ui"].menu_move())
def test_mono_sound_plays_in_both_channels_at_its_level(self):
sfx, modules = load_sfx()
self.start_mixer()
sound = modules["ui"].menu_move()
samples = pygame.sndarray.array(sfx.make_sound(sound))
self.assertEqual(samples.dtype, np.int16)
self.assertEqual(samples.shape, (len(sound), 2))
np.testing.assert_array_equal(samples[:, 0], samples[:, 1])
np.testing.assert_allclose(samples[:, 0], np.round(sound * 32767.0), atol=1)
def test_stereo_sound_keeps_its_sides(self):
sfx, modules = load_sfx()
self.start_mixer()
sound = modules["vehicles"].tyre_scrub_turn(1)
samples = pygame.sndarray.array(sfx.make_sound(sound))
np.testing.assert_allclose(samples, np.round(sound * 32767.0), atol=1)
def test_sound_past_full_scale_is_turned_down_to_fit_and_quieter_ones_are_left_alone(self):
sfx, modules = load_sfx()
self.start_mixer()
loud = sfx.make_sound(np.array([0.0, 1.5, -3.0, 0.75]))
samples = pygame.sndarray.array(loud)[:, 0]
np.testing.assert_array_equal(samples, np.round(np.array([0.0, 0.5, -1.0, 0.25]) * 32767.0))
quiet = pygame.sndarray.array(sfx.make_sound(np.array([0.0, 0.25, -0.5])))[:, 0]
np.testing.assert_array_equal(quiet, np.round(np.array([0.0, 0.25, -0.5]) * 32767.0))
def test_other_mixer_rate_keeps_the_length_in_seconds(self):
sfx, modules = load_sfx()
setup = self.start_mixer(frequency=22050)
sound = modules["ui"].confirm_chime()
made = sfx.make_sound(sound)
self.assertEqual(len(pygame.sndarray.array(made)), round(len(sound) * setup[0] / 44100))
self.assertAlmostEqual(made.get_length(), len(sound) / 44100, places=3)
def test_mono_mixer_gets_a_mono_sound(self):
sfx, modules = load_sfx()
self.start_mixer(channels=1)
samples = pygame.sndarray.array(sfx.make_sound(modules["vehicles"].skid_spin(1)))
self.assertEqual(samples.ndim, 1)
def test_add_sounds_keeps_file_sounds_unless_replacing(self):
sfx, modules = load_sfx()
self.start_mixer()
fromFile = sfx.make_sound(np.zeros(10))
sounds = {"thunder": fromFile}
made = []
def thunder():
made.append(True)
return modules["impacts"].thunder()
sfx.add_sounds(sounds, {"thunder": thunder, "click": modules["ui"].denied_click})
self.assertIs(sounds["thunder"], fromFile)
self.assertEqual(made, [], "A sound already there is not made at all.")
self.assertIn("click", sounds)
sfx.add_sounds(sounds, {"thunder": thunder}, replace=True)
self.assertIsNot(sounds["thunder"], fromFile)
def test_default_sounds_are_the_menu_sounds(self):
sfx, _ = load_sfx()
self.start_mixer()
sounds = sfx.add_sounds({}, sfx.default_sounds())
self.assertEqual(sorted(sounds), ["menu-move", "menu-select"])
class DefaultSoundTests(unittest.TestCase):
def setUp(self):
load_sfx()
self.sound = importlib.import_module("_sfx_test_library.sound")
def tearDown(self):
pygame.mixer.quit()
def test_names_match_what_sfx_makes(self):
sfx, _ = load_sfx()
self.assertEqual(sorted(self.sound.defaultSoundNames), sorted(sfx.default_sounds()))
def test_missing_menu_sounds_are_filled_in(self):
pygame.mixer.init(44100, -16, 2)
sounds = self.sound.add_default_sounds({})
self.assertEqual(sorted(sounds), ["menu-move", "menu-select"])
self.assertIsInstance(sounds["menu-select"], pygame.mixer.Sound)
def test_game_files_win(self):
pygame.mixer.init(44100, -16, 2)
fromFile = pygame.mixer.Sound(buffer=bytes(400))
sounds = self.sound.add_default_sounds({"menu-select": fromFile})
self.assertIs(sounds["menu-select"], fromFile)
self.assertIn("menu-move", sounds)
def test_nothing_is_made_without_a_mixer(self):
pygame.mixer.quit()
self.assertEqual(self.sound.add_default_sounds({}), {})
def test_sound_class_fills_them_in_after_loading_files(self):
pygame.mixer.init(44100, -16, 2)
loaded = self.sound.Sound(soundDir=str(libraryRoot / "tests" / "no-such-sounds"))
self.assertEqual(sorted(loaded.sounds), ["menu-move", "menu-select"])
if __name__ == "__main__":
unittest.main()
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env python3
"""Remake tests/data/sfx_fingerprints.npz from the sounds the library makes now.
Run this only after listening to a sound that was changed on purpose, since it
makes the tests accept whatever the generators make now. From the library root:
python tools/update-sfx-fingerprints.py
"""
import importlib
from pathlib import Path
import sys
from types import ModuleType
import numpy as np
libraryRoot = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(libraryRoot / "tests"))
import sfx_cases # noqa: E402
moduleNames = ("synth", "impacts", "ui", "rewards", "materials", "creatures", "babble", "vehicles", "ambience",
"alerts")
def load_modules():
packageName = "_sfx_fingerprint_library"
package = ModuleType(packageName)
package.__path__ = [str(libraryRoot)]
sys.modules[packageName] = package
return {name: importlib.import_module(f"{packageName}.sfx.{name}") for name in moduleNames}
def main():
cases = sfx_cases.cases(load_modules())
prints = {name: sfx_cases.fingerprint(make()) for name, make in cases.items()}
outputPath = libraryRoot / "tests" / "data" / "sfx_fingerprints.npz"
np.savez_compressed(outputPath, **prints)
print(f"Wrote fingerprints of {len(prints)} sounds to {outputPath}")
if __name__ == "__main__":
main()