TaylorSMarks / playsound

Pure Python, cross platform, single function module with no dependencies for playing sounds.
Other
504 stars 118 forks source link

playsound can be simplified and made less buggy #133

Open zackees opened 1 year ago

zackees commented 1 year ago

After trying to work around win32, macos and linux bugs I've gone ahead and removed playsound from my python project and replaced it with this cross platform solution.

"""Sound utilities."""

import os
import sys
import time
from subprocess import check_call
import warnings

def playaudio(file: str, ignore_errors=True) -> None:
    assert os.path.exists(file), f"Sound file {file} does not exist."
    try:
        if sys.platform != "win32":
            if "linux" in sys.platform:
                check_call(["xdg-open", file])
            elif sys.platform == "darwin":
                check_call(["afplay", file])
            else:
                assert False, f"Unsupported platform: {sys.platform}."
            return

        os.environ["PYGAME_HIDE_SUPPORT_PROMPT"] = "1"
        from pygame import mixer  # type: ignore  # pylint: disable=all

        mixer.init()
        mixer.music.load(file)
        mixer.music.play()
        while mixer.music.get_busy():
            time.sleep(0.01)
    except Exception as exc:
        if ignore_errors:
            warnings.warn(f"Cannot play {file} because of {exc}.")
        else:
            raise

I recommend that playsound moves to this code.

zackees commented 1 year ago

If someone is hitting this same problem check out my lib which implements the above.

https://github.com/zackees/playaudio

stodja commented 1 year ago

This doesn't check for multiple audio players. Shout out to PreferredSoundPlayer for doing this. I can't find any check in playsound either, so i guess that PreferredSoundPlayer is the best option. Always DYOR though!