原创 

python实现录制电脑屏幕视频带音频

分类:python    291人阅读    IT小君  2023-05-13 22:26

您可以使用OpenCV、PyAudio和PyAutoGUI库来实现 python 录屏录音到一个视频文件。

以下是示例代码:

import numpy as np
import cv2
import pyaudio
import wave
import threading
import pyautogui


# 设置录屏区域
screen_size = (1920, 1080)
fourcc = cv2.VideoWriter_fourcc(*"XVID")
out = cv2.VideoWriter("output.avi", fourcc, 20.0, (screen_size))

# 设置录音参数
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100

frames = []

# 开启录音线程
def record_audio():
    p = pyaudio.PyAudio()
    stream = p.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)

    while True:
        data = stream.read(CHUNK)
        frames.append(data)

        if len(data) == 0:
            break

    stream.stop_stream()
    stream.close()
    p.terminate()


# 开启录屏线程
def record_screen():
    while True:
        # 获取屏幕内容
        img = pyautogui.screenshot()
        # 转换为OpenCV格式
        frame = np.array(img)
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        # 写入视频
        out.write(frame)
        # 显示录制内容
        cv2.imshow("screenshot", frame)
        # 设置按键终止录屏
        if cv2.waitKey(1) == ord("q"):
            break

    # 释放资源
    out.release()
    cv2.destroyAllWindows()


# 录音线程
audio_thread = threading.Thread(target=record_audio)
audio_thread.start()


# 录屏线程
screen_thread = threading.Thread(target=record_screen)
screen_thread.start()

# 主线程等待录音和录屏线程完成
audio_thread.join()
screen_thread.join()


# 保存录音文件
wf = wave.open("output.wav", "wb")
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b"".join(frames))
wf.close()


# 把音频文件添加到视频文件中
video = cv2.VideoCapture('output.avi')
audio = wave.open('output.wav')
frame_rate = video.get(cv2.CAP_PROP_FPS)
sample_rate = audio.getframerate()
frame_duration = 1.0 / frame_rate
time_per_sample = 1.0 / sample_rate
sample_per_frame = int(frame_duration / time_per_sample)


while True:
    ret, frame = video.read()
    if not ret:
        break


    sound_data = audio.readframes(sample_per_frame)
    if len(sound_data) == 0:
        break


    sound_data = np.frombuffer(sound_data, dtype=np.int16)
    sound_data = np.array(sound_data, dtype=np.float64)
    sound_data /= (2**15)


    cv2.imshow('video', frame)
    if cv2.waitKey(1) == ord('q'):
        break



    # 叠加音频

    if CHANNELS == 2:
        sound_data = np.column_stack((sound_data, sound_data))

    sound_data = cv2.resize(sound_data, (frame.shape[1], 1))
    video.write(np.array(frame, dtype=np.uint8))


# 释放资源
audio.close()
video.release()
cv2.destroyAllWindows()

这段代码将屏幕截图转换为OpenCV格式,并将帧写入视频。在录制完成后,我们将内存中的音频数据写入WAV文件。最后,我们打开视频和音频文件,将音频数据添加到视频中,并将它们输出到一个新的视频文件中。在这个过程中,我们分别开启了三个线程,一个线程用于录制音频,一个线程用于录制屏幕,最后一个线程用于将音频添加到视频中。它们分别在后台运行,并在程序结束时完成自己的任务。

支付宝打赏 微信打赏

如果文章对你有帮助,欢迎点击上方按钮打赏作者

 工具推荐 更多»