Python implements screen recording software with audio
In Python, we can use pyautogui
and opencv
library to record screen, and use pyaudio
library to record audio. The following is an example of using these libraries to implement screen recording software with audio.
Install dependent libraries
First, we need to install the following dependencies:
pip install pyautogui opencv-python pyaudio
record screen
import cv2
import pyautogui
# 获取屏幕分辨率
screen_size = (1920, 1080)
# 创建视频编码器
fourcc = cv2.VideoWriter_fourcc(*"XVID")
out = cv2.VideoWriter("screen_record.avi", fourcc, 20.0, screen_size)
# 开始录制
while True:
# 获取屏幕截图
img = pyautogui.screenshot()
frame = np.array(img)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# 写入视频
out.write(frame)
# 按下'q'键停止录制
if cv2.waitKey(1) == ord('q'):
break
# 释放资源
out.release()
cv2.destroyAllWindows()
The above code converts the screenshot to video and saves it as screen_record.avi
a file. You can stop recording by pressing the 'q' key on your keyboard.
record audio
import pyaudio
import wave
# 录音参数
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 10
WAVE_OUTPUT_FILENAME = "audio_record.wav"
# 初始化音频录制器
audio = pyaudio.PyAudio()
# 打开音频流
stream = audio.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
# 开始录制
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
# 停止录制
stream.stop_stream()
stream.close()
audio.terminate()
# 保存录制的音频
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(audio.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
The above code will record 10 seconds of audio and save it as audio_record.wav
a file.
Merge audio and video
import moviepy.editor as mp
# 加载视频和音频文件
video = mp.VideoFileClip("screen_record.avi")
audio = mp.AudioFileClip("audio_record.wav")
# 合并视频和音频
final = video.set_audio(audio)
# 保存最终文件
final.write_videofile("final_output.mp4")
The above code combines the video and audio files into one file and saves it as final_output.mp4
a file.
in conclusion
By using pyautogui
, opencv
and pyaudio
libraries, we can easily realize the function of screen recording software with audio. You can modify and extend it according to your needs. Note that before running the code, make sure you have installed the required dependencies.