python调用pc的语音借口

先安装:

bash 复制代码
pip install pyttsx3

再运行:

python 复制代码
import pyttsx3
# 初始化语音引擎
def init_engine():
    engine = pyttsx3.init()
    # 设置中文语音
    voices = engine.getProperty('voices')
    
    for voice in voices:
        if 'chinese' in voice.name.lower():
            engine.setProperty('voice', voice.id)
            break
    
    # 设置语速 (默认是200)
    engine.setProperty('rate', 150)
    
    # 添加以下行来防止引擎过早释放
    engine.setProperty('debug', True)
    
    return engine

# 说中文的函数
def speak_chinese(text, engine=None):
    local_engine = engine if engine else init_engine()
    try:
        local_engine.say(text)
        local_engine.runAndWait()
        # 添加以下行来确保语音完全播放完成
        local_engine.stop()
    except Exception as e:
        print(f"语音转换出错: {str(e)}")
    finally:
        # 如果是本地创建的引擎,则需要清理
        if engine is None:
            del local_engine

# 使用示例
if __name__ == "__main__":
    text = "毛主席真伟大"
    speak_chinese(text)

高声呼喊,"毛主席真伟大"

相关推荐
智商低情商凑3 小时前
Go学习之 - Goroutines和channels
开发语言·学习·golang
半桶水专家3 小时前
Go 语言时间处理(time 包)详解
开发语言·后端·golang
编程点滴3 小时前
Go 重试机制终极指南:基于 go-retry 打造可靠容错系统
开发语言·后端·golang
顾安r3 小时前
11.20 开源APP
服务器·前端·javascript·python·css3
实心儿儿3 小时前
C++ —— 模板进阶
开发语言·c++
萧鼎4 小时前
Python PyTesseract OCR :从基础到项目实战
开发语言·python·ocr
二川bro4 小时前
第57节:Three.js企业级应用架构
开发语言·javascript·架构
sali-tec4 小时前
C# 基于halcon的视觉工作流-章62 点云采样
开发语言·图像处理·人工智能·算法·计算机视觉
没有bug.的程序员5 小时前
Java 字节码:看懂 JVM 的“机器语言“
java·jvm·python·spring·微服务
这人很懒没留下什么6 小时前
SpringBoot2.7.4整合Oauth2
开发语言·lua