Home >Backend Development >Python Tutorial >Here are a few title options, tailored to the question-answer format: **Focusing on the challenge:** * **How to Play Sounds in Python: A Cross-Platform Solution** * **Playing Audio Files in Python:
Playing Sounds in Python
When it comes to playing audio files in Python, there are several options available. However, if your goal is to achieve cross-platform compatibility with minimal dependencies, the choice becomes more straightforward.
Windows Solution using winsound:
For Windows systems, the built-in winsound module provides a convenient way to play sound files (.wav).
<code class="python">import winsound winsound.PlaySound('sound.wav', winsound.SND_FILENAME)</code>
Linux Solution using ossaudiodev:
On Linux platforms, ossaudiodev offers a suitable alternative. It provides bindings for the Open Sound System, allowing you to play audio directly to the sound card.
<code class="python">from wave import open as waveOpen from ossaudiodev import open as ossOpen s = waveOpen('tada.wav','rb') (nc,sw,fr,nf,comptype, compname) = s.getparams( ) dsp = ossOpen('/dev/dsp','w') ... (Setting parameters, reading data, writing to device, and closing) ...</code>
The above is the detailed content of Here are a few title options, tailored to the question-answer format: **Focusing on the challenge:** * **How to Play Sounds in Python: A Cross-Platform Solution** * **Playing Audio Files in Python:. For more information, please follow other related articles on the PHP Chinese website!