1 pynput 庫,可以全局監聽鍵盤、鼠標事件。
安裝方法:
a 下載 pynput-1.4.5-py2.py3-none-any.whl到本地。
b pip
2 代碼
from datetime import datetime
from PIL import ImageGrab
from cv2 import *
import numpy as np
from pynput import keyboard
import threading
def record_screen():
global name
name = datetime.now().strftime("%Y-%m-%d %H-%M-%S")
screen = ImageGrab.grab()
width, high = screen.size
fourcc = VideoWriter_fourcc('X', 'V', 'I', 'D')
video = VideoWriter('%s.avi' % name, fourcc, 16, (width, high))
print("record start !!!")
while True:
if flag:
print("record end !!!")
video.release()
break
img = ImageGrab.grab()
imm = cvtColor(np.array(img), COLOR_RGB2BGR) # 轉爲opencv的BGR模式
video.write(imm)
# 視頻信息
video = VideoCapture('%s.avi' % name)
fps = video.get(CAP_PROP_FPS)
frames = video.get(CAP_PROP_FRAME_COUNT)
print('幀率=%.1f'%(fps))
print('幀數=%.1f'%(frames))
print('分辨率=(%d,%d)'%(int(video.get(CAP_PROP_FRAME_WIDTH)), int(video.get(CAP_PROP_FRAME_HEIGHT))))
print('時間=%.2f秒' % (int(frames) / fps))
return
def on_press(key): # 監聽按鍵
global flag
if key == keyboard.Key.home:
flag = True
return False # 返回False,鍵盤監聽結束
if __name__ == '__main__':
flag = False
th = threading.Thread(target=record_screen)
th.start()
with keyboard.Listener(on_press=on_press) as listener:
listener.join()
pass
3 效果
運行程序,開始錄製。按home鍵結束錄製。
安裝pyaudio
Python3.6直接pip即可。