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