import os import numpy as np from scipy.io import wavfile import cv2 import sounddevice…
- User
import os import numpy as np from scipy.io import wavfile import cv2 import sounddevice as sd import subprocess import time from talkingface.audio_model import AudioModel from talkingface.render_model import RenderModel
加载模型
audioModel = AudioModel() audioModel.loadModel("checkpoint/audio.pkl")
renderModel = RenderModel() renderModel.loadModel("checkpoint/render.pth")
定义路径
test_video = "test3" pkl_path = f"video_data/{test_video}/keypoint_rotate.pkl" video_path = f"video_data/{test_video}/circle.mp4" wavpath = "video_data/audio0.wav" output_image_dir = f"output_images/{test_video}/"
创建输出目录
os.makedirs(output_image_dir, exist_ok=True)
重置渲染模型的角色
renderModel.reset_charactor(video_path, pkl_path)
读取音频文件
rate, wav = wavfile.read(wavpath, mmap=False) sample_rate = 16000 samples_per_read = int(0.04 * sample_rate)
准备 FFmpeg 命令用于 RTMP 流式传输
ffmpeg_command = [ 'ffmpeg', '-y', # 覆盖输出文件 '-f', 'rawvideo', '-pixel_format', 'bgr24', '-video_size', '640x480', # 根据您的帧大小进行调整 '-framerate', '25', # 设置帧率 '-i', '-', # 从 stdin 输入 '-c:v', 'libx264', # 指定视频编解码器 '-pix_fmt', 'yuv420p', '-f', 'flv', 'rtmp://localhost/live/livestream' # 替换为您的 RTMP URL ]
启动 FFmpeg 进程并捕获 stderr
process = subprocess.Popen(ffmpeg_command, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
用于同步的时间跟踪
start_time = time.time() frame_duration = 1 / 25 # 根据帧率调整
开始捕获音频和渲染帧
with sd.InputStream(channels=1, dtype="float32", samplerate=sample_rate) as stream: index_ = 0 try: while True: # 读取音频样本 samples, _ = stream.read(samples_per_read) # 阻塞读取 pcm_data = samples.reshape(-1)
# 计算音量 volume = np.mean(np.abs(pcm_data)) # 简单的音量计算 print(f"Volume: {volume}") # 您可以根据需要调整或移除音量阈值 # if volume > 0.01: # 生成嘴部帧和渲染视频帧 mouth_frame = audioModel.interface_frame(pcm_data) frame = renderModel.interface(mouth_frame) # 确保帧大小匹配 FFmpeg 设置 frame_height, frame_width = frame.shape[:2] if (frame_height, frame_width) != (480, 640): frame = cv2.resize(frame, (640, 480)) # 如果需要,将帧保存为图像 # image_path = os.path.join(output_image_dir, f"frame_{index_}.png") # cv2.imwrite(image_path, frame) # 将帧写入 FFmpeg 的 stdin process.stdin.write(frame.tobytes()) # 如果需要显示帧(在有显示器的环境中) # cv2.imshow("Frame", frame) # if cv2.waitKey(1) == 27: # 按 Esc 键退出 # break # 计算已用时间,如果需要进行同步,可以等待 elapsed_time = time.time() - start_time expected_time = index_ * frame_duration if elapsed_time < expected_time: time.sleep(expected_time - elapsed_time) index_ += 1 except Exception as e: print(f"An error occurred: {e}") finally: # 清理资源 process.stdin.close() process.wait() err = process.stderr.read().decode() print(f"FFmpeg stderr: {err}") # cv2.destroyAllWindows() 请把声音也同步进去,需要声音和图像同步,同步完,图像也需要保持很好原样,保持 - Assistant