Play generated music through play_bgm, just like a music file

sfx.make_music turns a generated sound into the bytes of a WAV file, and
play_bgm (the global function, the Sound method and the Game method) now
takes those bytes as well as a file's path. The music is loaded into
pygame's music player from memory, so everything that already works on
background music works on generated music unchanged: looping, pausing and
fading for dialogue and menus, and the music volume.

Like make_sound, make_music turns down only music that would go past full
scale. It needs no mixer, so music can be made while a game loads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Storm DragonandClaude Opus 5.5 committed 2026-11-28 20:33:15 -05:00
1 parent ec82210ea6
commit 00db02b236
4 files changed
+105 -6

No files matched your search

+32 -1
View File
@@ -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("<i2"))
output = io.BytesIO()
with wave.open(output, "wb") as wavFile:
wavFile.setnchannels(samples.shape[1])
wavFile.setsampwidth(2)
wavFile.setframerate(sampleRate)
wavFile.writeframes(data.tobytes())
return output.getvalue()
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.