diff --git a/sfx/__init__.py b/sfx/__init__.py index 7aef85c..70f6b63 100644 --- a/sfx/__init__.py +++ b/sfx/__init__.py @@ -12,7 +12,8 @@ same seed always gives the same samples. 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. +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: @@ -32,6 +33,9 @@ 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 @@ -88,6 +92,33 @@ def make_sound(sound, volume=1.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("