Fork me on GitHub

一 基本概念

1.这里实现了电脑的安全报警系统,假如有人不小心动了你的电脑,立即触发报警系统。报警是通过pc机的声卡播放报警信号。

2.该的基础是对python的pyxhook和wave库的合理应用。

二 源码解析

1.定义报警声音播放函数from__future__import print_function

# Libraries we need
import pyxhook
import time


import pyaudio
import wave

filename = 'air_tone.wav'

# Set chunk size of 1024 samples per data frame
chunk = 1024

# Open the sound file
wf = wave.open(filename, 'rb')

def warning_func():
    # Create an interface to PortAudio
    p = pyaudio.PyAudio()

    # Open a .Stream object to write the WAV file to
    # 'output = True' indicates that the sound will be played rather than recorded
    stream = p.open(format = p.get_format_from_width(wf.getsampwidth()),
                channels = wf.getnchannels(),
                rate = wf.getframerate(),
                output = True)

    # Read data in chunks
    data = wf.readframes(chunk)

    # Play the sound by writing the audio data to the stream
    while data != '':
        stream.write(data)
        data = wf.readframes(chunk)

    # Close and terminate the stream
    stream.close()
    p.terminate()


# This function is called every time a key is presssed
def kbevent(event):
    global running
    # print key info
    print(event)

    # If the ascii value matches spacebar, terminate the while loop
    if event.Ascii == 32:
        running = False
    else:
        warning_func()


def onMouseEvent(event):
    print(event)
    warning_func()


if __name__=='__main__':

    # Create hookmanager
    hookman = pyxhook.HookManager()
    # Define our callback to fire when a key is pressed down
    hookman.KeyDown = kbevent
    # Hook the keyboard
    hookman.HookKeyboard()

    # Hook the mouse
    hookman.MouseAllButtonsDown = onMouseEvent
    hookman.HookMouse()

    # Start our listener
    hookman.start()

    # Create a loop to keep the application running
    running = True
    while running:
        time.sleep(0.1)

    # Close the listener when we are done
    hookman.cancel()

 

 

三 总结

1.上面的源码基本实现了这个功能,不过,还需有一些完善的地方。

2. 除了报警,日志保存也是一个非常必要的措施

3.程序不能用快捷键杀死

4.接下来我们拭目以待。

posted on 2022-05-04 21:15  虚生  阅读(136)  评论(0编辑  收藏  举报