python代码录屏录音
写的不是很好,不如那些obs的录屏软件,而且没有实现音频和视频的合并,请多见谅。
def audio_record() 实现音频录制
def video_record() 实现视频录制
def on_press(key) 按键监听
import time,threading
from datetime import datetime
import pynput
from PIL import ImageGrab
from cv2 import *
import numpy as np
import pyaudio
import wave
from pynput.keyboard import Key,Listener
def audio_record():
name = datetime.now().strftime('%Y-%m-%d %H-%M-%S')
CHUNK=1024
FORMAT=pyaudio.paInt16#编码格式
CHANNELS=1 #单声道
RATE=16000#采样率
audio=pyaudio.PyAudio()
idx=2#内录设备号
#逐一查找声音设备
# for i in range(audio.get_device_count()):
# InFo=audio.get_device_info_by_index(i)
# print(InFo)
# if InFo['name'].find('立体声混音')>=0 and InFo['hostApi']==0:
# idx = i
if idx:
stream=audio.open(format=FORMAT,#音频流wav格式
channels=CHANNELS,#单声道
rate=RATE,#采样率
input=True,
input_device_index=idx,#指定内录设备的id,可以不写,使用win的默认录音设备
frames_per_buffer=CHUNK,#声道
)
frames=[]#录制的音频流
print('3秒后开始录音----') # 可选
time.sleep(3)
print('开始录音!')
global start_time
start_time = time.time()
while True:
if flag:
print("录音结束!")
global final_time
final_time = time.time()
stream.stop_stream()
stream.close()
# 打开用于保存数据的文件
wf = wave.open('%s.wav' % name, 'wb')
# 设置音频参数
wf.setnchannels(CHANNELS)
wf.setsampwidth(audio.get_sample_size(FORMAT))
wf.setframerate(RATE)
# 写入数据
wf.writeframes(b''.join(frames))
# 关闭文件
wf.close()
# 结束pyaudio
audio.terminate()
break
data = stream.read(CHUNK)
frames.append(data)
return
def video_record(): # 录入视频
name = datetime.now().strftime('%Y-%m-%d %H-%M-%S')
screen = ImageGrab.grab() # 获取当前屏幕
width, high = screen.size # 获取当前屏幕的大小
fourcc = VideoWriter_fourcc('X', 'V', 'I', 'D') # MPEG-4编码,文件后缀可为.avi .asf .mov等
video = VideoWriter('%s.avi' % name, fourcc, 30, (width, high)) # (文件名,编码器,帧率,视频宽高)
print('3秒后开始录屏----') # 可选
time.sleep(3)
print('开始录屏!')
global start_time
start_time = time.time()
while True:
if flag:
print("录屏结束!")
global final_time
final_time = time.time()
video.release() #释放
break
im = ImageGrab.grab() # 图片为RGB模式
imm = cvtColor(np.array(im), COLOR_RGB2BGR) # 转为opencv的BGR模式
video.write(imm) #写入
# cv2.imshow('max',imm)
# cv2.waitKey(0)
# time.sleep(5) # 等待5秒再次循环
return
def on_press(key): # 监听按键eerr
try:
global flag
if key ==key.home:
flag = True # 改变
# 返回False,键盘监听结束!
return
elif key == key.end:
flag = False
v= threading.Thread(target=video_record,daemon=True)
a= threading.Thread(target=audio_record,daemon=True)
v.start()
a.start()
except :
return
def video_info(): # 视频信息
video = VideoCapture('%s.avi' % name) # 记得文件名加格式不要错!
fps = video.get(CAP_PROP_FPS)
Count = video.get(CAP_PROP_FRAME_COUNT)
size = (int(video.get(CAP_PROP_FRAME_WIDTH)), int(video.get(CAP_PROP_FRAME_HEIGHT)))
print('帧率=%.1f'%fps)
print('帧数=%.1f'%Count)
print('分辨率',size)
print('视频时间=%.3f秒'%(int(Count)/fps))
print('录制时间=%.3f秒'%(final_time-start_time))
print('推荐帧率=%.2f'%(fps*((int(Count)/fps)/(final_time-start_time))))
def run():
# 当前的时间(当文件名)
with Listener(on_press=on_press) as listener: # 键盘监听
listener.join() # 等带进程
return
time.sleep(1) # 等待视频释放过后
video_info()
if __name__ == '__main__':
for i in range(10):
name = datetime.now().strftime('%Y-%m-%d %H-%M-%S')
run()
print(i)