使用Python实现文字转语音

360影视 日韩动漫 2025-05-17 22:16 3

摘要:文本转语音 (TTS) 是一项使计算机能够将书面文本转换为口语单词的技术。它有许多应用,从提高视障人士的可访问性到创建基于语音的交互式系统。TTS 技术分析文本输入并生成相应的音频输出,使用户可以听到内容而不是阅读内容。

文本转语音 (TTS) 是一项使计算机能够将书面文本转换为口语单词的技术。它有许多应用,从提高视障人士的可访问性到创建基于语音的交互式系统。TTS 技术分析文本输入并生成相应的音频输出,使用户可以听到内容而不是阅读内容。

Pyttsx3 是一个功能强大的 Python 库,它提供了各种语音合成器的接口。它允许开发人员轻松将文本转换为语音,并提供语音属性(例如语速、音量等)的自定义选项。通过利用 pyttsx3,您可以向 Python 应用程序添加语音合成功能,并创建引人入胜的交互式体验。

1.基本使用

# coding: utf-8import pyttsx3 # 导入库def text2voice(text):eng = pyttsx3.init # 初始化一个实例eng.say(text)# say 用于传递要说的文本的方法eng.runAndWait # 运行并处理语音命令if __name__ == "__main__":text2voice("这是一个演示在Python中使用pyttsx3库将文本转换为语音的示例。")

2.自定义语音属性

# coding: utf-8import pyttsx3 # 导入库def text2voice2(text):engine = pyttsx3.init# Customizing speech propertiesengine.setProperty('rate', 150) # Speed of speech (words per minute)engine.setProperty('volume', 0.8) # Volume (0.0 to 1.0)engine.say(text)engine.runAndWaitif __name__ == "__main__":text2voice2("这是一个演示在Python中使用pyttsx3库将文本转换为语音的示例。")

在此示例中,将语速设置为每分钟 150 个单词,并将音量设置为 0.8(最大音量的 80%)。

3.将语音保存为音频文件

def save_txt2voice(text, File):engine = pyttsx3.initengine.setProperty('rate', 150)engine.setProperty('volume', 0.8) engine.save_to_file(text, file)engine.runAndWaitif __name__ == "__main__":save_txt2voice('这是一个演示在Python中使用pyttsx3库将文本转换为语音的示例。', 'demo.WAV')

4.处理事件和回调

def onStart(name):print("Speech started")def onEnd(name, completed):if completed:print("Speech completed")else:print("Speech interrupted")def onWord(name, location, length):print(f"Current word: {name}, Location: {location}, Length: {length}")def text2voice3(text):engine = pyttsx3.initengine.connect('started-utterance', onStart)engine.connect('finished-utterance', onEnd)engine.connect('started-word', onWord)engine.say(text)engine.runAndWaitif __name__ == "__main__":text2voice3("这是一个演示在Python中使用pyttsx3库将文本转换为语音的示例。")

5.更改声音

def find_voice_say(text):engine = pyttsx3.init# 获取可用声音的列表voices = engine.getProperty('voices')# 打印可用声音的信息for i, voice in enumerate(voices):print(f"语音{i}:")print(f" - ID: {voice.id}")print(f" - 名称: {voice.name}")print(f" - 语言: {voice.languages}")print(f" - 性别: {voice.gender}")print(f" - 年龄: {voice.age}")# 设置第二个声音(如果有的话)if len(voices) > 1:engine.setProperty('voice', voices[1].id)engine.say(text)engine.runAndWaitdef text2voice4(text):engine = pyttsx3.initengine.setProperty('voice', 'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\Voices\\Tokens\\TTS_MS_EN-US_ZIRA_11.0')engine.say(text)engine.runAndWaitif __name__ == "__main__":find_voice_say("这是一个演示在Python中使用pyttsx3库将文本转换为语音的示例。")

6.简单的文件阅读器

