99 lines
3.2 KiB
Python
99 lines
3.2 KiB
Python
"""Procedural sound effects via pygame.mixer.
|
|
|
|
A handful of short tones are synthesized in memory with stdlib ``array`` (no
|
|
asset files). Audio is feedback only: it never mutates game state and never
|
|
blocks input. If the mixer cannot initialize (no device, headless run) the
|
|
engine degrades to silent no-ops and never raises.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import array
|
|
import math
|
|
from typing import Any
|
|
|
|
import pygame
|
|
|
|
_FREQ = 22050
|
|
_SIZE = -16 # 16-bit signed
|
|
_CHANNELS = 1
|
|
_BUFFER = 256
|
|
|
|
# (base_freq_hz, duration_ms, volume, sweep_to_freq). sweep 0 => steady tone.
|
|
_SFX: dict[str, tuple[int, int, float, int]] = {
|
|
"hit": (330, 70, 0.35, 180),
|
|
"crit": (660, 110, 0.45, 990),
|
|
"miss": (200, 60, 0.20, 120),
|
|
"damage": (140, 120, 0.40, 70),
|
|
"pickup": (520, 70, 0.30, 780),
|
|
"use": (700, 90, 0.30, 520),
|
|
"stairs": (440, 140, 0.35, 880),
|
|
"levelup": (523, 220, 0.40, 1046),
|
|
"death": (300, 420, 0.45, 70),
|
|
"victory": (523, 480, 0.45, 1568),
|
|
"menu": (600, 50, 0.22, 600),
|
|
}
|
|
|
|
|
|
def _synth(freq: int, ms: int, volume: float, sweep: int) -> bytes:
|
|
n = max(1, int(_FREQ * ms / 1000))
|
|
buf = array.array("h")
|
|
for i in range(n):
|
|
t = i / _FREQ
|
|
f = freq + (sweep - freq) * (i / n) if sweep else freq
|
|
env = (1.0 - i / n) ** 1.2 # quick decay envelope
|
|
val = int(volume * 32767 * env * math.sin(2 * math.pi * f * t))
|
|
buf.append(max(-32768, min(32767, val)))
|
|
return buf.tobytes()
|
|
|
|
|
|
class AudioEngine:
|
|
"""Tiny SFX player. Silent and raise-free when no audio device is present."""
|
|
|
|
def __init__(self, enabled: bool = True) -> None:
|
|
self.muted: bool = False
|
|
self.available: bool = False
|
|
self._sounds: dict[str, Any] = {}
|
|
if not enabled:
|
|
return
|
|
# Always attempt init ourselves so a forced failure (e.g. a monkeypatched
|
|
# pygame.mixer.init that raises) is observed here, not masked by an
|
|
# earlier pygame.init() that may have quietly succeeded.
|
|
try:
|
|
pygame.mixer.init(frequency=_FREQ, size=_SIZE, channels=_CHANNELS, buffer=_BUFFER)
|
|
except Exception:
|
|
self.available = False
|
|
return
|
|
try:
|
|
for name, (f, ms, vol, sweep) in _SFX.items():
|
|
self._sounds[name] = pygame.mixer.Sound(buffer=_synth(f, ms, vol, sweep))
|
|
self.available = True
|
|
except Exception:
|
|
# Mixer init'd but Sound creation failed: stay silent, stay safe.
|
|
self._sounds = {}
|
|
self.available = False
|
|
|
|
def play(self, name: str) -> None:
|
|
if not self.available or self.muted:
|
|
return
|
|
snd = self._sounds.get(name) or self._sounds.get("hit")
|
|
if snd is None:
|
|
return
|
|
try:
|
|
snd.play()
|
|
except Exception:
|
|
pass # audio is best-effort; never propagate a playback error
|
|
|
|
def toggle_mute(self) -> bool:
|
|
self.muted = not self.muted
|
|
return self.muted
|
|
|
|
|
|
if __name__ == "__main__":
|
|
pygame.init()
|
|
eng = AudioEngine(enabled=True)
|
|
print("available:", eng.available, "muted:", eng.muted)
|
|
eng.play("hit")
|
|
eng.toggle_mute()
|
|
print("toggled mute ->", eng.muted)
|
|
pygame.quit()
|