From bd37ea26872abc0a1530a34252696ca84125b360 Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Sat, 21 Nov 2026 02:17:33 -0500 Subject: [PATCH] Sounds overlap on Windows: each one plays on its own MCI device Co-Authored-By: Claude Opus 5.5 --- docs/guide/features.md | 7 ++-- meshterm/core/preferences.py | 5 ++- meshterm/services/sound.py | 70 ++++++++++++++++++++++++++++++++---- tests/test_sound.py | 29 +++++++++++++++ 4 files changed, 99 insertions(+), 12 deletions(-) diff --git a/docs/guide/features.md b/docs/guide/features.md index 96b1574..f46081e 100644 --- a/docs/guide/features.md +++ b/docs/guide/features.md @@ -117,9 +117,10 @@ selects when: off, on, or **when silent** (the default), which flashes when the muted or the theme is no sound. The PicoCalc has no sound, so there each notification flashes. -MeshTerm plays the sounds through the player of your computer: `winsound` on Windows, -`afplay` on macOS, and `pw-play`, `paplay`, or `aplay` on Linux. If none of them works, -MeshTerm writes one line in its log and continues with no sound. +MeshTerm plays the sounds through the player of your computer: MCI on Windows, `afplay` on +macOS, and `pw-play`, `paplay`, or `aplay` on Linux. Two sounds can play at the same time: +a new sound does not stop one that plays. If no player works, MeshTerm writes one line in +its log and continues with no sound. ## Leaving MeshTerm diff --git a/meshterm/core/preferences.py b/meshterm/core/preferences.py index 1b8756f..e97dc17 100644 --- a/meshterm/core/preferences.py +++ b/meshterm/core/preferences.py @@ -540,9 +540,8 @@ PREFERENCES: tuple[PrefSpec, ...] = ( question="How loud the sounds play: 1 is 10%, 10 is 100%", group="Sound", value_type="int", - # A slider of ten steps (JP, 2026-11-20). MeshTerm scales the samples itself, - # because winsound, the only player on Windows, has no volume control. Thus the - # volume is the same with each player. + # A slider of ten steps (JP, 2026-11-20). MeshTerm scales the samples itself, so + # that the volume is the same with each player. default=7, minimum=1, maximum=10, diff --git a/meshterm/services/sound.py b/meshterm/services/sound.py index 82018e4..975185d 100644 --- a/meshterm/services/sound.py +++ b/meshterm/services/sound.py @@ -11,12 +11,12 @@ flashes. MeshTerm has no audio dependency. It plays a WAV file through the player of the operating system: -* **Windows**: ``winsound``, from the standard library. +* **Windows**: MCI (``winmm``, through ``ctypes``), so that sounds can overlap. * **macOS**: ``afplay``. * **Linux** (the Cardputer Zero too): the first of ``pw-play``, ``paplay``, and ``aplay`` that is installed. -The volume is in MeshTerm, not in the player: ``winsound`` has no volume control. Thus the +The volume is in MeshTerm, not in the player, so that it is the same with each player. Thus the service writes a scaled copy of each sound into a cache folder, one time for each volume, and plays the copy. The ``bell`` theme plays no file. It sends the terminal bell (BEL), which rings on the computer of the user, also over SSH. @@ -167,9 +167,67 @@ def scaled(source: Path, volume_pct: int, cache_dir: Path) -> Path: return target +class _Mci: + """Plays WAV files on Windows through MCI (``winmm``), each sound on its own device. + + ``winsound`` plays one sound at a time: a new sound stops the sound that plays. MCI + opens a new ``waveaudio`` device for each sound, and Windows mixes the devices. Thus two + sounds play at the same time (JP, 2026-11-21: "playing a sound shouldn't interrupt an + already playing sound"). Each device closes at the next sound after it stops. + """ + + def __init__(self) -> None: + """Bind ``mciSendStringW`` from ``winmm``.""" + import ctypes + + self._ctypes = ctypes + self._send_string = ctypes.windll.winmm.mciSendStringW # type: ignore[attr-defined] + self._count = 0 + self._open: list[str] = [] + + def _send(self, command: str) -> str: + """Send one MCI command string, and return its answer. + + Raises: + OSError: If MCI refuses the command. + """ + answer = self._ctypes.create_unicode_buffer(64) + error = self._send_string(command, answer, len(answer), None) + if error: + raise OSError(f"MCI error {error} for {command.split()[0]!r}") + return answer.value + + def play(self, path: Path) -> None: + """Open a new device on the file, and start it without a wait.""" + self._close_stopped() + self._count += 1 + alias = f"meshterm{self._count}" + self._send(f'open "{path}" type waveaudio alias {alias}') + self._open.append(alias) + self._send(f"play {alias}") + + def _close_stopped(self) -> None: + """Close each device whose sound has ended.""" + for alias in list(self._open): + try: + playing = self._send(f"status {alias} mode") == "playing" + except OSError: + playing = False + if not playing: + try: + self._send(f"close {alias}") + except OSError: + pass + self._open.remove(alias) + + class Player: """Plays a WAV file through the player of the operating system, without a wait. + Sounds play at the same time: a new sound never stops one that plays. On macOS and + Linux, each sound is its own player process. On Windows, each sound is its own MCI + device (refer to :class:`_Mci`). + The first failure goes to the log, and then the player stays off for the session. """ @@ -178,6 +236,7 @@ class Player: self.broken = False self._command: list[str] | None = None self._running: list[subprocess.Popen[bytes]] = [] + self._mci: _Mci | None = None def play(self, path: Path) -> bool: """Start the sound, and return at once. @@ -192,10 +251,9 @@ class Player: return False try: if sys.platform == "win32": - import winsound - - flags = winsound.SND_FILENAME | winsound.SND_ASYNC | winsound.SND_NODEFAULT - winsound.PlaySound(str(path), flags) + if self._mci is None: + self._mci = _Mci() + self._mci.play(path) return True return self._spawn(path) except Exception as error: # noqa: BLE001 - any failure of the player makes it off. diff --git a/tests/test_sound.py b/tests/test_sound.py index adb4c4c..5e0301c 100644 --- a/tests/test_sound.py +++ b/tests/test_sound.py @@ -347,3 +347,32 @@ def test_a_room_catch_up_lasts_until_a_pause() -> None: assert rooms.catching_up("a1b2c3d4e5f6", now=103.0 + CATCH_UP_QUIET_S - 1) is True assert rooms.catching_up("a1b2c3d4e5f6", now=200.0) is False # the pause ended it assert rooms.catching_up("a1b2c3d4e5f6", now=201.0) is False + + +def test_mci_opens_a_device_for_each_sound_and_closes_the_stopped_ones() -> None: + """Each sound gets its own device, so a new sound never stops one that plays.""" + from meshterm.services.sound import _Mci + + sent: list[str] = [] + playing: set[str] = set() + + def send(command: str) -> str: + sent.append(command) + verb, alias = command.split()[0], command.split()[-1] + if verb == "play": + playing.add(alias) + if verb == "status": + return "playing" if command.split()[1] in playing else "stopped" + return "" + + mci = _Mci.__new__(_Mci) + mci._count, mci._open = 0, [] + mci._send = send # type: ignore[method-assign] + mci.play(Path("a.wav")) + mci.play(Path("b.wav")) + assert mci._open == ["meshterm1", "meshterm2"] # both play at the same time + assert not any(c.startswith("stop") for c in sent) + playing.discard("meshterm1") # the first sound ended + mci.play(Path("c.wav")) + assert mci._open == ["meshterm2", "meshterm3"] + assert "close meshterm1" in sent