import pyttsx3def text_reader(file_path):try:with open(file_path, 'r', encoding='utf-8') as file:text = file.readengine = pyttsx3.initprint("开始阅读文件...")engine.say(text)engine.runAndWaitprint("文件阅读完成")except FileNotFoundError:print(f"错误: 找不到文件 '{file_path}'")except Exception as e:print(f"发生错误: {e}")# 使用示例text_reader('example.txt')

7.多线程

在图形界面或需要非阻塞语音输出的应用中,可以在单独的线程中运行TTS引擎:

import threadingimport timeimport pyttsx3def speak_in_thread(text):engine = pyttsx3.initengine.say(text)engine.runAndWaitengine.stop# 创建一个线程来播放语音speech_thread = threading.Thread(target=speak_in_thread, args=("这段文本将在单独的线程中播放,不会阻塞主程序",))speech_thread.start# 主程序可以继续执行其他任务print("语音播放已开始,但主程序继续执行")for i in range(5):print(f"主线程计数: {i}")time.sleep(0.5)# 等待语音线程结束speech_thread.joinprint("语音播放完成")

8.简单的语音提醒工具

import pyttsx3import timeimport threadingclass VoiceReminder:def __init__(self):self.reminders = self.running = Trueself.check_thread = threading.Thread(target=self._check_reminders)self.check_thread.daemon = Trueself.check_thread.startdef add_reminder(self, message, minutes):reminder_time = time.time + minutes * 60self.reminders.append((reminder_time, message))print(f"提醒已设置: '{message}' 将在 {minutes} 分钟后提醒")def _check_reminders(self):while self.running:current_time = time.time# 检查是否有到期的提醒for i, (reminder_time, message) in enumerate(self.reminders[:]):if current_time >= reminder_time:print(f"提醒: {message}")speech_thread = threading.Thread(target=self._speak_in_thread, args=(message,))speech_thread.startspeech_thread.join# 删除已触发的提醒self.reminders.pop(i)# time.sleep(1)def stop(self):self.running = Falseself.check_thread.join(timeout=1)def _speak_in_thread(self, text):print(text)engine = pyttsx3.initengine.say(text)engine.runAndWaitengine.stop# 使用示例reminder = VoiceReminderreminder.add_reminder("该喝水了", 0.1) # 6秒后提醒reminder.add_reminder("休息一下眼睛", 0.2) # 12秒后提醒reminder.add_reminder("该站一下了", 0.3) # 18秒后提醒# 保持程序运行足够长的时间来触发提醒time.sleep(30)reminder.stop

edge-tts 是一个功能强大的 Python 库,利用 Microsoft Azure 的云端文本到语音(TTS)服务,支持多种语言和声音选项,能够生成高质量、自然听感的语音输出。它支持多种音频格式,包括 MP3、WAV 和 OGG,适用于在本地或服务器上进行文本转换为语音的应用程序,可以通过简单的 API 调用进行部署和运行,非常适合语音助手、教育应用和音频内容制作等多种场景。

1.文本转语音

import asyncioimport edge_ttsdef generate_audio(text: str, voice: str, output_file: str) -> None:async def generate_audio_async -> None:"""异步生成语音"""communicate = edge_tts.Communicate(text, voice)await Communicate.save(output_file)# 异步执行生成音频asyncio.run(generate_audio_async)# 示例调用generate_audio("这里是一个文字转语音的demo,使用的软件是edge tts。", "zh-CN-XiaoyiNeural", "demo.mp3")

2.打印音色

import asynciofrom edge_tts import VoicesManagerasync def print_voices:vm = await VoicesManager.createvoices = vm.findfor voice in voices:if voice['ShortName'].startswith('zh'):print(voice)async def main:await print_voicesif __name__ == '__main__':asyncio.run(main)

运行结果:

zh-HK-HiuGaaiNeuralzh-HK-HiuMaanNeuralzh-HK-WanLungNeuralzh-CN-XiaoxiaoNeuralzh-CN-XiaoyiNeuralzh-CN-YunjianNeuralzh-CN-YunxiNeuralzh-CN-YunxiaNeuralzh-CN-YunyangNeuralzh-CN-liaoning-XiaobeiNeuralzh-TW-HsiaoChenNeuralzh-TW-YunJheNeuralzh-TW-HsiaoYuNeuralzh-CN-shaanxi-XiaoniNeural

