在python中,如何在按键事件之前发出连续的哔声或其他简单的声音

2024-10-02 18:21:44 发布

您现在位置:Python中文网/ 问答频道 /正文

为了让用户测试/调整音量,我用python编写了以下简单的程序。它使用winsound。哔()发出重复的嘟嘟声,直到被msvcrt.kbhit()事件,并使用线程来允许在winsound。哔()正在进行:


import winsound, threading, msvcrt

class soundThread(threading.Thread):
    def __init__(self, threadID, pitch, duration):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.pitch = pitch
        self.duration = duration
    def run(self):
        soundTone(self.pitch,self.duration)        

def soundTone(pitch,duration):
    winsound.Beep(pitch,int(duration*1000))

def main():
    """main code module"""
    print("The computer will play a beeping tone at a frequency of 440 MHz.")
    print("It will continue to do so until you press a key which will cause the")
    print("sound to stop and the program to exit.  While the tone is sounding")
    print("adjust your volume so that you can hear the tone clearly and")
    print("comfortably.")
    print("")
    print("Tone starting now...")

    loopBool = True
    soundBool = True
    i = 0;
    while loopBool:
        i+=1
        # make beeping sound
        if soundBool:
            beep = soundThread(i,440,2.0)
            beep.start()

        # stop loop if a key is pressed
        if msvcrt.kbhit():
            loopBool = False
            print("Key press detected.  Waiting for sound to stop...")

        # don't make new beep thread if current one is still active
        if beep.isAlive():
            soundBool = False
        else:
            soundBool = True

    print("Sound stopped.  Exiting program.")

if __name__ == '__main__':
    main()

所以代码本身运行得很好。不管从美学上说我真的不喜欢winsound。哔()必须反复启动和停止,当按下某个键时,程序必须等待当前的Beep()线程结束,然后整个程序才能结束。但是,我想不出任何使用winsound的方法,也找不到任何其他内置的模块来允许这样简单地生成声音。在

我在这个网站上看到了一些非常相似的问题,但是所有的解决方案都需要非标准的模块,比如audiolab或PyMedia,但是如果可能的话,我希望使用标准模块。有没有办法在键盘中断前发出连续的哔哔声,而不必安装任何非标准模块?如果基本模块没有任何方法,那么我使用的是Anaconda python发行版,因此我至少可以访问numpy和scipy等,尽管我怀疑这些包在这里是否有用。在


Tags: 模块thetoself程序ifmaindef