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:
1 parent
ec82210ea6
commit
00db02b236
4 files changed
+105
-6
No files matched your search
+32
-1
@@ -12,7 +12,8 @@ same seed always gives the same samples.
|
|||||||
sounds["thunder"].play()
|
sounds["thunder"].play()
|
||||||
|
|
||||||
Generators return numpy arrays of float samples at sfx.synth.sampleRate, and
|
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:
|
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.
|
this package, so a game that does not use it does not need scipy.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import io
|
||||||
|
import wave
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pygame
|
import pygame
|
||||||
|
|
||||||
@@ -88,6 +92,33 @@ def make_sound(sound, volume=1.0):
|
|||||||
return pygame.sndarray.make_sound(np.ascontiguousarray(data))
|
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):
|
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.
|
"""Add generated sounds to a game's sounds by name; a sound already there, such as from a file, is kept.
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ Provides functionality for:
|
|||||||
- Volume controls
|
- Volume controls
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import io
|
||||||
import os
|
import os
|
||||||
import pygame
|
import pygame
|
||||||
import random
|
import random
|
||||||
@@ -291,10 +292,14 @@ class Sound:
|
|||||||
return channel
|
return channel
|
||||||
|
|
||||||
def play_bgm(self, musicFile):
|
def play_bgm(self, musicFile):
|
||||||
"""Play background music with proper volume settings."""
|
"""Play background music with proper volume settings.
|
||||||
|
|
||||||
|
musicFile is a music file's path, or the bytes of a WAV file such as
|
||||||
|
libstormgames.sfx.make_music makes from generated music.
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
pygame.mixer.music.stop()
|
pygame.mixer.music.stop()
|
||||||
pygame.mixer.music.load(musicFile)
|
_load_bgm(musicFile)
|
||||||
pygame.mixer.music.set_volume(self.volumeService.get_bgm_volume())
|
pygame.mixer.music.set_volume(self.volumeService.get_bgm_volume())
|
||||||
pygame.mixer.music.play(-1)
|
pygame.mixer.music.play(-1)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -446,12 +451,31 @@ def get_available_channel():
|
|||||||
"""Get an available channel for playing sounds."""
|
"""Get an available channel for playing sounds."""
|
||||||
return pygame.mixer.find_channel()
|
return pygame.mixer.find_channel()
|
||||||
|
|
||||||
|
# The music being played from memory, kept here so pygame can go on reading it.
|
||||||
|
_bgmData = None
|
||||||
|
|
||||||
|
|
||||||
|
def _load_bgm(musicFile):
|
||||||
|
"""Load background music from a file's path, or from the bytes of a WAV file."""
|
||||||
|
global _bgmData
|
||||||
|
if isinstance(musicFile, (bytes, bytearray, memoryview)):
|
||||||
|
_bgmData = io.BytesIO(bytes(musicFile))
|
||||||
|
pygame.mixer.music.load(_bgmData, "wav")
|
||||||
|
else:
|
||||||
|
pygame.mixer.music.load(musicFile)
|
||||||
|
_bgmData = None
|
||||||
|
|
||||||
|
|
||||||
# Global functions for backward compatibility
|
# Global functions for backward compatibility
|
||||||
def play_bgm(musicFile):
|
def play_bgm(musicFile):
|
||||||
"""Play background music with proper volume settings."""
|
"""Play background music with proper volume settings.
|
||||||
|
|
||||||
|
musicFile is a music file's path, or the bytes of a WAV file such as
|
||||||
|
libstormgames.sfx.make_music makes from generated music.
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
pygame.mixer.music.stop()
|
pygame.mixer.music.stop()
|
||||||
pygame.mixer.music.load(musicFile)
|
_load_bgm(musicFile)
|
||||||
pygame.mixer.music.set_volume(volumeService.get_bgm_volume())
|
pygame.mixer.music.set_volume(volumeService.get_bgm_volume())
|
||||||
pygame.mixer.music.play(-1)
|
pygame.mixer.music.play(-1)
|
||||||
except: pass
|
except: pass
|
||||||
|
|||||||
@@ -7,11 +7,13 @@ with tools/update-sfx-fingerprints.py.
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import importlib
|
import importlib
|
||||||
|
import io
|
||||||
import os
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import sys
|
import sys
|
||||||
from types import ModuleType
|
from types import ModuleType
|
||||||
import unittest
|
import unittest
|
||||||
|
import wave
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
@@ -22,6 +24,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|||||||
import sfx_cases # noqa: E402
|
import sfx_cases # noqa: E402
|
||||||
|
|
||||||
libraryRoot = Path(__file__).resolve().parents[1]
|
libraryRoot = Path(__file__).resolve().parents[1]
|
||||||
|
sampleRateForTests = 44100
|
||||||
moduleNames = ("synth", "impacts", "ui", "rewards", "materials", "creatures", "babble", "vehicles", "ambience",
|
moduleNames = ("synth", "impacts", "ui", "rewards", "materials", "creatures", "babble", "vehicles", "ambience",
|
||||||
"alerts", "movement")
|
"alerts", "movement")
|
||||||
|
|
||||||
@@ -249,5 +252,45 @@ class DefaultSoundTests(unittest.TestCase):
|
|||||||
self.assertEqual(sorted(loaded.sounds), ["menu-move", "menu-select"])
|
self.assertEqual(sorted(loaded.sounds), ["menu-move", "menu-select"])
|
||||||
|
|
||||||
|
|
||||||
|
class MusicPlaybackTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.sfx, _ = load_sfx()
|
||||||
|
self.sound = importlib.import_module("_sfx_test_library.sound")
|
||||||
|
times = np.arange(int(sampleRateForTests * 0.5)) / sampleRateForTests
|
||||||
|
tone = 0.4 * np.sin(2.0 * np.pi * 440.0 * times)
|
||||||
|
self.stereo = np.column_stack((tone, -tone))
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
pygame.mixer.quit()
|
||||||
|
|
||||||
|
def test_make_music_is_a_wav_file_at_the_generated_rate(self):
|
||||||
|
data = self.sfx.make_music(self.stereo)
|
||||||
|
with wave.open(io.BytesIO(data)) as wavFile:
|
||||||
|
self.assertEqual(wavFile.getnchannels(), 2)
|
||||||
|
self.assertEqual(wavFile.getsampwidth(), 2)
|
||||||
|
self.assertEqual(wavFile.getframerate(), sampleRateForTests)
|
||||||
|
frames = np.frombuffer(wavFile.readframes(wavFile.getnframes()), dtype="<i2").reshape(-1, 2)
|
||||||
|
self.assertEqual(len(frames), len(self.stereo))
|
||||||
|
np.testing.assert_allclose(frames / 32767.0, self.stereo, atol=1.0 / 32767.0)
|
||||||
|
|
||||||
|
def test_make_music_turns_down_only_music_past_full_scale(self):
|
||||||
|
with wave.open(io.BytesIO(self.sfx.make_music(self.stereo * 5.0))) as wavFile:
|
||||||
|
frames = np.frombuffer(wavFile.readframes(wavFile.getnframes()), dtype="<i2")
|
||||||
|
self.assertEqual(np.abs(frames).max(), 32767)
|
||||||
|
|
||||||
|
def test_play_bgm_plays_generated_music_like_a_file(self):
|
||||||
|
pygame.mixer.init(48000, -16, 2)
|
||||||
|
data = self.sfx.make_music(self.stereo)
|
||||||
|
for play in (self.sound.play_bgm, self.sound.Sound(soundDir=str(libraryRoot / "tests" / "no-sounds")).play_bgm):
|
||||||
|
with self.subTest(play=play):
|
||||||
|
play(data)
|
||||||
|
self.assertTrue(pygame.mixer.music.get_busy())
|
||||||
|
pygame.mixer.music.pause()
|
||||||
|
self.assertFalse(pygame.mixer.music.get_busy())
|
||||||
|
pygame.mixer.music.unpause()
|
||||||
|
self.assertTrue(pygame.mixer.music.get_busy())
|
||||||
|
pygame.mixer.music.stop()
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
@@ -232,7 +232,8 @@ class Game:
|
|||||||
"""Play background music.
|
"""Play background music.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
musicFile (str): Path to music file
|
musicFile (str or bytes): Path to music file, or the bytes of a WAV file such as
|
||||||
|
libstormgames.sfx.make_music makes from generated music
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Game: Self for method chaining
|
Game: Self for method chaining
|
||||||
|
|||||||
Reference in new issue
Block a user