How to Play a .WAV File in Python

Python's extensive set of standard libraries enable programmers to handle a wide range of programming tasks. Python is a “batteries included” language: nothing else to add. True to form, Python has built-in functions for reading and writing some audio file formats. Unfortunately, there are no standard ways to play audio files across the wide range of hardware and operating systems the Python programmer might encounter. Standard Python does, however, include a simple way to get the job done. The “os” or operating system module allows the programmer to use the underlying operating system to do the actual work of playing the file.

...
Python provides tools to play audio files.

Playing .Wav Files with Python on Linux

Step

Press the "ALT" and F2 key simultaneously. Enter "python" in the input box. Select the option to allow Python to run in the Linux terminal. Click on the "Run" button.

Step

At the Python prompt, import the os module by typing "import os".

Step

Enter the following system call on the Python command line.

Step

os.system("aplay sounds/test.wav")

Step

Replace the parameter "sounds/test.wav" with the location and name of the .wav file to be played.

Step

Press the return or enter key to execute the code.

Playing .Wav Files with Python on Windows XP

Step

Click on the Start menu button and then select "Run" to load the Windows command interpreter.

Step

At the Windows command prompt, type “python” and then press the enter key. Some installations require the path to the directory containing the Python binaries in order to locate and load the interpreter. For example if Python 2.7 is the installed version, to load the Python interpreter enter “c:\python27\python.”

Step

At the Python command line prompt, enter “import os” and then press the enter key.

Step

Enter the following command in the Python interpreter prompt to play the wave file.

Step

os.system("start /min mplay32 /play /close tada.wav")

Step

Replace the parameter "sounds/test.wav" with the location and name of the .wav file to be played.

Step

Press the return or enter key to play the wave file.