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)

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

相关推荐
武子康2 小时前
Java-82 深入浅出 MySQL 内部架构:服务层、存储引擎与文件系统全覆盖
java·开发语言·数据库·学习·mysql·spring·微服务
倒悬于世2 小时前
开源的语音合成大模型-Cosyvoice使用介绍
人工智能·python·语音识别
惜.己3 小时前
pytest中使用skip跳过某个函数
开发语言·python·测试工具·pytest
姜暮儿3 小时前
C++ 性能优化
开发语言·c++
啊呦.超能力4 小时前
QT开发---多线程编程
开发语言·qt
挽风8214 小时前
Excel file format cannot be determined, you must specify an engine manually.
python
铭哥的编程日记4 小时前
《从C风格到C++风格:内存管理的进化之路》
开发语言·c++
秃了也弱了。4 小时前
reflections:Java非常好用的反射工具包
java·开发语言
叫我:松哥5 小时前
基于网络爬虫的在线医疗咨询数据爬取与医疗服务分析系统,技术采用django+朴素贝叶斯算法+boostrap+echart可视化
人工智能·爬虫·python·算法·django·数据可视化·朴素贝叶斯
Joker—H5 小时前
【Java】Reflection反射(代理模式)
java·开发语言·经验分享·代理模式·idea