初始提交
This commit is contained in:
1 parent
73b6c8e76d
commit
0775fa3681
7 files changed
+426
-1
No files matched your search
@@ -0,0 +1,7 @@
|
||||
.venv/
|
||||
output/*
|
||||
temp/*
|
||||
*.md
|
||||
!example.md
|
||||
!README.md
|
||||
!output/example.mp3
|
||||
@@ -1,3 +1,25 @@
|
||||
# ttscript
|
||||
|
||||
自动化tts脚本
|
||||
这是一个实现了将markdown文本转语音并进行一系列后续操作的自动化项目
|
||||
|
||||
## 支持的功能
|
||||
|
||||
- 去除markdown符号
|
||||
- 文本转语音
|
||||
- 用ffmpeg设置语速
|
||||
- 用ffmpeg为得到的语音音频添加循环背景音乐
|
||||
|
||||
## 依赖
|
||||
|
||||
- `fish-audio-sdk`库
|
||||
- ffmpeg
|
||||
|
||||
## 使用方法
|
||||
|
||||
```bash
|
||||
python tts.py -f <markdown文件目录> -b <背景音乐文件目录> -l <语言> -r <倍数>
|
||||
-f : 后面跟着markdown文件目录,为必填项
|
||||
-b :后面跟着背景音乐文件目录,为选题项
|
||||
-r :后面跟着一个0.5~2.0的数字,可指定文本转语音的语速,为旋填项,默认为1.0
|
||||
```
|
||||
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
# 测试示例
|
||||
|
||||
这是一个用于测试 Markdown 转 MP3 功能的示例文件。
|
||||
|
||||
## 功能介绍
|
||||
|
||||
本工具可以将 Markdown 文件转换为 MP3 音频文件。
|
||||
|
||||
## 主要特点
|
||||
|
||||
- 支持中文和英文
|
||||
- 自动清理代码块
|
||||
- 保留主要文本内容
|
||||
|
||||
这是一段普通的文本,用于测试语音合成效果。
|
||||
|
||||
**粗体文本** 和 *斜体文本* 都会被正确处理。
|
||||
|
||||
代码块会被自动忽略:
|
||||
|
||||
```javascript
|
||||
console.log('这段代码不会被朗读');
|
||||
```
|
||||
|
||||
链接文本会被保留:[这是一个链接](https://example.com)
|
||||
|
||||
## 结尾
|
||||
|
||||
测试完成!
|
||||
|
||||
Executable
BIN
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
fishaudio==0.0.5
|
||||
@@ -0,0 +1,365 @@
|
||||
"""
|
||||
依赖:
|
||||
python3
|
||||
# gtts库
|
||||
fish-audio-sdk 库
|
||||
ffmpeg
|
||||
# pyttsx3
|
||||
本脚本使用方法:
|
||||
python tts.py -f <markdown文件目录> -b <背景音乐文件目录> -l <语言> -r <倍数>
|
||||
-f : 后面跟着markdown文件目录,为必填项
|
||||
-b :后面跟着背景音乐文件目录,为选题项
|
||||
# -l :后面跟着语言代号,可指定tts引擎用什么语言输出音频,为选填项,默认为中文 (新模型无法设定语言,所以此项作废)
|
||||
-r :后面跟着一个0.5~2.0的数字,可指定文本转语音的语速,为旋填项,默认为1.0
|
||||
"""
|
||||
import re
|
||||
import sys
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
from fishaudio import FishAudio
|
||||
from fishaudio.utils import save
|
||||
# from gtts import gTTS # 用于测试的gtts方案
|
||||
# import pyttsx3 # 本地tts方案,效果不行
|
||||
|
||||
|
||||
|
||||
def main():
|
||||
"""
|
||||
主函数,处理命令行参数
|
||||
"""
|
||||
|
||||
# 设置参数默认值
|
||||
markdown_path = ""
|
||||
background_path = ""
|
||||
# language = "zh-CN" #(语言参数作废)
|
||||
rate = 1.0
|
||||
|
||||
# 处理命令行输入
|
||||
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 == "-l": language = sys.argv[i + 1] #(语言参数作废)
|
||||
if arg == "-r": rate = float(sys.argv[i + 1])
|
||||
|
||||
# 处理输入不规范的情况
|
||||
if markdown_path == "":
|
||||
print("本脚本使用方法:\npython tts.py -f <markdown文件目录> -b <背景音乐文件目录> -r <倍数>\n\t-f : 后面跟着markdown文件目录,为必填项\n\t-b :后面跟着背景音乐文件目录,为选题项\n\t-r :后面跟着一个0.5~2.0的数字,可指定文本转语音的语速,为旋填项,默认为1.0\n")
|
||||
return
|
||||
|
||||
# 创建必要的文件夹
|
||||
create_necessary_dir()
|
||||
|
||||
# 生成文件
|
||||
print("生成中...")
|
||||
cod = generate_mp3(markdown_path, background_path, rate)
|
||||
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="", rate=1.0): # (语言参数作废)
|
||||
"""
|
||||
在./output目录下生成(经过处理后的)markdown朗读音频
|
||||
|
||||
Args:
|
||||
markdown_path(str): markdown文件路径
|
||||
background_path(str):背景音乐路径,若为空字符串则不会尝试添加背景音乐
|
||||
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)
|
||||
print("语音音频生成完毕")
|
||||
|
||||
# 若倍数不为1,则用ffmpeg调整tts倍数
|
||||
if rate != 1.0:
|
||||
print("正在调整朗读文本速度...")
|
||||
cod = made_in_heaven(temp_path, rate)
|
||||
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): # (语言参数作废)
|
||||
"""
|
||||
将输入的文本转换成音频输出
|
||||
|
||||
Args:
|
||||
text(str):输入的文本
|
||||
output(str):输出的文件的路径
|
||||
"""
|
||||
|
||||
apikey = "" # 请在""内输入你的api key
|
||||
# 若为空,则让用户在终端输入
|
||||
if apikey == "":
|
||||
apikey = input("请输入你的api key:")
|
||||
|
||||
# 使用fish speech服务(需要API KEY)将文本转换为语音
|
||||
client = FishAudio(api_key = apikey)
|
||||
audio = client.tts.convert(text = text)
|
||||
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)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
|
||||
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()
|
||||
Reference in new issue
Block a user