Sound-playing interface for Windows in Python (winsound)


The winsound module is specific to Python installation on Windows operating system. The module defines following functions −

Beep()

When this function is called a beep is heard from the PC’s speaker. The function needs two parameters. The frequency parameter specifies frequency of the sound, and must be in the range 37 through 32,767 hertz. The duration parameter specifies duration of sound in .

>>> import winsound
>>> winsound.Beep(1000,500)

MessageBeep()

This function plays a sound as specified in the registry. The type argument specifies which sound to play. Possible values are −

-1, MB_ICONASTERISK, MB_ICONEXCLAMATION, MB_ICONHAND, MB_ICONQUESTION, and MB_OK (default).

The value -1 produces a "simple beep"

>>> winsound.MessageBeep()

PlaySound()

This function Calls the underlying PlaySound() function from the Platform API. The function needs two parameters. The sound parameter may be a filename, a system sound alias, or audio data as a bytes-like object. Its interpretation depends on the value of flags. The flags are as defined below:

SND_FILENAMEThe sound parameter is the name of a WAV file.
SND_LOOPPlay the sound repeatedly
SND_MEMORYThe sound parameter to PlaySound() is a memory image of a WAV file, as a bytes-like object.
SND_ASYNCReturn immediately, allowing sounds to play asynchronously.
SND_NODEFAULTIf the specified sound cannot be found, do not play the system default sound.
SND_NOSTOPDo not interrupt sounds currently playing.

Following statement plays the given WAV file.

>>> winsound.PlaySound('sample.wav', winsound.SND_FILENAME|winsound.SND_NOWAIT)

SND_ALIAS

The Windows registry keys are associated with sound names.If the registry contains no such name, play the system default sound unless SND_NODEFAULT. All Win32 systems support the following:

PlaySound() nameCorresponding Control Panel Sound name
'SystemAsterisk'Asterisk
'SystemExclamation'Exclamation
SystemExit'Exit Windows
'SystemHand'Critical Stop
SystemQuestion'Question

For example following statement plays Windows Exit sound.

>>> winsound.PlaySound("SystemExit", winsound.SND_ALIAS)

The winsound module also defines following sounds

MB_ICONASTERISKPlay the SystemDefault sound.
MB_ICONEXCLAMATIONPlay the SystemExclamation sound.
MB_ICONHANDPlay the SystemHand sound.
MB_ICONQUESTIONPlay the SystemQuestion sound.
MB_OKPlay the SystemDefault sound

Updated on: 30-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements