Tuesday, May 3, 2011

Try the Python WinSound API

By Vasudev Ram - www.dancingbison.com


UPDATE: Added more info and a link to the WinSound docs to this post.


The Python WinSound API is built-in to Python on the Windows platform. You can use it to play a sound of a specific frequency for a specific duration (in milliseconds). The API also lets you play a sound from a WAV file, or from the contents of a WAV file stored in a string, and also lets you play standard Windows registry sounds that are associated with different events/actions in Windows, such as displaying different kinds of dialogs (alert, question, exiting Windows sound, etc.). It also lets you play a sound repeatedly.


This is the Python docs page for the WinSound API


Here is a very simple program to try out the Python WinSound API.

Copy-paste the program below into a text editor file, save it with some filename like test_win_sound.py and then run it with Python like this:

C:\> python test_win_sound.py

Switch on your PC speakers first, if needed.

The program has a doubly nested loop that iterates over a few durations and within those, iterates over a few frequencies, and in each iteration, plays a sound at that frequency for that duration.

Here is the program:


#------------------------------------------------------------
# test_win_sound.py - testing the Python WinSound API.
# Author: Vasudev Ram - www.dancingbison.com
# Will work only on Windows.
#------------------------------------------------------------
# imports

import time import winsound

#------------------------------------------------------------

def play_note(): pass

#------------------------------------------------------------

def test_play_freq_list(freq_list, dur=500): for freq in freq_list: winsound.Beep(freq, dur)

#------------------------------------------------------------

def main(): for dur in (100, 200, 300, 400): test_play_freq_list(range(300, 1200, 100), dur) time.sleep(2)

#------------------------------------------------------------

if __name__ == "__main__": main()

#------------------------------------------------------------


Posted via email
- Vasudev Ram - Dancing Bison Enterprises

No comments: