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.
Things You'll Need
- Windows or Linux computer with Python version 2.5 or later installed
- Wave format audio file
Playing .Wav Files with Python on Linux
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.
At the Python prompt, import the os module by typing "import os".
Enter the following system call on the Python command line.os.system("aplay sounds/test.wav")Replace the parameter "sounds/test.wav" with the location and name of the .wav file to be played.
Press the return or enter key to execute the code.
Playing .Wav Files with Python on Windows XP
Click on the Start menu button and then select "Run" to load the Windows command interpreter.
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."
At the Python command line prompt, enter "import os" and then press the enter key.
Enter the following command in the Python interpreter prompt to play the wave file. os.system("start /min mplay32 /play /close tada.wav")Replace the parameter "sounds/test.wav" with the location and name of the .wav file to be played.
Press the return or enter key to play the wave file.
Tips & Warnings
- Python programmers have several open source audio libraries available that can provide the classes and methods needed to play popular audio file formats. These libraries often have dependencies: other libraries or files are needed in order for them to install and function.
- Python's "os.system()" function allows any standard operating system command to be executed that the Python interpreter has permission to execute. It is possible to insert commands to delete or access important data and applications.