r/learnpython • • 1d ago

Is there any way to play audio in Python without using external libraries or winsound?

I wanted to play audio in Python, so I started looking for modules that were already installed, it means ones that wouldn't require an internet connection to install (for example Pygame)

I found winsound but the problem is that it will only play audio on Windows and no in other OS

It seemed more convenient not to have to install external libraries to test Python capabilities within the existing environment (such as using Tkinter instead of game engines)

Unfortunately many audio libraries and modules were removed in 3.13 (i'm using 3.14)

11 Upvotes

27 comments sorted by

14

u/_mturtle_ 1d ago

you can with ctypes and direct native calls

import ctypes
import ctypes.util
import os
import sys
import time
import wave


def play_wav(filepath: str, block: bool = True) -> None:
    """Play a WAV file using native OS libraries via ctypes."""
    filepath = os.path.abspath(filepath)
    if not os.path.exists(filepath):
        raise FileNotFoundError(f"Audio file not found: {filepath}")

    if sys.platform == "win32":
        _play_windows(filepath, block)
    elif sys.platform == "darwin":
        _play_macos(filepath, block)
    elif sys.platform.startswith("linux"):
        _play_linux(filepath, block)
    else:
        raise NotImplementedError(f"Unsupported OS: {sys.platform}")


# --- Windows (winmm.dll) ---
def _play_windows(filepath: str, block: bool) -> None:
    winmm = ctypes.windll.winmm
    SND_FILENAME = 0x00020000
    SND_NODEFAULT = 0x0002
    SND_ASYNC = 0x0001

    flags = SND_FILENAME | SND_NODEFAULT
    if not block:
        flags |= SND_ASYNC

    winmm.PlaySoundW(filepath, None, flags)


# --- macOS (AppKit / Objective-C Runtime) ---
def _play_macos(filepath: str, block: bool) -> None:
    objc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("objc"))
    ctypes.cdll.LoadLibrary(ctypes.util.find_library("AppKit"))

    # Configure return types for 64-bit pointers
    objc.objc_getClass.restype = ctypes.c_void_p
    objc.objc_getClass.argtypes = [ctypes.c_char_p]
    objc.sel_registerName.restype = ctypes.c_void_p
    objc.sel_registerName.argtypes = [ctypes.c_char_p]
    objc.objc_msgSend.restype = ctypes.c_void_p

    def msg(receiver, selector, *args_and_types):
        argtypes = [ctypes.c_void_p, ctypes.c_void_p]
        args = []
        for val, ctype in args_and_types:
            argtypes.append(ctype)
            args.append(val)
        objc.objc_msgSend.argtypes = argtypes
        return objc.objc_msgSend(receiver, objc.sel_registerName(selector), *args)

    # Create NSString for filepath
    NSString = objc.objc_getClass(b"NSString")
    ns_path = msg(NSString, b"stringWithUTF8String:", (filepath.encode("utf-8"), ctypes.c_char_p))

    # Initialize NSSound
    NSSound = objc.objc_getClass(b"NSSound")
    alloc = msg(NSSound, b"alloc")
    sound = msg(
        alloc,
        b"initWithContentsOfFile:byReference:",
        (ns_path, ctypes.c_void_p),
        (True, ctypes.c_bool),
    )
    if not sound:
        raise RuntimeError(f"macOS NSSound failed to load: {filepath}")

    # Play sound
    msg(sound, b"play")

    if block:
        # Poll [sound isPlaying] until finished
        objc.objc_msgSend.restype = ctypes.c_bool
        sel_is_playing = objc.sel_registerName(b"isPlaying")
        objc.objc_msgSend.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
        while objc.objc_msgSend(sound, sel_is_playing):
            time.sleep(0.05)


# --- Linux (ALSA / libasound.so.2) ---
def _play_linux(filepath: str, block: bool) -> None:
    if not block:
        import threading
        threading.Thread(target=_play_linux, args=(filepath, True), daemon=True).start()
        return

    asound_path = ctypes.util.find_library("asound") or "libasound.so.2"
    asound = ctypes.cdll.LoadLibrary(asound_path)

    # Set function signatures
    asound.snd_pcm_open.argtypes = [
        ctypes.POINTER(ctypes.c_void_p),
        ctypes.c_char_p,
        ctypes.c_int,
        ctypes.c_int,
    ]
    asound.snd_pcm_set_params.argtypes = [
        ctypes.c_void_p,
        ctypes.c_int,
        ctypes.c_int,
        ctypes.c_uint,
        ctypes.c_uint,
        ctypes.c_int,
        ctypes.c_uint,
    ]
    asound.snd_pcm_writei.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_ulong]
    asound.snd_pcm_writei.restype = ctypes.c_long
    asound.snd_pcm_drain.argtypes = [ctypes.c_void_p]
    asound.snd_pcm_close.argtypes = [ctypes.c_void_p]

    SND_PCM_STREAM_PLAYBACK = 0
    SND_PCM_ACCESS_RW_INTERLEAVED = 3
    FORMAT_MAP = {
        1: 0,   # SND_PCM_FORMAT_U8 (8-bit unsigned)
        2: 2,   # SND_PCM_FORMAT_S16_LE (16-bit signed little-endian)
        3: 10,  # SND_PCM_FORMAT_S24_3LE (24-bit signed 3-byte)
        4: 6,   # SND_PCM_FORMAT_S32_LE (32-bit signed little-endian)
    }

    with wave.open(filepath, "rb") as wf:
        channels = wf.getnchannels()
        sample_width = wf.getsampwidth()
        rate = wf.getframerate()
        frames = wf.readframes(wf.getnframes())

    if sample_width not in FORMAT_MAP:
        raise ValueError(f"Unsupported WAV bit depth: {sample_width * 8}-bit")

    pcm = ctypes.c_void_p()
    err = asound.snd_pcm_open(ctypes.byref(pcm), b"default", SND_PCM_STREAM_PLAYBACK, 0)
    if err < 0:
        raise RuntimeError(f"ALSA snd_pcm_open failed with error code {err}")

    try:
        err = asound.snd_pcm_set_params(
            pcm,
            FORMAT_MAP[sample_width],
            SND_PCM_ACCESS_RW_INTERLEAVED,
            channels,
            rate,
            1,       # Allow soft resampling
            500000,  # 0.5s latency buffer
        )
        if err < 0:
            raise RuntimeError(f"ALSA snd_pcm_set_params failed with error code {err}")

        frame_size = channels * sample_width
        total_frames = len(frames) // frame_size
        written = 0

        while written < total_frames:
            offset = written * frame_size
            res = asound.snd_pcm_writei(pcm, frames[offset:], total_frames - written)
            if res < 0:
                asound.snd_pcm_prepare(pcm)  # Recover from buffer underrun
            else:
                written += res

        asound.snd_pcm_drain(pcm)
    finally:
        asound.snd_pcm_close(pcm)


