426 lines
12 KiB
Python
Executable File
426 lines
12 KiB
Python
Executable File
"""
|
||
依赖:
|
||
python3
|
||
# gtts库
|
||
fish-audio-sdk 库
|
||
ffmpeg
|
||
本脚本使用方法:
|
||
python tts.py -f <markdown文件目录> -b <背景音乐文件目录> -i <音色id> -r <倍数> -v <语音相对音量>
|
||
-f : 后面跟着markdown文件目录,为必填项
|
||
-b :后面跟着背景音乐文件目录,为选填项
|
||
-i : 后面跟着tts音色id,为选填项
|
||
-r :后面跟着一个0.5~2.0的数字,可指定文本转语音的语速,为选填项,默认为1.0
|
||
-v : 后面跟着一个数字,可指定文本转语音的相对音量,为选填项,默认为0
|
||
"""
|
||
import re
|
||
import sys
|
||
import os
|
||
import subprocess
|
||
|
||
from fishaudio import FishAudio
|
||
from fishaudio.types import TTSConfig, Prosody
|
||
from fishaudio.utils import save
|
||
# from gtts import gTTS # 用于测试的gtts方案
|
||
# import pyttsx3 # 本地tts方案,效果不行
|
||
|
||
|
||
|
||
def main():
|
||
"""
|
||
主函数,处理命令行参数
|
||
"""
|
||
|
||
# 设置参数默认值
|
||
markdown_path = ""
|
||
background_path = ""
|
||
id = ""
|
||
rate = float(1.0)
|
||
volume = float(0)
|
||
|
||
# 处理命令行输入id
|
||
for i , arg in enumerate(sys.argv):
|
||
if arg == "-f": markdown_path = sys.argv[i + 1]
|
||
if arg == "-b": background_path = sys.argv[i + 1]
|
||
if arg == "-i": id = sys.argv[i + 1]
|
||
if arg == "-r": rate = float(sys.argv[i + 1])
|
||
if arg == "-v": volume = float(sys.argv[i + 1])
|
||
|
||
# 处理输入不规范的情况
|
||
if markdown_path == "":
|
||
print("本脚本使用方法:\npython tts.py -f <markdown文件目录> -b <背景音乐文件目录> -i <音色id> -r <倍数> -v <语音相对音量>\n\t-f : 后面跟着markdown文件目录,为必填项\n\t-b :后面跟着背景音乐文件目录,为选填项\n\t-i : 后面跟着tts音色id,为选填项\n\t-r :后面跟着一个0.5~2.0的数字,可指定文本转语音的语速,为选填项,默认为1.0\n\t-v : 后面跟着一个数字,可指定文本转语音的相对音量,为选填项,默认为0\n")
|
||
return
|
||
|
||
# 创建必要的文件夹
|
||
create_necessary_dir()
|
||
|
||
# 生成文件
|
||
print("生成中...")
|
||
cod = generate_mp3(markdown_path, background_path, id, rate, volume)
|
||
if cod != -1: print("完成")
|
||
|
||
|
||
|
||
def create_necessary_dir():
|
||
"""
|
||
确保目录下存在output和temp文件夹
|
||
output用于存储输出文件,temp用于存储脚本需要的临时文件
|
||
"""
|
||
|
||
# output
|
||
if os.path.isfile("./output"):
|
||
print("错误:目录下有名为 \"output\"的文件,请移动或者重命名它以让程序正常运行")
|
||
if not os.path.isdir("./output"): os.mkdir("output")
|
||
|
||
# temp
|
||
if os.path.isfile("./temp"):
|
||
print("错误:目录下有名为 \"temp\"的文件,请移动或者重命名它以让程序正常运行")
|
||
if not os.path.isdir("./temp"): os.mkdir("temp")
|
||
|
||
|
||
|
||
def generate_mp3(markdown_path, background_path="", id = "", rate=1.0, volume=0.0):
|
||
"""
|
||
在./output目录下生成(经过处理后的)markdown朗读音频
|
||
|
||
Args:
|
||
markdown_path(str): markdown文件路径
|
||
background_path(str):背景音乐路径,若为空字符串则不会尝试添加背景音乐
|
||
id(str):tts音色id,若为空则默认
|
||
rate(float):tts语速,范围为0.5~2.0
|
||
"""
|
||
|
||
# 去除markdown文件中的符号后将其转化为音频
|
||
# 处理markdown文件
|
||
if not os.path.exists(markdown_path):
|
||
print(f"错误:文件\"{markdown_path}\"不存在!")
|
||
return -1
|
||
f = open(markdown_path, 'r', encoding='utf-8')
|
||
|
||
# 处理文本,去除markdown符号
|
||
content = f.read()
|
||
f.close()
|
||
text = extract_text_from_markdown(content)
|
||
|
||
# 确保文本非空
|
||
if not text or len(text.strip()) == 0:
|
||
print(f"错误:文件\"{path}\"不包含可被朗读的文本")
|
||
return -1
|
||
|
||
temp_path = "./temp/" + os.path.splitext(os.path.basename(markdown_path))[0] + ".mp3" # 正在生成中的音频文件的路径
|
||
|
||
# 生成tts音频
|
||
print("正在生成文本转语音音频...")
|
||
generate_tts(text, temp_path, id, rate)
|
||
print("语音音频生成完毕")
|
||
|
||
# 新模型自带调整语速功能,没必要用ffmpeg调整语速
|
||
# # 若倍数不为1,则用ffmpeg调整tts倍数
|
||
|
||
# if rate != 1.0:
|
||
# print("正在调整朗读文本速度...")
|
||
# cod = made_in_heaven(temp_path, rate)
|
||
# if cod != -1: print("朗读速度调整完毕")
|
||
|
||
# 若相对音量不为0,则用ffmpeg调整tts音量
|
||
if volume != 0:
|
||
print("正在调整朗读音量...")
|
||
cod = adjust_volume(temp_path, volume)
|
||
if cod != -1: print("朗读音量调整完毕")
|
||
# 若背景音乐路径不为空,则用ffmpeg添加背景音乐
|
||
if background_path != "":
|
||
print("正在添加背景音乐...")
|
||
cod = add_bg(temp_path, background_path)
|
||
if cod != -1: print("背景音乐添加完毕")
|
||
|
||
# 将位于./temp中的以及生成完毕的音频文件移动到output
|
||
output_path = "./output/" + os.path.splitext(os.path.basename(markdown_path))[0] + ".mp3" # 最终得到的音频文件的路径
|
||
os.rename(temp_path, output_path)
|
||
|
||
|
||
|
||
def extract_text_from_markdown(content):
|
||
"""
|
||
从markdown内容中提取纯文本
|
||
|
||
Args:
|
||
content: markdown文件内容
|
||
|
||
Returns:
|
||
提取后的纯文本
|
||
"""
|
||
|
||
# 移除代码块
|
||
text = re.sub(r'```[\s\S]*?```', '', content)
|
||
|
||
# 移除行内代码
|
||
text = re.sub(r'`[^`]+`', '', text)
|
||
|
||
# 移除图片
|
||
text = re.sub(r'!\[.*?\]\(.*?\)', '', text)
|
||
|
||
# 移除链接但保留文本
|
||
text = re.sub(r'\[([^\]]+)\]\([^\)]+\)', r'\1', text)
|
||
|
||
# 移除标题标记
|
||
text = re.sub(r'^#{1,6}\s+', '', text, flags=re.MULTILINE)
|
||
|
||
# 移除粗体和斜体标记
|
||
text = re.sub(r'(\*\*|__)(.*?)\1', r'\2', text)
|
||
text = re.sub(r'(\*|_)(.*?)\1', r'\2', text)
|
||
|
||
# 移除HTML标签
|
||
text = re.sub(r'<[^>]+>', '', text)
|
||
|
||
# 我在md2mp3项目的基础上增加了去除无序序号、引用符号以及分割线标记的代码
|
||
|
||
# 移除无序序号标记
|
||
text = text.replace("- ", "")
|
||
|
||
# 移除引用标记
|
||
text = text.replace("> ", "")
|
||
|
||
# 移除分割线标记
|
||
text = text.replace("---", "")
|
||
|
||
#---
|
||
|
||
# 移除多余的空行
|
||
text = re.sub(r'\n\s*\n', '\n', text)
|
||
|
||
# 移除多余的空格
|
||
text = text.strip()
|
||
|
||
# 之后根据需要可能还得去除公式符号($$, $$$$, \(\), \[\])
|
||
|
||
return text
|
||
|
||
|
||
|
||
def generate_tts(text, output, id="", rate=1.0):
|
||
"""
|
||
将输入的文本转换成音频输出
|
||
|
||
Args:
|
||
text(str):输入的文本
|
||
output(str):输出的文件的路径
|
||
id(str):tts音色id
|
||
rate(float):tts语速
|
||
volume(float):tts相对音量
|
||
"""
|
||
|
||
apikey = "" # 请在""内输入你的api key
|
||
# 若为空,则让用户在终端输入
|
||
if apikey == "":
|
||
apikey = input("请输入你的api key:")
|
||
|
||
# 使用fish speech服务(需要API KEY)将文本转换为语音
|
||
|
||
client = FishAudio(api_key = apikey)
|
||
# 由于该tts自带的音量调整有问题,因此本脚本不用它来调整tts音量
|
||
if id == "":
|
||
config = TTSConfig(
|
||
prosody=Prosody(speed=rate, volume=0)
|
||
)
|
||
else:
|
||
config = TTSConfig(
|
||
prosody=Prosody(speed=rate, volume=0),
|
||
reference_id=id,
|
||
)
|
||
audio = client.tts.convert(text = text, config = config)
|
||
save(audio, output)
|
||
|
||
|
||
# 无API的谷歌tts方案
|
||
# tts = gTTS(text=text, lang=lang)
|
||
# tts.save(output)
|
||
# pyttsx3引擎生成音频的代码,效果不行所以注释掉了
|
||
#tts = pyttsx3.init()
|
||
#tts.setProperty('voice', lang)
|
||
#tts.save_to_file(text, output)
|
||
#tts.runAndWait()
|
||
|
||
|
||
|
||
def made_in_heaven(path, rate):
|
||
"""
|
||
调整输入音频的倍数
|
||
|
||
Args:
|
||
path(str):待处理音频的路径,同时也是处理后音频的路径
|
||
rate(float):倍数,范围为0.5~2.0
|
||
"""
|
||
|
||
# 确保已经安装了ffmpeg
|
||
if not check_ffmpeg():
|
||
print("错误:需要安装ffmpeg")
|
||
return -1
|
||
|
||
# 利用ffmpeg将调整输入文件倍数并提高音量(由于我不知道的原因,ffmpeg调整倍速后音频音量会下降),输出到重命名前的路径(这么别扭的原因是ffmpeg不支持输入文件和输出文件的路径完全相同)
|
||
input_path = "./temp/" + os.path.splitext(os.path.basename(path))[0] + "_rate.mp3"
|
||
cmds = [
|
||
[
|
||
'ffmpeg',
|
||
'-i', str(input_path),
|
||
'-filter:a', f'atempo={rate}',
|
||
'-vn', # 不处理视频
|
||
'-y', # 覆盖输出文件
|
||
str(path)
|
||
]
|
||
,
|
||
[
|
||
'ffmpeg',
|
||
'-i', str(input_path),
|
||
'-af', 'volume=2dB',
|
||
str(path)
|
||
]
|
||
]
|
||
for cmd in cmds:
|
||
# 重命名输入文件
|
||
os.rename(path, input_path)
|
||
|
||
subprocess.run(cmd)
|
||
|
||
# 删除输入文件
|
||
os.remove(input_path)
|
||
|
||
return 0
|
||
|
||
|
||
def adjust_volume(path, volume):
|
||
"""
|
||
调整输入音频的音量
|
||
|
||
Args:
|
||
path(str):待处理音频的路径,同时也是处理后音频的路径
|
||
volume(float):相对音量
|
||
"""
|
||
|
||
# 确保已经安装了ffmpeg
|
||
if not check_ffmpeg():
|
||
print("错误:需要安装ffmpeg")
|
||
return -1
|
||
|
||
# 利用ffmpeg将调整输入文件的音量,输出到重命名前的路径(这么别扭的原因是ffmpeg不支持输入文件和输出文件的路径完全相同)
|
||
input_path = "./temp/" + os.path.splitext(os.path.basename(path))[0] + "_volume.mp3"
|
||
cmd = [
|
||
'ffmpeg',
|
||
'-i', str(input_path),
|
||
'-af', 'volume=' + str(volume) + 'dB',
|
||
str(path)
|
||
]
|
||
# 重命名输入文件
|
||
os.rename(path, input_path)
|
||
|
||
subprocess.run(cmd)
|
||
|
||
# 删除输入文件
|
||
os.remove(input_path)
|
||
|
||
return 0
|
||
|
||
|
||
|
||
def add_bg(path, bg_path):
|
||
"""
|
||
为输入音频添加背景音乐
|
||
|
||
Args:
|
||
path(str):待处理音频的路径,同时也是处理后音频的路径
|
||
bg_path(str):背景音乐的路径
|
||
"""
|
||
|
||
# 确保背景音乐文件存在
|
||
if not os.path.exists(bg_path):
|
||
print(print(f"错误:文件\"{bg_path}\"不存在"))
|
||
return -1
|
||
|
||
# 确保已经安装了ffmpeg
|
||
if not check_ffmpeg():
|
||
print("错误:需要安装ffmpeg")
|
||
return -1
|
||
|
||
# 获取待处理音频时长,用于确保添加前后音频时长相同
|
||
duration = get_audio_duration(path)
|
||
|
||
# 重命名输入文件
|
||
input_path = "./temp/" + os.path.splitext(os.path.basename(path))[0] + "_bg.mp3"
|
||
os.rename(path, input_path)
|
||
|
||
# 利用ffmpeg添加循环背景音乐,输出到重命名前的路径(这么别扭的原因是ffmpeg不支持输入文件和输出文件的路径完全相同)
|
||
cmd = [
|
||
'ffmpeg',
|
||
'-i',str(input_path),
|
||
'-i', str(bg_path),
|
||
'-filter_complex', '[1:a]aloop=loop=-1:size=2e+09[out];[out][0:a]amix',
|
||
'-ss', '0',
|
||
'-t', str(duration),
|
||
'-y', str(path)
|
||
]
|
||
subprocess.run(cmd)
|
||
|
||
# 删除输入文件
|
||
os.remove(input_path)
|
||
|
||
return 0
|
||
|
||
|
||
|
||
def get_audio_duration(audio_path):
|
||
"""
|
||
获取音频时长
|
||
|
||
Args:
|
||
audio_path(str):音频路径
|
||
|
||
Returns:
|
||
(float)音频时长
|
||
"""
|
||
|
||
# 确保已经安装了ffmpeg
|
||
if not check_ffmpeg():
|
||
print("错误:需要安装ffmpeg")
|
||
return -1
|
||
|
||
# 执行ffmpeg命令来获取时长
|
||
cmd = [
|
||
'ffprobe',
|
||
'-v', 'error',
|
||
'-show_entries', 'format=duration',
|
||
'-of', 'default=noprint_wrappers=1:nokey=1',
|
||
str(audio_path)
|
||
]
|
||
result = subprocess.run(
|
||
cmd,
|
||
stdout=subprocess.PIPE,
|
||
stderr=subprocess.PIPE,
|
||
text=True
|
||
)
|
||
if result.returncode == 0:
|
||
duration = float(result.stdout.strip())
|
||
return duration
|
||
else:
|
||
return None
|
||
|
||
|
||
|
||
def check_ffmpeg():
|
||
"""
|
||
检测是否安装了ffmpeg
|
||
Returns:
|
||
布尔值,代表是否安装
|
||
"""
|
||
|
||
try:
|
||
subprocess.run(['ffmpeg', '-version'],
|
||
stdout=subprocess.DEVNULL,
|
||
stderr=subprocess.DEVNULL,
|
||
check=True)
|
||
return True
|
||
except (subprocess.CalledProcessError, FileNotFoundError):
|
||
return False
|
||
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|