"""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