目录
1.介绍
2.思路
3.安装python包
3.程序:
4.运行结果
1.介绍
当我们使用一些本地部署的语言模型的时候,往往只能进行文字对话,这一片博客教大家如何实现语音转文字和文字转语音,之后接入ollama的模型就能进行语音对话了。
2.思路
使用离线本地语音:pyttsx3实现文字转语言,然后使用whisper实现语音转文字
3.安装python包
pip install pyttsx3pip install whisper
- 文字转语音 (TTS):
- 使用
pyttsx3
将输入文本转换为音频文件output.wav
。 pyttsx3
生成的语音文件是本地生成的,不依赖于网络。
- 使用
- 语音转文字 (STT):
- 使用 Whisper 模型将
output.wav
文件中的语音转录为文字。 - Whisper 通过 PyTorch 在本地运行,不需要外部网络访问。
- 使用 Whisper 模型将
3.程序:
import pyttsx3
import whisper
import os# 文字转语音(TTS)部分
def text_to_speech(text, output_file="语音文字相互转换/output.wav"):# 初始化 pyttsx3 引擎engine = pyttsx3.init()# 设置语速和音量engine.setProperty('rate', 150) # 语速engine.setProperty('volume', 1.0) # 音量# 将文本保存为音频文件engine.save_to_file(text, output_file)# 运行并生成语音文件engine.runAndWait()print(f"Text-to-Speech conversion complete! Audio saved as '{output_file}'.")# 语音转文字(STT)部分
def speech_to_text(input_file):# 加载 Whisper 模型model = whisper.load_model("base")# 转录音频文件result = model.transcribe(input_file)# 打印转录的文本print("Transcribed Text:", result["text"])# 主函数
if __name__ == "__main__":# 1. 输入文本text = "hello,today is a good day!"# 2. 文字转语音text_to_speech(text, output_file="语音文字相互转换/output.wav")# 3. 语音转文字speech_to_text("语音文字相互转换/output.wav")