Home > Backend Development > Python Tutorial > How to Play Sound Files in Python: The Simplest Methods for Windows and Linux

How to Play Sound Files in Python: The Simplest Methods for Windows and Linux

Mary-Kate Olsen
Release: 2024-10-24 19:44:29
Original
960 people have browsed it

How to Play Sound Files in Python: The Simplest Methods for Windows and Linux

Easiest Way to Play Sound in Python

Determining the most straightforward approach to play sound files in Python can involve considerations of platform independence and dependency requirements. While Pygame presents a capable option, it may be excessive for solely handling audio playback.

Windows

For Windows systems, the built-in winsound module offers an accessible solution:

import winsound

winsound.PlaySound('sound.wav', winsound.SND_FILENAME)
Copy after login

Linux

On Linux, the ossaudiodev module provides an alternative:

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()
Copy after login

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

The above is the detailed content of How to Play Sound Files in Python: The Simplest Methods for Windows and Linux. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template