if __name__ == "__main__":
    play_wav("sound.wav", block=True)

7

u/Momostein 23h ago

Absolutely horrid, darling. Good job.

1

u/itsmebo12 12h ago

Thanks you :D

So uh... "block" at the end of the code what means?

1

u/mr_frpdo 12h ago

Should the script wait while the sound plays or continue while it plays

15

u/Atmosck 1d ago

If you want to ship something that does stuff like this but doesn't require the user to install any dependencies, python is not the right language because it's interpereted.

1

u/Manostel-Jveive 19h ago

Pretty much this, half the point of the language is the ecosystem anyway

-10

u/Educational_Virus672 1d ago

no, python is turing complete(wwith full hardware control) on its own because practically you can write a exe file using built in open() and using sub process to run it
note - python can do most stuff with readability in mind this is just a analogy

7

u/SCD_minecraft 1d ago

Turing Completeness does not assume any form of IO and sounds is very much IO

-2

u/Educational_Virus672 1d ago

yes thats why i added "with hardware contol" next to it i mean python isnt sandboxed, is it? it can access any sys component without third party library and python can access sound

0

u/SCD_minecraft 1d ago

It can not

Pure python is just flow control

If you want to do anything, you need to use C defined functions, many of which are not in std lib

2

u/hugthemachines 1d ago

Pure python is just flow control

That is a false statement.

0

u/SCD_minecraft 23h ago

Okay

Write me a calculator with user input without using a single C defined function

Btw, input is defined in C

Same with print

And a + b (int.__add__)

No language can work without functions defined in other language, and just so happen that 90% of python's standard library is defined in C

4

u/hugthemachines 22h ago

Python:

def add(a, b):
    return a + b

C:

int x = a + b;    

The fact that Python's runtime is written in C doesn't make Python "just flow control". By that logic, C is just flow control too because it ultimately becomes machine code.

1

u/Educational_Virus672 21h ago

write me a problem without binary type a question..

0

u/SCD_minecraft 18h ago

No language can work without functions defined in other language

Thank you for agreeing with me

1

u/Educational_Virus672 16h ago

bro im not agreeing with the statement python is not a strict api because it actively updates it

6

u/Atmosck 1d ago

My point is the user has to set up the python environment because it doesn't compile to a self-contained program.

1

u/SCD_minecraft 1d ago

Technically, there are compilers that compile python file AND interpreter into binary, so anyone* can run it

6

u/SCD_minecraft 1d ago

Not really, at least not arbitrary sound

What's wrong with pip it in? User needs to download your code anyway, why not also download some extra lib?

5

u/Educational_Virus672 1d ago edited 1d ago

best bet

mod = "play" # or "afplay" for mac
subprocess.Popen([mod, "your_audio.mp3"])

but window is visible so, it is hard to use it properly

5

u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 1d ago

The short answer is "no", although technically you can run print('\a') to get a "bell sound". Not that it helps you play audio files.

4

u/LayotFctor 1d ago

Use sys.platform to check platform, then subprocesses to call os packages. Linux is quite fragmented between distros, so you have to check whether the audio package you need is even installed.

4

u/Educational_Fold1428 1d ago

I went down the same road when I was messing about sorting music lists, and ended up just playing the file in VLC while the script ran. If you only need to check a wav is what you think it is the wave module reads it fine, but actual playback is where it gets annoying.

2

u/gmes78 1d ago

No. You need to interact with OS APIs to play audio. Unless you want to invoke the C APIs yourself using ctypes (which you really shouldn't do), you need third-party libraries for that.

2

u/Free-Good9203 1d ago

python 3.13 dropped the legacy stdlib audio modules under pep 594 (`ossaudiodev`, `aifc`, `sunau`, `sndhdr`), so aside from `winsound` on windows and `wave` for reading or writing raw wav bytes, there is no built-in cross-platform audio player left in the stdlib. for a truly zero-install script that plays wav files across platforms, branching on `sys.platform` works well: `winsound.PlaySound` on windows, `afplay` via `subprocess` on macos, and checking `shutil.which` for `pw-play`, `paplay`, or `aplay` on linux. if your constraint is only 'no internet on the target machine' rather than strictly stdlib-only, you can also run `pip download -d wheels sounddevice` once online and install offline with `pip install --no-index --find-links wheels sounddevice`.

2

u/cdcformatc 1d ago

there's that one character that when you print it it plays the chime sound. that's pretty much the only audio you can play without a library