如何在pyttsx3中打印正在朗读的单词?不可行可换其他TTS库
解决pyttsx3打印当前朗读单词的问题
问题原因
你看到的name参数返回None是因为pyttsx3的回调函数中,该参数用于标识语音合成的发声单元ID,并非传递单词内容。而location和length是当前朗读单词在原始文本中的起始索引和长度,我们可以利用这两个值提取对应单词。
修改后的pyttsx3代码
直接通过位置索引截取原文本中的单词:
import pyttsx3 # 存储要朗读的原始文本 text_to_speak = 'The quick brown fox jumped over the lazy dog.' def onStart(name): print('开始朗读') def onWord(name, location, length): # 利用位置索引截取当前朗读的单词 current_word = text_to_speak[location:location+length] print(f'正在朗读: {current_word}') def onEnd(name, completed): print('朗读结束' if completed else '朗读中断') engine = pyttsx3.init() engine.connect('started-utterance', onStart) engine.connect('started-word', onWord) engine.connect('finished-utterance', onEnd) engine.say(text_to_speak) engine.runAndWait()
优化方案(处理标点干扰)
如果原文本包含标点,可能导致截取内容不准确,可先预处理文本拆分单词:
import pyttsx3 import re text_to_speak = 'The quick brown fox jumped over the lazy dog.' # 拆分单词并去除标点 word_list = re.findall(r'\b\w+\b', text_to_speak) # 记录每个单词在原文本中的起始和结束位置 word_positions = [] current_pos = 0 for word in word_list: pos = text_to_speak.find(word, current_pos) word_positions.append((pos, pos + len(word))) current_pos = pos + len(word) def onWord(name, location, length): # 匹配当前位置对应的单词 for idx, (start, end) in enumerate(word_positions): if start <= location < end: print(f'正在朗读: {word_list[idx]}') break engine = pyttsx3.init() engine.connect('started-word', onWord) engine.say(text_to_speak) engine.runAndWait()
替代方案(使用其他库)
如果pyttsx3的回调机制不符合需求,可使用gTTS配合playsound实现,但注意gTTS需要联网:
from gtts import gTTS from playsound import playsound import os import re text_to_speak = 'The quick brown fox jumped over the lazy dog.' word_list = re.findall(r'\b\w+\b', text_to_speak) # 逐个朗读单词并打印 for word in word_list: print(f'正在朗读: {word}') tts = gTTS(text=word, lang='en') temp_file = 'temp.mp3' tts.save(temp_file) playsound(temp_file) os.remove(temp_file)
内容的提问来源于stack exchange,提问作者Ninja_Soup
相关产品推荐
相关产品推荐

