Home  >  Article  >  Backend Development  >  How to Play Audio Files in Python with Minimal Dependencies?

How to Play Audio Files in Python with Minimal Dependencies?

Linda Hamilton
Linda HamiltonOriginal
2024-10-25 04:07:18544browse

How to Play Audio Files in Python with Minimal Dependencies?

Playing Audio Files in Python with Minimal Dependencies

Python lacks a cross-platform module for playing sound files out of the box. For Windows systems, winsound provides a simple solution:

<code class="python">import winsound

winsound.PlaySound('sound.wav', winsound.SND_FILENAME)</code>

For Linux, ossaudiodev offers more flexibility:

<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')
try:
  from ossaudiodev import AFMT_S16_NE
except ImportError:
  from sys import byteorder
  if byteorder == "little":
    AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
  else:
    AFMT_S16_NE = ossaudiodev.AFMT_S16_BE
dsp.setparameters(AFMT_S16_NE, nc, fr)
data = s.readframes(nf)
s.close()
dsp.write(data)
dsp.close()</code>

(Credit for ossaudiodev: Bill Dandreta https://mail.python.org/pipermail/python-list/2004-October/288905.html)

The above is the detailed content of How to Play Audio Files in Python with Minimal Dependencies?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn