Python是一種廣泛使用的高級編程語言,其功能強大且易于使用。Python可以用于制作多媒體內容,例如錄屏有聲的視頻。下面將介紹如何使用Python進行錄屏有聲。
# 導入必要的庫 import cv2 import numpy as np import pyaudio import wave import threading # 設置錄屏參數 screen_size = (1920, 1080) fps = 24.0 # 開啟屏幕錄制 screen_capture = cv2.VideoCapture(0) screen_capture.set(cv2.CAP_PROP_FRAME_WIDTH, screen_size[0]) screen_capture.set(cv2.CAP_PROP_FRAME_HEIGHT, screen_size[1]) screen_capture.set(cv2.CAP_PROP_FPS, fps) # 設置音頻錄制參數 audio_chunk_size = 1024 audio_sample_rate = 44100 audio_channels = 2 audio_format = pyaudio.paInt16 audio_seconds = 10 # 開始錄制音頻 audio_capture = pyaudio.PyAudio() audio_stream = audio_capture.open(format=audio_format, channels=audio_channels, rate=audio_sample_rate, input=True, frames_per_buffer=audio_chunk_size) # 啟動音頻錄制線程 audio_frames = [] is_recording_audio = True def record_audio(): global audio_frames while is_recording_audio: audio_data = audio_stream.read(audio_chunk_size) audio_frames.append(np.fromstring(audio_data, dtype=np.int16)) audio_thread = threading.Thread(target=record_audio) audio_thread.start() # 開始錄制視頻 video_frames = [] is_recording_video = True while is_recording_video: ret, frame = screen_capture.read() video_frames.append(frame) # 錄制結束,停止音頻錄制線程 is_recording_audio = False audio_thread.join() audio_stream.stop_stream() audio_stream.close() audio_capture.terminate() # 將視頻和音頻寫入文件 video_writer = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc(*'XVID'), fps, screen_size) for frame in video_frames: video_writer.write(frame) audio_frames = np.concatenate(audio_frames, axis=0) audio_writer = wave.open('output.wav', 'wb') audio_writer.setnchannels(audio_channels) audio_writer.setsampwidth(audio_capture.get_sample_size(audio_format)) audio_writer.setframerate(audio_sample_rate) audio_writer.writeframes(audio_frames.tobytes()) audio_writer.close() # 完成 print('錄制完成!')
以上代碼包括了屏幕錄制、音頻錄制和視頻和音頻合成等多個步驟。用戶可以根據需要調整參數和設置,在Python中實現錄屏有聲非常容易。
上一篇html實例小代碼
下一篇python 形參實參