文字转语音 edge_tts

1、前沿

这是一款微软语音转文字的项目,不要电脑配置因为他是通过类爬虫方式把文字转语音,跟官方比起来速度会慢一点但是基本够用

https://github.com/rany2/edge-tts

2、代码封装

默认是通过命令行的方式不适合集成到我们自己的项目通过封装成接口的方式使用

复制代码
@router.get("/text-to-speech", tags=["语音合成"], summary="文字转语音")
async def text_to_speech(text: str):
    try:
        file_path = await edge_tts_async(text)
        return FileResponse(
            path=file_path, media_type="audio/mp3", filename=os.path.basename(file_path)
        )
    except Exception as e:
        return {"error": f"转换失败: {str(e)}"}


import edge_tts

async def edge_tts_async(text):
    num = random.randint(1, 100000000)
    static_dir = "static/audio"
    os.makedirs(static_dir, exist_ok=True)
    file_path = os.path.join(static_dir, f"{num}.mp3")

    # 从配置获取代理设置(如果有)
    proxy = None
    if "proxies" in GLOBAL_CONFIG and "proxy" in GLOBAL_CONFIG["proxies"]:
        proxy = GLOBAL_CONFIG["proxies"]["proxy"]
    
    try:
        # 使用edge_tts.Communicate类进行文字转语音
        communicate = edge_tts.Communicate(
            text,
            "zh-CN-XiaoyiNeural",
            proxy=proxy,
            connect_timeout=20,
            receive_timeout=60
        )
        
        # 保存音频文件
        await communicate.save(file_path)
        return file_path
    except Exception as e:
        log_error(f"文字转语音失败: {str(e)}")
        raise Exception(f"TTS conversion failed: {str(e)}")
相关推荐
朱涛的自习室23 分钟前
212 个需求、22 万行代码:Agent 接管开源项目的 19 天
android·前端·人工智能
aZhe的全栈知识分享26 分钟前
AI 还原 Figma 效果总达不到预期?先别急着让它写代码
前端·后端·面试
review4454327 分钟前
Codex Hooks 入门实战:生命周期事件、matcher 与5分钟跑通一个钩子
前端·agent·vibecoding
函数小陈29 分钟前
阿里云部署DSH与RAM完成运维
前端·后端
用户4993350250743 分钟前
JS 作用域劫持的死穴:动态 this 穿透,以及 AST 怎么救
前端
IT_陈寒1 小时前
React的setState真是个演员,你以为它同步其实在装睡
前端·人工智能·后端
孟健3 小时前
Claude Code 同需求写两版对比:装不装 frontend-design 差多远?
前端·ai编程·claude
梦de天空一米16885 小时前
【一个重复id让游戏卡在62%,聊聊配置表检查】
前端
ryn483985 小时前
01 一个功能模块,怎么分层才不乱
前端·ai编程·claude
Amos_Web5 小时前
通过 Rspack 源码学 Rust(五):读懂 Result 与问号运算符的错误返回
前端