如果有大量的文本文档,希望转换成语音文件,可以在chatgpt中输入提示词:
你是一个Python编程专家,现在要完成一个编写将文本批量转语音的Python脚本的任务,具体步骤如下:
打开文件夹:D:AR,
读取里面的txt文档,
用edge-tts库(https://github.com/rany2/edge-tts)实现文本转语音,其中:
--voice 语音角色Name为 en-US-AnaNeural,Gender为 Female
--rate参数设为80%
语音另存为mp3文件,文件标题和txt文档一致,保存在同一个文件夹中;
###注意:
edge-tts.exe位于文件夹:D:Program Files (x86)Scripts
edge-tts库的使用方法:
Basic usage,If you want to use the edge-tts command, you can simply run it with the following command:
$ edge-tts --text "Hello, world!" --write-media hello.mp3 --write-subtitles hello.vtt
Changing rate, volume and pitch,It is possible to make minor changes to the generated speech.
$ edge-tts --rate=-50% --text "Hello, world!" --write-media hello_with_rate_halved.mp3 --write-subtitles hello_with_rate_halved.vtt
$ edge-tts --volume=-50% --text "Hello, world!" --write-media hello_with_volume_halved.mp3 --write-subtitles hello_with_volume_halved.vtt
$ edge-tts --pitch=-50Hz --text "Hello, world!" --write-media hello_with_pitch_halved.mp3 --write-subtitles hello_with_pitch_halved.vtt
In addition, it is required to use --rate=-50% instead of --rate -50% (note the lack of an equal sign) otherwise the -50% would be interpreted as just another argument.
这是打开本地demo.txt文本将其传递传递给edge-tts进行语音转化的示例代码:
import edge_tts
import asyncio
TEXT = ""
with open ('demo.txt','rb') as f:
data = f.read()
TEXT = data.decode('utf-8')
print(TEXT)
voice = 'zh-CN-YunxiNeural'
output = 'demo.mp3'
rate = '-4%'
volume = ' 0%'
async def my_function():
tts = edge_tts.Communicate(text = TEXT,voice = voice,rate = rate,volume=volume)
await tts.save(output)
if __name__ == '__main__':
asyncio.run(my_function())
这是ChatGPT给出的Python源代码:
import asyncio
import os
from edge_tts import Communicate # 确保从edge_tts正确导入Communicate类
# 文件夹路径
txt_folder_path = "D:\AR"
# 函数以异步方式运行文本到语音的转换
async def text_to_speech(txt_path, mp3_path, text, voice, rate):
tts = Communicate(text=text, voice=voice, rate=rate)
await tts.save(mp3_path)
# 遍历文件夹中的所有txt文件并进行转换
async def convert_folder_to_mp3(folder_path):
for filename in os.listdir(folder_path):
if filename.endswith(".txt"):
txt_file_path = os.path.join(folder_path, filename)
mp3_file_path = os.path.splitext(txt_file_path)[0] '.mp3'
# 从文本文件中读取内容
with open(txt_file_path, 'r', encoding='utf-8') as file:
text_content = file.read()
# 调用异步转换函数
await text_to_speech(txt_file_path, mp3_file_path, text_content,
voice="en-US-AnaNeural", rate="-20%") # 我们希望是80%的语速,所以是-20%
# 调用asyncio库以运行异步函数
asyncio.run(convert_folder_to_mp3(txt_folder_path))
print("所有的文本文件都已转换成语音。")
运行后,txt文本文档成功转换为mp3语音文件。