import pyaudio
import wave
from PIL import ImageGrab
import cv2
import threading
import time
from numpy import array
from moviepy.editor import *
import os
class PyRecord:
def __init__(self, file_path="test"):
self.allow_record = True
self.file_path = file_path
def record\_audio(self):
# 如无法正常录音 请启用计算机的"立体声混音"输入设备
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 11025
p = pyaudio.PyAudio()
stream = p.open(
format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames\_per\_buffer=CHUNK,
)
wf = wave.open(self.file\_path + ".wav", "wb")
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get\_sample\_size(FORMAT))
wf.setframerate(RATE)
while self.allow\_record:
data = stream.read(CHUNK)
wf.writeframes(data)
stream.stop\_stream()
stream.close()
p.terminate()
wf.close()
def record\_screen(self):
im = ImageGrab.grab()
video = cv2.VideoWriter(
self.file\_path + ".avi", cv2.VideoWriter\_fourcc(\*"XVID"), 10, im.size
)
while self.allow\_record:
im = ImageGrab.grab()
im = cv2.cvtColor(array(im), cv2.COLOR\_RGB2BGR)
video.write(im)
video.release()
def compose\_file(self):
print("合并视频&音频文件")
audio = AudioFileClip(self.file\_path + ".wav")
video = VideoFileClip(self.file\_path + ".avi")
ratio = audio.duration / video.duration
video = video.fl\_time(lambda t: t / ratio, apply\_to=\["video"\]).set\_end(
audio.duration
)
video = video.set\_audio(audio)
video = video.volumex(5)
video.write\_videofile(
self.file\_path + "\_out.avi", codec="libx264", fps=10, logger=None
)
video.close()
def remove\_temp\_file(self):
print("删除缓存文件")
os.remove(self.file\_path + ".wav")
os.remove(self.file\_path + ".avi")
def stop(self):
print("停止录制")
self.allow\_record = False
time.sleep(1)
self.compose\_file()
self.remove\_temp\_file()
def run(self):
t = threading.Thread(target=self.record\_screen)
t1 = threading.Thread(target=self.record\_audio)
t.start()
t1.start()
print("开始录制")
pr = PyRecord()
pr.run()
time.sleep(40)#录制40秒,可以自己修改
pr.stop()
#录音代码
import pyaudio
import wave
def start_audio(time = 20,save_file="test.wav"):
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 16000
RECORD_SECONDS = time #需要录制的时间
WAVE_OUTPUT_FILENAME = save_file #保存的文件名
p = pyaudio.PyAudio() #初始化
print("ON")
stream = p.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()
p.terminate()
print("OFF")
wf = wave.open(WAVE\_OUTPUT\_FILENAME, 'wb') #保存
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get\_sample\_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
start_audio()
手机扫一扫
移动阅读更方便
你可能感兴趣的文章