Detecting Windows System sounds with Python

时间:2018-01-23 19:20:21

标签: python audio

I have a python script that pulls the cell values from a spreadsheet and inputs it into a program. Problem is that if there is an error that occurs when the information is being input (duplicate value, navigational error, sql error, etc) the script will not recognize that there is an error and just keep running. I'd like to find a way to have the script recognize when these errors occur and hold the script or take another action.

All of the errors vary between each other, but all of them produce a prompt window specifying the error code, the description, and they it plays the default "Windows Background.wav" sound in C:\Windows\media when it. The only thing that remains consistent through all possible errors is that sound so I thought I could have Python store that sound as a variable and constantly check to see if it has been triggered.

I saw modules like pyaudio, audioread, and winsound, but none of them seemed to have any way to read the wav file, store it as a variable, and then monitor the output of the system sounds on the volume mixer to check for it. Hoping there is a solution for this or possibly another way of going about checking for any errors that might occur with the program the script interacts with.

1 个答案:

答案 0 :(得分:0)

<强> EDIT1
如果您确实需要播放本机窗口声音,则可以使用winsound模块。 有关模块和可用音调的更多详细信息here.

winsound安装为:

pip install winsound.

当您从电子表格中读取时,请通过try-except块。

winsound

相同的示例如下
import winsound

try:
    data = int(raw_input("Enter a number:" ))
except ValueError:
    print "Data type mismatch"
    winsound.PlaySound("*", winsound.SND_ALIAS)   

修改
您可能希望尝试从电子表格中读取包装数据,除了块和错误(基于您期望的数据类型),您可以使用pydub来播放音频。

您也可以使用其他模块,但在pydub中播放音频是一个班轮 有关pydub is over here的更多详情。

将pydub安装为:

pip install pydub

这是一个小实验,当输入值不是整数时播放音频(哔哔声)。

from pydub import AudioSegment
from pydub.playback import play

audio_file = "alert.wav"
sound = AudioSegment.from_wav(audio_file)

try:
    data = int(raw_input("Enter a number:" ))
except ValueError:
    print "Data type mismatch"
    play(sound)

这将播放&#34; alert.wav&#34; (如果输入的是整数以外的任何内容,则基本上是10k sine_wave(beep)文件)。

输出

>>> 
Enter a number:5
>>> ================================ RESTART ================================
>>> 
Enter a number:number
Data type mismatch
>>>