You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pyttsx3 save_to_file()仅朗读至句号处的问题解决咨询

解决pyttsx3 save_to_file仅朗读至第一个句号的问题

针对你遇到的save_to_file()方法只朗读到第一个句号的问题,可以尝试以下几种解决方案:

方案1:升级pyttsx3到最新版本

这个问题可能是旧版本pyttsx3在macOS平台上的已知bug,执行以下命令更新:

pip install --upgrade pyttsx3

方案2:使用SSML格式包裹文本

pyttsx3支持SSML(语音合成标记语言),通过格式化文本可以避免引擎误判文本结束位置:

import pyttsx3
engine = pyttsx3.init()
# 用SSML标签包裹文本,明确标记停顿而非结束
hell = '<speak>this is period 1.<break time="300ms"/> this is period 2</speak>'
engine.setProperty('voice', 'com.apple.speech.synthesis.voice.alex')
# 开启SSML支持
engine.setProperty('ssml', True)
engine.save_to_file(hell, 'test.mp3')
engine.runAndWait()

方案3:拆分文本并多次调用say()后统一保存

如果上述方法无效,可以将文本拆分成多个片段,通过say()方法逐一添加,再执行保存:

import pyttsx3
engine = pyttsx3.init()
engine.setProperty('voice', 'com.apple.speech.synthesis.voice.alex')
# 拆分文本为多个部分
engine.say("this is period 1.")
engine.say("this is period 2")
# 传入空字符串触发保存所有已添加的语音内容
engine.save_to_file('', 'test.mp3')
engine.runAndWait()

方案4:直接使用macOS原生语音合成API(替代方案)

如果pyttsx3的问题无法解决,可以直接调用macOS的NSSpeechSynthesizer来生成音频:

from AppKit import NSSpeechSynthesizer
import Foundation

speaker = NSSpeechSynthesizer.alloc().initWithVoice_("com.apple.speech.synthesis.voice.alex")
text = "this is period 1. this is period 2"
output_path = Foundation.NSURL.fileURLWithPath_("test.mp3")
# 保存音频到指定路径
speaker.startSpeakingString_toURL_(text, output_path)
# 等待合成完成
while speaker.isSpeaking():
    pass

内容的提问来源于stack exchange,提问作者Dog_Appreciator6000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 22:56:30