import pyaudio
import numpy as np
import ctypes
import time
import threading
FORMAT = pyaudio.paFloat32
CHANNELS =1
RATE =44100
CHUNK =1024
THRESHOLD =0.001classScrollLockController:def__init__(self):
self.user32 = ctypes.WinDLL('user32', use_last_error=True)
self.last_state =False
self.running =Truedefset_scrolllock(self, state):"""设置ScrollLock指示灯状态"""if state == self.last_state:return
self.last_state = state
key_state = ctypes.create_string_buffer(256)
self.user32.GetKeyboardState(ctypes.byref(key_state))
current_state =(ord(key_state[0x91])&1)!=0if current_state != state:
self.user32.keybd_event(0x91,0,0,0)
self.user32.keybd_event(0x91,0,0x0002,0)defaudio_monitor(self):"""监听音频并控制指示灯"""
audio = pyaudio.PyAudio()
stream = audio.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,input=True,
frames_per_buffer=CHUNK
)print("开始监听音频,按Ctrl+C退出...")try:while self.running:
data = stream.read(CHUNK)
audio_data = np.frombuffer(data, dtype=np.float32)
volume = np.sqrt(np.mean(np.square(audio_data)))if volume > THRESHOLD:
self.set_scrolllock(True)else:
self.set_scrolllock(False)
time.sleep(0.01)except KeyboardInterrupt:print("\n程序正在退出...")finally:
stream.stop_stream()
stream.close()
audio.terminate()
self.set_scrolllock(True)defstart(self):"""启动监控线程"""
self.thread = threading.Thread(target=self.audio_monitor)
self.thread.start()defstop(self):"""停止监控线程"""
self.running =False
self.thread.join()if __name__ =="__main__":try:print("注意:运行此程序需要安装pyaudio库")print("如果尚未安装,请先运行:pip install pyaudio numpy\n")
controller = ScrollLockController()
controller.start()whileTrue:
time.sleep(1)except KeyboardInterrupt:
controller.stop()print("程序已退出")
发布评论