3.同步调用

# coding: utf-8import edge_ttsdef generate_audio(text: str, voice: str, output_file: str) -> None:communicate = edge_tts.Communicate(text, voice)communicate.save_sync(output_file)# 示例调用generate_audio("这里是一个文字转语音的demo,使用的软件是edge tts。", "zh-CN-XiaoyiNeural", "demo.mp3")

4.语音参数

edge-tts 还允许用户在合成时对语音的音色、音量、语速、音调等参数进行调整。通过 Communicate 类中的 rate、pitch 和 volume 参数,可以动态控制生成的语音效果。

import edge_ttsdef generate_audio_with_custom_params(text: str, output_file: str, rate: str = "+0%", pitch: str = "+0Hz",volume: str = "+0%") -> None:# 选择中文语音,这里使用的是小艺的 Neural 语音voice = "zh-CN-XiaoyiNeural"# 使用 edge_tts.Communicate 创建语音对象,并传入自定义参数communicate = edge_tts.Communicate(text, voice=voice, rate=rate, pitch=pitch, volume=volume)# 保存生成的音频文件communicate.save_sync(output_file)print(f"音频已生成,语速: {rate},音调: {pitch},音量: {volume}。")# 示例调用generate_audio_with_custom_params("欢迎体验自定义语音合成!","custom_param_audio.wav",rate="+50%",pitch="+10Hz",volume="-20%")rate(语速):控制语速的调整。默认值为 "+0%",表示标准语速。pitch(音调):控制音调的调整,单位是 Hz。默认值为 "+0Hz",表示标准音调。volume(音量):控制音量的调整,单位是百分比。默认值为 "+0%",表示标准音量。

5.音频与字幕

在某些应用场景中,可能需要同时生成音频和字幕,并根据需要选择同步或异步方式进行处理。下面展示了如何通过 edge-tts 实现同步和异步生成音频和字幕文件。执行后,会生成音频文件和对应的字幕文件。

import asyncioimport edge_ttsdef process_audio_and_subtitles_sync(text: str, voice: str, output_file: str, srt_file: str) -> None:"""同步生成音频并实时生成字幕:param text: 需要合成的中文文本:param voice: 使用的语音类型:param output_file: 输出的音频文件名:param srt_file: 输出的字幕文件名"""communicate = edge_tts.Communicate(text, voice)submaker = edge_tts.SubMaker# 同步生成音频并实时生成字幕with open(output_file, "wb") as audio_file:for chunk in communicate.stream_sync:if chunk["type"] == "audio":audio_file.write(chunk["data"]) # 写入音频数据elif chunk["type"] == "WordBoundary":submaker.feed(chunk) # 处理字幕# 保存字幕文件with open(srt_file, "w", encoding="utf-8") as subtitle_file:subtitle_file.write(submaker.get_srt)async def process_audio_and_subtitles_async(text: str, voice: str, output_file: str, srt_file: str) -> None:"""异步生成音频并实时生成字幕:param text: 需要合成的中文文本:param voice: 使用的语音类型:param output_file: 输出的音频文件名:param srt_file: 输出的字幕文件名"""# 异步调用同步版本的逻辑loop = asyncio.get_event_loopawait loop.run_in_executor(None, process_audio_and_subtitles_sync, text, voice, output_file, srt_file)# 示例调用process_audio_and_subtitles_sync("欢迎使用 Python 进行语音合成!","zh-CN-XiaoyiNeural","audio_sync.mp3","audio_sync.srt")# 异步调用asyncio.run(process_audio_and_subtitles_async("这是一段测试语音和字幕生成的示例。","zh-CN-XiaoyiNeural","audio_async.mp3","audio_async.srt"))

来源:IT职业教育

相关推荐