Play a Sound with Python

ghz 3months ago ⋅ 30 views

What's the easiest way to play a sound file (.wav) in Python? By easiest I mean both most platform independent and requiring the least dependencies. pygame is certainly an option, but it seems overkill for just sound.

Answers

To play a .wav file in Python with minimal dependencies and good platform independence, one of the easiest options is to use the built-in winsound module on Windows or playsound for cross-platform needs. Here's a breakdown of both approaches:

1. For Windows (using winsound):

If you're on Windows, the winsound module is built-in, so you don't need to install any external libraries. This is the simplest method for Windows users.

import winsound

# Play the .wav file
winsound.PlaySound("yourfile.wav", winsound.SND_FILENAME)

2. Cross-platform (using playsound):

For cross-platform compatibility, the playsound library is a simple, lightweight option that works on both Windows and macOS/Linux. You'll need to install it first:

pip install playsound

Then, you can play the .wav file like this:

from playsound import playsound

# Play the .wav file
playsound('yourfile.wav')

This method has no additional heavy dependencies like pygame and supports multiple platforms easily.

Comparison:

  • winsound: Built-in, very lightweight but limited to Windows.
  • playsound: Cross-platform and easy to use, but requires installing a lightweight dependency.