Python+opencv+pyaudio實現(xiàn)帶聲音屏幕錄制
基于個人的愛好和現(xiàn)實的需求,決定用Python做一個屏幕錄制的腳本。因為要看一些加密的視頻,每次都要登錄,特別麻煩,遂決定用自己寫的腳本,將加密視頻的播放過程全程錄制下來,這樣以后看自己的錄播就好了。結(jié)合近期自己學(xué)習(xí)的內(nèi)容,正好用Python來練練手,鞏固自己的學(xué)習(xí)效果。
經(jīng)過多番搜索,決定采用Python+opencv+pyaudio來實現(xiàn)屏幕錄制。網(wǎng)上搜索到的錄屏,基本都是不帶聲音的,而我要實現(xiàn)的是帶聲音的屏幕錄制。下面就開始一步一步的實現(xiàn)吧。
聲音錄制
import pyaudio
import wave
import sys
CHUNK = 1024
if len(sys.argv) < 2:
print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0])
sys.exit(-1)
wf = wave.open(sys.argv[1], 'rb')
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=True)
data = wf.readframes(CHUNK)
while data != '':
stream.write(data)
data = wf.readframes(CHUNK)
stream.stop_stream()
stream.close()
p.terminate()
簡潔回調(diào)函數(shù)版音頻錄制
import pyaudio
import wave
import time
import sys
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 10
WAVE_OUTPUT_FILENAME = "output.wav"
p = pyaudio.PyAudio()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
time_count = 0
def callback(in_data, frame_count, time_info, status):
wf.writeframes(in_data)
if(time_count < 10):
return (in_data, pyaudio.paContinue)
else:
return (in_data, pyaudio.paComplete)
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
input=True,
stream_callback=callback)
stream.start_stream()
print("* recording")
while stream.is_active():
time.sleep(1)
time_count += 1
stream.stop_stream()
stream.close()
wf.close()
p.terminate()
print("* recording done!")
視頻錄制(無聲音)
from PIL import ImageGrab
import numpy as np
import cv2
image = ImageGrab.grab()#獲得當(dāng)前屏幕
width = image.size[0]
height = image.size[1]
print("width:", width, "height:", height)
print("image mode:",image.mode)
k=np.zeros((width,height),np.uint8)
fourcc = cv2.VideoWriter_fourcc(*'XVID')#編碼格式
video = cv2.VideoWriter('test.avi', fourcc, 25, (width, height))
#輸出文件命名為test.mp4,幀率為16,可以自己設(shè)置
while True:
img_rgb = ImageGrab.grab()
img_bgr=cv2.cvtColor(np.array(img_rgb), cv2.COLOR_RGB2BGR)#轉(zhuǎn)為opencv的BGR格式
video.write(img_bgr)
cv2.imshow('imm', img_bgr)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video.release()
cv2.destroyAllWindows()
錄制的音頻與視頻合成為帶聲音的視頻
錄制200幀,帶音頻的MP4視頻,單線程
import wave
from pyaudio import PyAudio,paInt16
from PIL import ImageGrab
import numpy as np
import cv2
from moviepy.editor import *
from moviepy.audio.fx import all
import time
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
WAVE_OUTPUT_FILENAME = "output.wav"
p = pyaudio.PyAudio()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
audio_record_flag = True
def callback(in_data, frame_count, time_info, status):
wf.writeframes(in_data)
if audio_record_flag:
return (in_data, pyaudio.paContinue)
else:
return (in_data, pyaudio.paComplete)
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
input=True,
stream_callback=callback)
image = ImageGrab.grab()#獲得當(dāng)前屏幕
width = image.size[0]
height = image.size[1]
print("width:", width, "height:", height)
print("image mode:",image.mode)
k=np.zeros((width,height),np.uint8)
fourcc = cv2.VideoWriter_fourcc(*'XVID')#編碼格式
video = cv2.VideoWriter('test.mp4', fourcc, 9.5, (width, height))
#經(jīng)實際測試,單線程下最高幀率為10幀/秒,且會變動,因此選擇9.5幀/秒
#若設(shè)置幀率與實際幀率不一致,會導(dǎo)致視頻時間與音頻時間不一致
print("video recording!!!!!")
stream.start_stream()
print("audio recording!!!!!")
record_count = 0
while True:
img_rgb = ImageGrab.grab()
img_bgr=cv2.cvtColor(np.array(img_rgb), cv2.COLOR_RGB2BGR)#轉(zhuǎn)為opencv的BGR格式
video.write(img_bgr)
record_count += 1
if(record_count > 200):
break
print(record_count, time.time())
audio_record_flag = False
while stream.is_active():
time.sleep(1)
stream.stop_stream()
stream.close()
wf.close()
p.terminate()
print("audio recording done!!!!!")
video.release()
cv2.destroyAllWindows()
print("video recording done!!!!!")
print("video audio merge!!!!!")
audioclip = AudioFileClip("output.wav")
videoclip = VideoFileClip("test.mp4")
videoclip2 = videoclip.set_audio(audioclip)
video = CompositeVideoClip([videoclip2])
video.write_videofile("test2.mp4",codec='mpeg4')
看來要提高幀率必須使用隊列加多線程了,這一步等到以后來添加吧。不過總是覺得用OpenCV來實現(xiàn)視頻錄制,有點怪異,畢竟opencv是用來做圖像與視頻分析的,還是走正道認(rèn)真搗鼓opencv該做的事情吧。
以上這篇Python+opencv+pyaudio實現(xiàn)帶聲音屏幕錄制就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python請求域名requests.(url = 地址)報錯
本文主要介紹了python請求域名requests.(url = 地址)報錯,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02
解決Python串口接收無標(biāo)識不定長數(shù)據(jù)
這篇文章主要介紹了解決Python串口接收無標(biāo)識不定長數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09

