VariantConst
576 字
3 分钟
AI 视频配音
2023-11-27

OpenAI Text to Speech (TTS) 能方便地将文字转换为语音,可以用来给 PPT 讲解视频配音。然而,文字转语音的结果和视频的进度的一致性是一个问题。下面简单介绍我的解决方案。

1. 将视频文稿格式化#

用你的方式写出视频的文稿。为了方便将音频和视频对齐,也是为了避免超出 4096 个 token 的限制,最好是将文稿分成若干小段。例如,每页 PPT 或者每个段落都可以作为一个小段。假设将文稿保存到了 content 数组中,其中 content[i] 表示第 i 段文稿的字符串。

2. OpenAI TTS API 的使用#

OpenAI TTS API 的使用非常简单,只需要调用 client.audio.speech.create 方法即可。下面是一个简单的例子,将 content 中的内容分段保存在 speech_{idx}.mp3 中:

from pathlib import Path
from openai import OpenAI
client = OpenAI()

def convert_line(idx):
  speech_file_path = f"speech_{idx}.mp3"
  response = client.audio.speech.create(
    model="tts-1",
    voice="echo",
    input=content[idx]
  )
  response.stream_to_file(speech_file_path)

for i in range(len(lines)):
  convert_line(i)

通过 voice 参数,可以选择 alloy, echo, fable, onyx, nova 以及 shimmer 这几种不同的声音。model 参数可选 tts-1tts-1-hd,前者质量较低但速度较快,后者质量较高但速度较慢。

3. 合并音频,录制 PPT 讲解视频#

为了确保音频和视频同步,我们先把所有的音频合并成一个音频文件,然后再根据音频的速度和节奏录制视频。

合并音频#

from pydub import AudioSegment
import os

# Function to get all mp3 files in the current directory, sorted numerically
def get_mp3_files():
    files = [f for f in os.listdir('.') if f.endswith('.mp3') and \
																								f.startswith('speech_')]
    files.sort(key=lambda f: int(''.join(filter(str.isdigit, f))))
    return files

# Concatenate mp3 files
def concatenate_mp3(files, output_file='combined_audio.mp3'):
    combined = AudioSegment.empty()
    for file in files:
        combined += AudioSegment.from_mp3(file)
    combined.export(output_file, format='mp3')

if __name__ == '__main__':
    mp3_files = get_mp3_files()
    concatenate_mp3(mp3_files)

录制视频#

播放 combined_audio.mp3,根据音频播放 PPT,同时录制屏幕,这样语音和文字就对上了。

4. 优化音视频对齐#

通常而言,音频和视频的对齐是不完美的,这时候可以用剪映等软件,把前面得到的各个音频切片手动和视频对齐,进行精细的调整。这样,我们就得到了一段完美对齐的视频 ^_^

在导出视频时,可以用 ffmpeg 高质量地压缩视频:

ffmpeg -i [input_video_name] -c:v libx264 -crf 28 -preset medium -c:a aac -b:a 128k [compressed_video_name]
AI 视频配音
https://blog.variantconst.com/posts/tts-for-ppt-voiceover/
作者
VariantConst
发布于
2023-11-27
许可协议
CC BY-NC-SA 4.0