| 1 |
"""Audio wrapper module. |
| 2 |
|
| 3 |
Can use SDL, pyglet, pyo or wx. |
| 4 |
pyglet or SDL will be used by default if available. |
| 5 |
pyglet can only be used if version >= 1.2.2 is available. |
| 6 |
pyo is still buggy under Linux and has a few quirks under Windows. |
| 7 |
wx doesn't support fading, changing volume, multiple concurrent sounds, |
| 8 |
and only supports wav format. |
| 9 |
|
| 10 |
Example: |
| 11 |
sound = Sound("test.wav", loop=True) |
| 12 |
sound.Play(fade_ms=1000) |
| 13 |
""" |
| 14 |
|
| 15 |
from __future__ import annotations |
| 16 |
|
| 17 |
import atexit |
| 18 |
import contextlib |
| 19 |
import ctypes.util |
| 20 |
import os |
| 21 |
import sys |
| 22 |
import threading |
| 23 |
import time |
| 24 |
from ctypes import ( |
| 25 |
POINTER, |
| 26 |
Structure, |
| 27 |
c_int, |
| 28 |
c_uint8, |
| 29 |
c_uint16, |
| 30 |
c_uint32, |
| 31 |
) |
| 32 |
from typing import TYPE_CHECKING, ClassVar |
| 33 |
|
| 34 |
if sys.platform == "win32": |
| 35 |
try: |
| 36 |
import pywintypes |
| 37 |
import win32api |
| 38 |
except ImportError: |
| 39 |
win32api = None |
| 40 |
|
| 41 |
from DisplayCAL.config import PYDIR |
| 42 |
from DisplayCAL.util_os import dlopen, getenvu |
| 43 |
from DisplayCAL.util_str import safe_str |
| 44 |
|
| 45 |
if TYPE_CHECKING: |
| 46 |
import pyglet.media # noqa: TC004 |
| 47 |
import pyo # noqa: TC004 |
| 48 |
import sdl # noqa: TC004 |
| 49 |
import sdl2 # noqa: TC004 |
| 50 |
import wx |
| 51 |
|
| 52 |
|
| 53 |
# Workaround for pyglet crash on exit |
| 54 |
try: |
| 55 |
import pyglet |
| 56 |
except ImportError: |
| 57 |
pass |
| 58 |
else: |
| 59 |
|
| 60 |
def _pyglet_cleanup(): |
| 61 |
with contextlib.suppress(Exception): |
| 62 |
for ch in list(_CH.values()): |
| 63 |
if hasattr(ch, "delete"): |
| 64 |
ch.delete() |
| 65 |
# Only touch the audio driver when pyglet.media was actually |
| 66 |
# imported during this session. Calling get_audio_driver() when |
| 67 |
# the module is absent would initialize (and immediately tear down) |
| 68 |
# the driver, which crashes on macOS via Swift/AVFoundation during |
| 69 |
# atexit. |
| 70 |
if "pyglet.media" not in sys.modules: |
| 71 |
return |
| 72 |
driver = pyglet.media.get_audio_driver() |
| 73 |
if driver: |
| 74 |
driver.delete() |
| 75 |
|
| 76 |
atexit.register(_pyglet_cleanup) |
| 77 |
|
| 78 |
|
| 79 |
_CH = {} |
| 80 |
_INITIALIZED = False |
| 81 |
_LIB = None |
| 82 |
_LIB_VERSION = None |
| 83 |
_SERVER = None |
| 84 |
_SND = {} |
| 85 |
_SOUNDS = {} |
| 86 |
|
| 87 |
# Loaded SDL library (set by the _init_sdl_* helpers, read by the Sound class). |
| 88 |
sdl = None |
| 89 |
|
| 90 |
SDL_INIT_AUDIO = 16 |
| 91 |
AUDIO_S16LSB = 0x8010 |
| 92 |
AUDIO_S16MSB = 0x9010 |
| 93 |
MIX_DEFAULT_FORMAT = AUDIO_S16LSB if sys.byteorder == "little" else AUDIO_S16MSB |
| 94 |
|
| 95 |
|
| 96 |
def init( |
| 97 |
lib: None | str = None, |
| 98 |
samplerate: int = 22050, |
| 99 |
channels: int = 2, |
| 100 |
buffersize: int = 2048, |
| 101 |
reinit: str = False, |
| 102 |
) -> None | pyglet.media | pyo.Server | sdl.Mixer | sdl2.Mixer | wx.Sound: |
| 103 |
"""(Re-)Initialize sound subsystem. |
| 104 |
|
| 105 |
Args: |
| 106 |
lib (str): The audio library to use (e.g., "SDL", "pyglet", "pyo", "wx"). |
| 107 |
samplerate (int): The sample rate to use. |
| 108 |
channels (int): The number of audio channels. |
| 109 |
buffersize (int): The size of the audio buffer. |
| 110 |
reinit (bool): Whether to reinitialize the sound subsystem. |
| 111 |
|
| 112 |
Returns: |
| 113 |
None | pyglet.media | pyo.Server | sdl.Mixer | sdl2.Mixer | wx.Sound: |
| 114 |
The initialized audio library or None if no suitable library was found. |
| 115 |
""" |
| 116 |
# Note on buffer size: Too high values cause crackling during fade, too low |
| 117 |
# values cause choppy playback of ogg files when using pyo (good value for |
| 118 |
# pyo is >= 2048) |
| 119 |
global _INITIALIZED, _LIB, _LIB_VERSION, _SERVER, pyglet, pyo, sdl, wx |
| 120 |
if _INITIALIZED and not reinit: |
| 121 |
# To re-initialize, explicitly set reinit to True |
| 122 |
return None |
| 123 |
# Select the audio library we're going to use. |
| 124 |
# User choice or SDL > pyglet > pyo > wx |
| 125 |
if not lib: |
| 126 |
if sys.platform in ("darwin", "win32"): |
| 127 |
# Mac OS X, Windows |
| 128 |
libs = ("pyglet", "SDL", "pyo", "wx") |
| 129 |
else: |
| 130 |
# Linux |
| 131 |
libs = ("SDL", "pyglet", "pyo", "wx") |
| 132 |
|
| 133 |
audio_lib = None |
| 134 |
for lib_ in libs: |
| 135 |
try: |
| 136 |
audio_lib = init(lib_, samplerate, channels, buffersize, reinit) |
| 137 |
break |
| 138 |
except Exception: |
| 139 |
pass |
| 140 |
|
| 141 |
if not audio_lib: |
| 142 |
raise RuntimeError("No suitable audio library found!") |
| 143 |
return audio_lib |
| 144 |
|
| 145 |
if lib == "pyglet": |
| 146 |
_init_pyglet() |
| 147 |
elif lib == "pyo": |
| 148 |
_init_pyo(samplerate, channels, buffersize) |
| 149 |
elif lib == "SDL": |
| 150 |
_init_sdl(samplerate, channels, buffersize) |
| 151 |
elif lib == "wx": |
| 152 |
_init_wx() |
| 153 |
if not _LIB: |
| 154 |
raise RuntimeError("No audio library available") |
| 155 |
_INITIALIZED = True |
| 156 |
return _SERVER |
| 157 |
|
| 158 |
|
| 159 |
def _init_wx() -> None: |
| 160 |
"""Initialize wx audio subsystem.""" |
| 161 |
global _SERVER, _LIB, _LIB_VERSION, wx |
| 162 |
try: |
| 163 |
import wx |
| 164 |
|
| 165 |
_LIB = "wx" |
| 166 |
except ImportError: |
| 167 |
_LIB = None |
| 168 |
else: |
| 169 |
_SERVER = wx |
| 170 |
_LIB_VERSION = wx.__version__ |
| 171 |
|
| 172 |
|
| 173 |
def _load_audio_dll( |
| 174 |
sdl: None | sdl.Mixer | sdl2.Mixer, |
| 175 |
samplerate: int, |
| 176 |
channels: int, |
| 177 |
buffersize: int, |
| 178 |
libname: str, |
| 179 |
libfn: str | None, |
| 180 |
handle: None | int | str = None, |
| 181 |
) -> None | sdl.Mixer | sdl2.Mixer: |
| 182 |
"""Load the audio DLL. |
| 183 |
|
| 184 |
Args: |
| 185 |
sdl (None | sdl.Mixer | sdl2.Mixer): The SDL audio library to use. |
| 186 |
samplerate (int): The sample rate to use. |
| 187 |
channels (int): The number of audio channels. |
| 188 |
buffersize (int): The size of the audio buffer. |
| 189 |
libname (str): The name of the audio library. |
| 190 |
libfn (str | None): The filename of the audio library. |
| 191 |
handle (None | int | str): The handle to the loaded library. |
| 192 |
|
| 193 |
Returns: |
| 194 |
None | sdl.Mixer | sdl2.Mixer: The loaded SDL audio library or None if |
| 195 |
the library could not be loaded. |
| 196 |
""" |
| 197 |
global _SERVER, _LIB, _LIB_VERSION, _INITIALIZED |
| 198 |
dll = dlopen(libfn, handle=handle) |
| 199 |
if dll: |
| 200 |
print(f"{libname}:", libfn) |
| 201 |
if libname.endswith("_mixer"): |
| 202 |
if not dll: |
| 203 |
return None |
| 204 |
if not sdl: |
| 205 |
raise RuntimeError("SDL library not loaded") |
| 206 |
sdl.SDL_RWFromFile.restype = POINTER(SDL_RWops) |
| 207 |
_SERVER = dll |
| 208 |
_SERVER.Mix_OpenAudio.argtypes = [c_int, c_uint16, c_int, c_int] |
| 209 |
_SERVER.Mix_LoadWAV_RW.argtypes = [POINTER(SDL_RWops), c_int] |
| 210 |
_SERVER.Mix_LoadWAV_RW.restype = POINTER(Mix_Chunk) |
| 211 |
_SERVER.Mix_PlayChannelTimed.argtypes = [ |
| 212 |
c_int, |
| 213 |
POINTER(Mix_Chunk), |
| 214 |
c_int, |
| 215 |
c_int, |
| 216 |
] |
| 217 |
_SERVER.Mix_VolumeChunk.argtypes = [POINTER(Mix_Chunk), c_int] |
| 218 |
if _INITIALIZED: |
| 219 |
_SERVER.Mix_Quit() |
| 220 |
sdl.SDL_Quit() |
| 221 |
sdl.SDL_Init(SDL_INIT_AUDIO) |
| 222 |
_SERVER.Mix_OpenAudio(samplerate, MIX_DEFAULT_FORMAT, channels, buffersize) |
| 223 |
_LIB = "SDL" |
| 224 |
_LIB_VERSION = "2.0" if libname.startswith("SDL2") else "1.2" |
| 225 |
return sdl |
| 226 |
sdl = dll |
| 227 |
_SERVER = None |
| 228 |
return sdl |
| 229 |
|
| 230 |
|
| 231 |
def _init_sdl_windows(samplerate: int, channels: int, buffersize: int) -> None: |
| 232 |
"""Initialize SDL on Windows. |
| 233 |
|
| 234 |
Args: |
| 235 |
samplerate (int): The sample rate to use. |
| 236 |
channels (int): The number of audio channels. |
| 237 |
buffersize (int): The size of the audio buffer. |
| 238 |
""" |
| 239 |
global _SERVER, sdl |
| 240 |
sdl = None |
| 241 |
pth = getenvu("PATH") |
| 242 |
libpth = os.path.join(PYDIR, "lib") |
| 243 |
if not pth.startswith(libpth + os.pathsep): |
| 244 |
pth = libpth + os.pathsep + pth |
| 245 |
os.environ["PATH"] = safe_str(pth) |
| 246 |
for libname in ("SDL2", "SDL2_mixer", "SDL", "SDL_mixer"): |
| 247 |
handle = None |
| 248 |
libfn = ctypes.util.find_library(libname) |
| 249 |
if libfn and win32api: |
| 250 |
# Support for unicode paths |
| 251 |
libfn = str(libfn) |
| 252 |
with contextlib.suppress(pywintypes.error): |
| 253 |
handle = win32api.LoadLibrary(libfn) |
| 254 |
|
| 255 |
sdl = _load_audio_dll( |
| 256 |
sdl, |
| 257 |
samplerate, |
| 258 |
channels, |
| 259 |
buffersize, |
| 260 |
libname, |
| 261 |
libfn, |
| 262 |
handle, |
| 263 |
) |
| 264 |
|
| 265 |
|
| 266 |
def _init_sdl_macos(samplerate: int, channels: int, buffersize: int) -> None: |
| 267 |
"""Initialize SDL on macOS. |
| 268 |
|
| 269 |
Args: |
| 270 |
samplerate (int): The sample rate to use. |
| 271 |
channels (int): The number of audio channels. |
| 272 |
buffersize (int): The size of the audio buffer. |
| 273 |
""" |
| 274 |
global _SERVER, sdl |
| 275 |
sdl = None |
| 276 |
if x_framework_pth := os.getenv("X_DYLD_FALLBACK_FRAMEWORK_PATH"): |
| 277 |
if framework_pth := os.getenv("DYLD_FALLBACK_FRAMEWORK_PATH"): |
| 278 |
x_framework_pth = os.pathsep.join([x_framework_pth, framework_pth]) |
| 279 |
os.environ["DYLD_FALLBACK_FRAMEWORK_PATH"] = x_framework_pth |
| 280 |
for libname in ("SDL2", "SDL2_mixer", "SDL", "SDL_mixer"): |
| 281 |
handle = None |
| 282 |
libfn = ctypes.util.find_library(libname) |
| 283 |
|
| 284 |
sdl = _load_audio_dll( |
| 285 |
sdl, |
| 286 |
samplerate, |
| 287 |
channels, |
| 288 |
buffersize, |
| 289 |
libname, |
| 290 |
libfn, |
| 291 |
handle, |
| 292 |
) |
| 293 |
|
| 294 |
|
| 295 |
def _init_sdl_linux(samplerate: int, channels: int, buffersize: int) -> None: |
| 296 |
"""Initialize SDL on Linux. |
| 297 |
|
| 298 |
Args: |
| 299 |
samplerate (int): The sample rate to use. |
| 300 |
channels (int): The number of audio channels. |
| 301 |
buffersize (int): The size of the audio buffer. |
| 302 |
""" |
| 303 |
global _SERVER, sdl |
| 304 |
sdl = None |
| 305 |
for libname in ("SDL2", "SDL2_mixer", "SDL", "SDL_mixer"): |
| 306 |
handle = None |
| 307 |
# Hard-code lib names for Linux |
| 308 |
libfn = f"lib{libname}" |
| 309 |
if libname.startswith("SDL2"): |
| 310 |
# SDL 2.0 |
| 311 |
libfn += "-2.0.so.0" |
| 312 |
else: |
| 313 |
# SDL 1.2 |
| 314 |
libfn += "-1.2.so.0" |
| 315 |
|
| 316 |
sdl = _load_audio_dll( |
| 317 |
sdl, |
| 318 |
samplerate, |
| 319 |
channels, |
| 320 |
buffersize, |
| 321 |
libname, |
| 322 |
libfn, |
| 323 |
handle, |
| 324 |
) |
| 325 |
|
| 326 |
|
| 327 |
def _init_sdl(samplerate: int, channels: int, buffersize: int) -> None: |
| 328 |
"""Initialize SDL audio subsystem. |
| 329 |
|
| 330 |
Args: |
| 331 |
samplerate (int): The sample rate to use. |
| 332 |
channels (int): The number of audio channels. |
| 333 |
buffersize (int): The size of the audio buffer. |
| 334 |
""" |
| 335 |
if sys.platform == "win32": |
| 336 |
_init_sdl_windows(samplerate, channels, buffersize) |
| 337 |
elif sys.platform == "darwin": |
| 338 |
_init_sdl_macos(samplerate, channels, buffersize) |
| 339 |
else: |
| 340 |
_init_sdl_linux(samplerate, channels, buffersize) |
| 341 |
|
| 342 |
|
| 343 |
def _init_pyo(samplerate: int, channels: int, buffersize: int) -> None: |
| 344 |
"""Initialize pyo audio subsystem. |
| 345 |
|
| 346 |
Args: |
| 347 |
samplerate (int): The sample rate to use. |
| 348 |
channels (int): The number of audio channels. |
| 349 |
buffersize (int): The size of the audio buffer. |
| 350 |
|
| 351 |
Raises: |
| 352 |
ImportError: If pyo is not installed or cannot be imported. |
| 353 |
RuntimeError: If pyo server initialization fails. |
| 354 |
""" |
| 355 |
global _SERVER, _LIB, _LIB_VERSION, pyo |
| 356 |
try: |
| 357 |
import pyo |
| 358 |
|
| 359 |
_LIB = "pyo" |
| 360 |
except ImportError: |
| 361 |
_LIB = None |
| 362 |
else: |
| 363 |
if isinstance(_SERVER, pyo.Server): |
| 364 |
_SERVER.reinit( |
| 365 |
sr=samplerate, nchnls=channels, buffersize=buffersize, duplex=0 |
| 366 |
) |
| 367 |
else: |
| 368 |
_SERVER = pyo.Server( |
| 369 |
sr=samplerate, |
| 370 |
nchnls=channels, |
| 371 |
buffersize=buffersize, |
| 372 |
duplex=0, |
| 373 |
winhost="asio", |
| 374 |
).boot() |
| 375 |
_SERVER.start() |
| 376 |
_LIB_VERSION = ".".join(str(v) for v in pyo.getVersion()) |
| 377 |
|
| 378 |
|
| 379 |
def _init_pyglet() -> None: |
| 380 |
"""Initialize pyglet audio subsystem.""" |
| 381 |
global _SERVER, _LIB, _LIB_VERSION, pyglet |
| 382 |
if not getattr(sys, "frozen", False): |
| 383 |
# Use included pyglet |
| 384 |
lib_dir = os.path.join(os.path.dirname(__file__), "lib") |
| 385 |
if lib_dir not in sys.path: |
| 386 |
sys.path.insert(0, lib_dir) |
| 387 |
try: |
| 388 |
import pyglet |
| 389 |
|
| 390 |
version = [] |
| 391 |
for item in pyglet.version.split("."): |
| 392 |
try: |
| 393 |
version.append(int(item)) |
| 394 |
except ValueError: |
| 395 |
version.append(item) |
| 396 |
if version < [1, 2, 2]: |
| 397 |
raise ImportError(f"pyglet version {pyglet.version} is too old") |
| 398 |
_LIB = "pyglet" |
| 399 |
except ImportError: |
| 400 |
_LIB = None |
| 401 |
else: |
| 402 |
# Work around localization preventing fallback to RIFFSourceLoader |
| 403 |
pyglet.lib.LibraryLoader.darwin_not_found_error = "" |
| 404 |
pyglet.lib.LibraryLoader.linux_not_found_error = "" |
| 405 |
# Set audio driver preference |
| 406 |
pyglet.options["audio"] = ("pulse", "openal", "directsound", "silent") |
| 407 |
_SERVER = pyglet.media |
| 408 |
_LIB_VERSION = pyglet.version |
| 409 |
|
| 410 |
|
| 411 |
def safe_init( |
| 412 |
lib: None | str = None, |
| 413 |
samplerate: int = 22050, |
| 414 |
channels: int = 2, |
| 415 |
buffersize: int = 2048, |
| 416 |
reinit: bool = False, |
| 417 |
) -> None | Exception: |
| 418 |
"""Safely initialize the sound subsystem. |
| 419 |
|
| 420 |
Like init(), but catch any exceptions. |
| 421 |
|
| 422 |
Args: |
| 423 |
lib (str): The audio library to use (e.g., "SDL", "pyglet", "pyo", "wx"). |
| 424 |
samplerate (int): The sample rate to use. |
| 425 |
channels (int): The number of audio channels. |
| 426 |
buffersize (int): The size of the audio buffer. |
| 427 |
reinit (bool): Whether to reinitialize the sound subsystem. |
| 428 |
|
| 429 |
Returns: |
| 430 |
None | Exception: None if initialization was successful, or an |
| 431 |
Exception if an error occurred. |
| 432 |
""" |
| 433 |
global _INITIALIZED |
| 434 |
try: |
| 435 |
return init(lib, samplerate, channels, buffersize, reinit) |
| 436 |
except Exception as exception: |
| 437 |
# So we can check if initialization failed |
| 438 |
_INITIALIZED = exception |
| 439 |
return exception |
| 440 |
|
| 441 |
|
| 442 |
class DummySound: |
| 443 |
"""Dummy sound wrapper class. |
| 444 |
|
| 445 |
Args: |
| 446 |
filename (str): The filename of the sound file (not used). |
| 447 |
loop (bool): Whether to loop the sound (not used). |
| 448 |
""" |
| 449 |
|
| 450 |
def __init__(self, filename: None | str = None, loop: bool = False) -> None: |
| 451 |
pass |
| 452 |
|
| 453 |
def fade(self, fade_ms: int, fade_in: None | bool = None) -> bool: |
| 454 |
"""Fade in/out. |
| 455 |
|
| 456 |
Args: |
| 457 |
fade_ms (int): Fade in/out duration in milliseconds. |
| 458 |
fade_in (bool): If True, fade in, if False, fade out. If None, |
| 459 |
fade in if currently not playing, otherwise fade out. |
| 460 |
|
| 461 |
Returns: |
| 462 |
bool: Always True for DummySound. |
| 463 |
""" |
| 464 |
return True |
| 465 |
|
| 466 |
@property |
| 467 |
def is_playing(self) -> bool: |
| 468 |
"""Return whether the sound is currently playing. |
| 469 |
|
| 470 |
Returns: |
| 471 |
bool: Always False for DummySound. |
| 472 |
""" |
| 473 |
return False |
| 474 |
|
| 475 |
def play(self, fade_ms: int = 0) -> bool: |
| 476 |
"""Play the sound. |
| 477 |
|
| 478 |
Args: |
| 479 |
fade_ms (int): Fade in duration in milliseconds. |
| 480 |
|
| 481 |
Returns: |
| 482 |
bool: True if the sound was played, False otherwise. |
| 483 |
""" |
| 484 |
return True |
| 485 |
|
| 486 |
@property |
| 487 |
def play_count(self) -> int: |
| 488 |
"""Return the number of times the sound has been played. |
| 489 |
|
| 490 |
Returns: |
| 491 |
int: The number of times the sound has been played. |
| 492 |
""" |
| 493 |
return 0 |
| 494 |
|
| 495 |
def safe_fade(self, fade_ms: int, fade_in: None | bool = None) -> bool: |
| 496 |
"""Like fade(), but catch any exceptions. |
| 497 |
|
| 498 |
Args: |
| 499 |
fade_ms (int): Fade in/out duration in milliseconds. |
| 500 |
fade_in (None | bool): If True, fade in, if False, fade out. If |
| 501 |
None, fade in if currently not playing, otherwise fade out. |
| 502 |
|
| 503 |
Returns: |
| 504 |
bool: True if the fade was successful, False otherwise. |
| 505 |
""" |
| 506 |
return True |
| 507 |
|
| 508 |
def safe_play(self, fade_ms: int = 0) -> bool: |
| 509 |
"""Like play(), but catch any exceptions. |
| 510 |
|
| 511 |
Args: |
| 512 |
fade_ms (int): Fade in duration in milliseconds. |
| 513 |
|
| 514 |
Returns: |
| 515 |
bool: True if the sound was played, False otherwise. |
| 516 |
""" |
| 517 |
return True |
| 518 |
|
| 519 |
def safe_stop(self, fade_ms: int = 0) -> bool: |
| 520 |
"""Like stop(), but catch any exceptions. |
| 521 |
|
| 522 |
Args: |
| 523 |
fade_ms (int): Fade out duration in milliseconds. |
| 524 |
|
| 525 |
Returns: |
| 526 |
bool: True if the sound was stopped, False otherwise. |
| 527 |
""" |
| 528 |
return True |
| 529 |
|
| 530 |
def stop(self, fade_ms: int = 0) -> bool: |
| 531 |
"""Stop playback. |
| 532 |
|
| 533 |
Args: |
| 534 |
fade_ms (int): Fade out duration in milliseconds. |
| 535 |
|
| 536 |
Returns: |
| 537 |
bool: True if the sound was stopped, False otherwise. |
| 538 |
""" |
| 539 |
return True |
| 540 |
|
| 541 |
volume = 0 |
| 542 |
|
| 543 |
|
| 544 |
class SDL_RWops(Structure): # noqa: N801 |
| 545 |
"""SDL_RWops structure.""" |
| 546 |
|
| 547 |
|
| 548 |
class Mix_Chunk(Structure): # noqa: N801 |
| 549 |
"""SDL_Mixer chunk structure.""" |
| 550 |
|
| 551 |
_fields_: ClassVar[list[tuple]] = [ |
| 552 |
("allocated", c_int), |
| 553 |
("abuf", POINTER(c_uint8)), |
| 554 |
("alen", c_uint32), |
| 555 |
("volume", c_uint8), |
| 556 |
] |
| 557 |
|
| 558 |
|
| 559 |
class Sound: |
| 560 |
"""Sound wrapper class. |
| 561 |
|
| 562 |
Args: |
| 563 |
filename (str): The filename of the sound file. |
| 564 |
loop (bool): Whether to loop the sound. |
| 565 |
""" |
| 566 |
|
| 567 |
def __new__(cls, filename: str, loop: bool = False) -> Sound: # noqa: PYI034 |
| 568 |
"""Create a new Sound instance. |
| 569 |
|
| 570 |
Args: |
| 571 |
filename (str): The filename of the sound file. |
| 572 |
loop (bool): Whether to loop the sound. |
| 573 |
|
| 574 |
Returns: |
| 575 |
Sound: A new Sound instance. |
| 576 |
""" |
| 577 |
if (filename, loop) in _SOUNDS: |
| 578 |
# Cache hit |
| 579 |
return _SOUNDS[(filename, loop)] |
| 580 |
# Create and instance and cache it |
| 581 |
sound = super().__new__(cls) |
| 582 |
_SOUNDS[(filename, loop)] = sound |
| 583 |
return sound |
| 584 |
|
| 585 |
def __init__(self, filename: str, loop: bool = False) -> None: |
| 586 |
self._filename = filename |
| 587 |
self._is_playing = False |
| 588 |
self._lib = _LIB |
| 589 |
self._lib_version = _LIB_VERSION |
| 590 |
self._loop = loop |
| 591 |
self._play_timestamp = 0 |
| 592 |
self._play_count = 0 |
| 593 |
self._thread = -1 |
| 594 |
if not _INITIALIZED: |
| 595 |
self._server = init() |
| 596 |
else: |
| 597 |
self._server = _SERVER |
| 598 |
if not _INITIALIZED or isinstance(_INITIALIZED, Exception): |
| 599 |
return |
| 600 |
if not self._lib and _LIB: |
| 601 |
self._lib = _LIB |
| 602 |
self._lib_version = _LIB_VERSION |
| 603 |
if self._snd or not self._filename: |
| 604 |
return |
| 605 |
if self._lib == "pyo": |
| 606 |
self._snd = pyo.SfPlayer(safe_str(self._filename), loop=self._loop) |
| 607 |
elif self._lib == "pyglet": |
| 608 |
snd = pyglet.media.load(self._filename, streaming=False) |
| 609 |
self._ch = pyglet.media.Player() |
| 610 |
self._snd = snd |
| 611 |
elif self._lib == "SDL": |
| 612 |
rw = sdl.SDL_RWFromFile(safe_str(self._filename, "UTF-8"), "rb") |
| 613 |
self._snd = self._server.Mix_LoadWAV_RW(rw, 1) |
| 614 |
elif self._lib == "wx": |
| 615 |
self._snd = wx.Sound(self._filename) |
| 616 |
|
| 617 |
@property |
| 618 |
def _ch(self) -> None | int | pyglet.media.Player: |
| 619 |
"""Return the channel object or value. |
| 620 |
|
| 621 |
Returns: |
| 622 |
None | int | pyglet.media.Player : The channel object or None if |
| 623 |
not available. |
| 624 |
""" |
| 625 |
return _CH.get((self._filename, self._loop)) |
| 626 |
|
| 627 |
@_ch.setter |
| 628 |
def _ch(self, ch: None | int | pyglet.media.Player) -> None: |
| 629 |
"""Set the channel object or value. |
| 630 |
|
| 631 |
Args: |
| 632 |
ch (None | int | pyglet.media.Player): The channel object to set. |
| 633 |
""" |
| 634 |
_CH[(self._filename, self._loop)] = ch |
| 635 |
|
| 636 |
def _fade(self, fade_ms: int, fade_in: bool, thread: int) -> None: |
| 637 |
"""Fade in/out the sound. |
| 638 |
|
| 639 |
Args: |
| 640 |
fade_ms (int): Fade in/out duration in milliseconds. |
| 641 |
fade_in (bool): If True, fade in, if False, fade out. |
| 642 |
thread (int): Thread identifier to check if we are still the current thread. |
| 643 |
""" |
| 644 |
volume = self.volume |
| 645 |
if fade_ms and ((fade_in and volume < 1) or (not fade_in and volume)): |
| 646 |
count = 200 |
| 647 |
for i in range(count + 1): |
| 648 |
if fade_in: |
| 649 |
self.volume = volume + i / float(count) * (1.0 - volume) |
| 650 |
else: |
| 651 |
self.volume = volume - i / float(count) * volume |
| 652 |
time.sleep(fade_ms / 1000.0 / count) |
| 653 |
if self._thread is not thread: |
| 654 |
# If we are no longer the current thread, return immediately |
| 655 |
return |
| 656 |
if not self.volume: |
| 657 |
self.stop() |
| 658 |
|
| 659 |
@property |
| 660 |
def volume(self) -> float: |
| 661 |
"""Return the current volume of the sound. |
| 662 |
|
| 663 |
If the sound is not playing, return 0.0. |
| 664 |
If the sound is not available, return 1.0. |
| 665 |
|
| 666 |
Returns: |
| 667 |
float: The current volume of the sound, between 0.0 and 1.0. |
| 668 |
""" |
| 669 |
volume = 1.0 |
| 670 |
if self._snd: |
| 671 |
if self._lib == "pyo": |
| 672 |
volume = self._snd.mul |
| 673 |
elif self._lib == "pyglet": |
| 674 |
volume = self._ch.volume |
| 675 |
elif self._lib == "SDL": |
| 676 |
volume = float(self._server.Mix_VolumeChunk(self._snd, -1)) / 128 |
| 677 |
return volume |
| 678 |
|
| 679 |
@volume.setter |
| 680 |
def volume(self, volume: float) -> None: |
| 681 |
"""Set the volume of the sound. |
| 682 |
|
| 683 |
Args: |
| 684 |
volume (float): The volume to set, between 0.0 and 1.0. |
| 685 |
""" |
| 686 |
if not self._snd or self._lib == "wx": |
| 687 |
return |
| 688 |
if self._lib == "pyo": |
| 689 |
self._snd.mul = volume |
| 690 |
elif self._lib == "pyglet": |
| 691 |
self._ch.volume = volume |
| 692 |
elif self._lib == "SDL": |
| 693 |
self._server.Mix_VolumeChunk(self._snd, round(volume * 128)) |
| 694 |
|
| 695 |
@property |
| 696 |
def _snd(self) -> None | Sound: |
| 697 |
"""Return the sound object. |
| 698 |
|
| 699 |
Returns: |
| 700 |
None | Sound: The sound object or None if not available. |
| 701 |
""" |
| 702 |
return _SND.get((self._filename, self._loop)) |
| 703 |
|
| 704 |
@_snd.setter |
| 705 |
def _snd(self, snd: Sound) -> None: |
| 706 |
"""Set the sound object. |
| 707 |
|
| 708 |
Args: |
| 709 |
snd: The sound object to set. |
| 710 |
""" |
| 711 |
_SND[(self._filename, self._loop)] = snd |
| 712 |
|
| 713 |
def fade(self, fade_ms: int, fade_in: None | bool = None) -> bool: |
| 714 |
"""Fade in/out. |
| 715 |
|
| 716 |
If fade_in is None, fade in/out depending on current volume. |
| 717 |
|
| 718 |
Args: |
| 719 |
fade_ms (int): Fade in/out duration in milliseconds. |
| 720 |
fade_in (bool): If True, fade in, if False, fade out. If None, |
| 721 |
fade in if currently not playing, otherwise fade out. |
| 722 |
|
| 723 |
Returns: |
| 724 |
bool: True if the fade was started, False otherwise. |
| 725 |
""" |
| 726 |
if fade_in is None: |
| 727 |
fade_in = not self.volume |
| 728 |
if fade_in and not self.is_playing: |
| 729 |
return self.play(fade_ms=fade_ms) |
| 730 |
if not self._snd or self._lib == "wx": |
| 731 |
return False |
| 732 |
self._thread += 1 |
| 733 |
threading.Thread( |
| 734 |
target=self._fade, |
| 735 |
name=f"AudioFading-{self._thread}[{fade_ms}ms]", |
| 736 |
args=(fade_ms, fade_in, self._thread), |
| 737 |
).start() |
| 738 |
return True |
| 739 |
|
| 740 |
@property |
| 741 |
def is_playing(self) -> bool: |
| 742 |
"""Return whether the sound is currently playing. |
| 743 |
|
| 744 |
Returns: |
| 745 |
bool: True if the sound is playing, False otherwise. |
| 746 |
""" |
| 747 |
if self._lib == "pyo": |
| 748 |
return bool(self._snd and self._snd.isOutputting()) |
| 749 |
if self._lib == "pyglet": |
| 750 |
return bool( |
| 751 |
self._ch |
| 752 |
and self._ch.playing |
| 753 |
and self._ch.source |
| 754 |
and ( |
| 755 |
self._loop |
| 756 |
or time.time() - self._play_timestamp < self._ch.source.duration |
| 757 |
) |
| 758 |
) |
| 759 |
if self._lib == "SDL": |
| 760 |
return bool(self._ch is not None and self._server.Mix_Playing(self._ch)) |
| 761 |
return self._is_playing |
| 762 |
|
| 763 |
def _play_pyglet(self, fade_ms: int = 0, stop_already_playing: bool = True) -> bool: |
| 764 |
"""Play the sound using pyglet. |
| 765 |
|
| 766 |
Args: |
| 767 |
fade_ms (int): Fade in duration in milliseconds. |
| 768 |
stop_already_playing (bool): If True, stop the sound if it is |
| 769 |
already playing before starting playback. |
| 770 |
|
| 771 |
Returns: |
| 772 |
bool: True if the sound was played, False otherwise. |
| 773 |
""" |
| 774 |
if not self._snd: |
| 775 |
return False |
| 776 |
volume = self.volume |
| 777 |
if stop_already_playing: |
| 778 |
self.stop() |
| 779 |
# Can't reuse the player, won't replay the sound under Mac OS X |
| 780 |
# and Linux even when seeking to start position which allows |
| 781 |
# replaying the sound under Windows. |
| 782 |
if stop_already_playing: |
| 783 |
with contextlib.suppress(TypeError): |
| 784 |
self._ch.delete() |
| 785 |
self._ch = pyglet.media.Player() |
| 786 |
if self._lib_version >= "1.4.0": |
| 787 |
self._ch.loop = self._loop |
| 788 |
self.volume = volume |
| 789 |
if not self.is_playing and fade_ms and volume == 1: |
| 790 |
self.volume = 0 |
| 791 |
self._play_timestamp = time.time() |
| 792 |
|
| 793 |
if self._loop and self._lib_version < "1.4.0": |
| 794 |
snd = pyglet.media.SourceGroup( |
| 795 |
self._snd.audio_format, self._snd.video_format |
| 796 |
) |
| 797 |
snd.loop = True |
| 798 |
snd.queue(self._snd) |
| 799 |
else: |
| 800 |
snd = self._snd |
| 801 |
self._ch.queue(snd) |
| 802 |
self._ch.play() |
| 803 |
|
| 804 |
if self._lib: |
| 805 |
self._play_count += 1 |
| 806 |
if fade_ms: |
| 807 |
self.fade(fade_ms, True) |
| 808 |
return True |
| 809 |
|
| 810 |
def _play_pyo(self, fade_ms: int = 0, stop_already_playing: bool = True) -> bool: |
| 811 |
"""Play the sound using pyo. |
| 812 |
|
| 813 |
Args: |
| 814 |
fade_ms (int): Fade in duration in milliseconds. |
| 815 |
stop_already_playing (bool): If True, stop the sound if it is |
| 816 |
already playing before starting playback. |
| 817 |
|
| 818 |
Returns: |
| 819 |
bool: True if the sound was played, False otherwise. |
| 820 |
""" |
| 821 |
if not self._snd: |
| 822 |
return False |
| 823 |
volume = self.volume |
| 824 |
if stop_already_playing: |
| 825 |
self.stop() |
| 826 |
|
| 827 |
if not self.is_playing and fade_ms and volume == 1: |
| 828 |
self.volume = 0 |
| 829 |
self._play_timestamp = time.time() |
| 830 |
self._snd.out() |
| 831 |
if self._lib: |
| 832 |
self._play_count += 1 |
| 833 |
if fade_ms: |
| 834 |
self.fade(fade_ms, True) |
| 835 |
return True |
| 836 |
|
| 837 |
def _play_sdl(self, fade_ms: int = 0, stop_already_playing: bool = True) -> bool: |
| 838 |
"""Play the sound using SDL. |
| 839 |
|
| 840 |
Args: |
| 841 |
fade_ms (int): Fade in duration in milliseconds. |
| 842 |
stop_already_playing (bool): If True, stop the sound if it is |
| 843 |
already playing before starting playback. |
| 844 |
|
| 845 |
Returns: |
| 846 |
bool: True if the sound was played, False otherwise. |
| 847 |
""" |
| 848 |
if not self._snd: |
| 849 |
return False |
| 850 |
volume = self.volume |
| 851 |
if stop_already_playing: |
| 852 |
self.stop() |
| 853 |
if not self.is_playing and fade_ms and volume == 1: |
| 854 |
self.volume = 0 |
| 855 |
self._play_timestamp = time.time() |
| 856 |
self._ch = self._server.Mix_PlayChannelTimed( |
| 857 |
-1, self._snd, -1 if self._loop else 0, -1 |
| 858 |
) |
| 859 |
if self._lib: |
| 860 |
self._play_count += 1 |
| 861 |
if fade_ms: |
| 862 |
self.fade(fade_ms, True) |
| 863 |
return True |
| 864 |
|
| 865 |
def _play_wx(self, fade_ms: int = 0, stop_already_playing: bool = True) -> bool: |
| 866 |
"""Play the sound using wx. |
| 867 |
|
| 868 |
Args: |
| 869 |
fade_ms (int): Fade in duration in milliseconds. |
| 870 |
stop_already_playing (bool): If True, stop the sound if it is |
| 871 |
already playing before starting playback. |
| 872 |
|
| 873 |
Returns: |
| 874 |
bool: True if the sound was played, False otherwise. |
| 875 |
""" |
| 876 |
if not self._snd: |
| 877 |
return False |
| 878 |
volume = self.volume |
| 879 |
if stop_already_playing: |
| 880 |
self.stop() |
| 881 |
if not self.is_playing and fade_ms and volume == 1: |
| 882 |
self.volume = 0 |
| 883 |
self._play_timestamp = time.time() |
| 884 |
if self._snd.IsOk(): |
| 885 |
flags = wx.SOUND_ASYNC |
| 886 |
if self._loop: |
| 887 |
flags |= wx.SOUND_LOOP |
| 888 |
# The best we can do is have the correct state reflected |
| 889 |
# for looping sounds only |
| 890 |
self._is_playing = True |
| 891 |
# wx.Sound.Play is supposed to return True on success. |
| 892 |
# When I tested this, it always returned False, but still |
| 893 |
# played the sound. |
| 894 |
self._snd.Play(flags) |
| 895 |
if self._lib: |
| 896 |
self._play_count += 1 |
| 897 |
return True |
| 898 |
|
| 899 |
def play(self, fade_ms: int = 0, stop_already_playing: bool = True) -> bool: |
| 900 |
"""Play the sound. |
| 901 |
|
| 902 |
Args: |
| 903 |
fade_ms (int): Fade in duration in milliseconds. |
| 904 |
stop_already_playing (bool): If True, stop the sound if it is |
| 905 |
already playing before starting playback. |
| 906 |
|
| 907 |
Returns: |
| 908 |
bool: True if the sound was played, False otherwise. |
| 909 |
""" |
| 910 |
if not self._snd: |
| 911 |
return False |
| 912 |
if self._lib == "pyglet": |
| 913 |
return self._play_pyglet(fade_ms, stop_already_playing) |
| 914 |
if self._lib == "pyo": |
| 915 |
return self._play_pyo(fade_ms, stop_already_playing) |
| 916 |
if self._lib == "pyglet": |
| 917 |
return self._play_pyglet(fade_ms, stop_already_playing) |
| 918 |
if self._lib == "SDL": |
| 919 |
return self._play_sdl(fade_ms, stop_already_playing) |
| 920 |
if self._lib == "wx": |
| 921 |
return self._play_wx(fade_ms, stop_already_playing) |
| 922 |
return True |
| 923 |
|
| 924 |
@property |
| 925 |
def play_count(self) -> int: |
| 926 |
"""Return the number of times the sound has been played. |
| 927 |
|
| 928 |
Returns: |
| 929 |
int: The number of times the sound has been played. |
| 930 |
""" |
| 931 |
return self._play_count |
| 932 |
|
| 933 |
def safe_fade(self, fade_ms: int, fade_in: None | bool = None) -> bool | Exception: |
| 934 |
"""Safely fade in/out. |
| 935 |
|
| 936 |
Like fade(), but catch any exceptions. |
| 937 |
|
| 938 |
Args: |
| 939 |
fade_ms (int): Fade in/out duration in milliseconds. |
| 940 |
fade_in (None | bool): If True, fade in, if False, fade out. If |
| 941 |
None, fade in if currently not playing, otherwise fade out. |
| 942 |
|
| 943 |
Returns: |
| 944 |
bool | Exception: True if the fade was successful, False otherwise, |
| 945 |
or an exception if an error occurred. |
| 946 |
""" |
| 947 |
if not _INITIALIZED: |
| 948 |
safe_init() |
| 949 |
try: |
| 950 |
return self.fade(fade_ms, fade_in) |
| 951 |
except Exception as exception: |
| 952 |
return exception |
| 953 |
|
| 954 |
def safe_play(self, fade_ms: int = 0) -> bool | Exception: |
| 955 |
"""Safely play the sound. |
| 956 |
|
| 957 |
Like play(), but catch any exceptions. |
| 958 |
|
| 959 |
Args: |
| 960 |
fade_ms (int): Fade in duration in milliseconds. |
| 961 |
|
| 962 |
Returns: |
| 963 |
bool | Exception: True if the sound was played, False otherwise, |
| 964 |
or an exception if an error occurred. |
| 965 |
""" |
| 966 |
if not _INITIALIZED: |
| 967 |
safe_init() |
| 968 |
try: |
| 969 |
return self.play(fade_ms) |
| 970 |
except Exception as exception: |
| 971 |
return exception |
| 972 |
|
| 973 |
def safe_stop(self, fade_ms: int = 0) -> bool | Exception: |
| 974 |
"""Safely stop playback. |
| 975 |
|
| 976 |
Like stop(), but catch any exceptions. |
| 977 |
|
| 978 |
Returns: |
| 979 |
bool | Exception: True if the sound was stopped, False otherwise, |
| 980 |
or an exception if an error occurred. |
| 981 |
""" |
| 982 |
try: |
| 983 |
return self.stop(fade_ms) |
| 984 |
except Exception as exception: |
| 985 |
return exception |
| 986 |
|
| 987 |
def stop(self, fade_ms: int = 0) -> bool: |
| 988 |
"""Stop playback. |
| 989 |
|
| 990 |
Args: |
| 991 |
fade_ms (int): Fade out duration in milliseconds. |
| 992 |
|
| 993 |
Returns: |
| 994 |
bool: True if the sound was stopped, False otherwise. |
| 995 |
""" |
| 996 |
if self._snd and self.is_playing: |
| 997 |
if self._lib == "wx": |
| 998 |
self._snd.Stop() |
| 999 |
self._is_playing = False |
| 1000 |
elif fade_ms: |
| 1001 |
self.fade(fade_ms, False) |
| 1002 |
elif self._lib == "pyglet": |
| 1003 |
self._ch.pause() |
| 1004 |
elif self._lib == "SDL": |
| 1005 |
self._server.Mix_HaltChannel(self._ch) |
| 1006 |
else: |
| 1007 |
self._snd.stop() |
| 1008 |
return True |
| 1009 |
return False |
| 1010 |
|
| 1011 |
|
| 1012 |
if __name__ == "__main__": |
| 1013 |
import wx |
| 1014 |
|
| 1015 |
from DisplayCAL.config import get_data_path |
| 1016 |
|
| 1017 |
sound = Sound(get_data_path("theme/engine_hum_loop.wav"), True) |
| 1018 |
app = wx.App(0) |
| 1019 |
frame = wx.Frame(None, -1, "Test") |
| 1020 |
frame.Bind( |
| 1021 |
wx.EVT_CLOSE, |
| 1022 |
lambda event: ( |
| 1023 |
sound.stop(1000) and _LIB != "wx" and time.sleep(1), |
| 1024 |
event.Skip(), |
| 1025 |
), |
| 1026 |
) |
| 1027 |
panel = wx.Panel(frame) |
| 1028 |
panel.Sizer = wx.BoxSizer() |
| 1029 |
button = wx.Button(panel, -1, "Play") |
| 1030 |
button.Bind(wx.EVT_BUTTON, lambda event: not sound.is_playing and sound.play(3000)) |
| 1031 |
panel.Sizer.Add(button, 1) |
| 1032 |
button = wx.Button(panel, -1, "Stop") |
| 1033 |
button.Bind(wx.EVT_BUTTON, lambda event: sound.is_playing and sound.stop(3000)) |
| 1034 |
panel.Sizer.Add(button, 1) |
| 1035 |
panel.Sizer.SetSizeHints(frame) |
| 1036 |
frame.Show() |
| 1037 |
app.MainLoop() |