文字转语音 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)}")
相关推荐
WebInfra2 分钟前
Rsdoctor 1.2 发布:打包产物体积一目了然
前端·javascript·github
用户527096487449035 分钟前
SCSS模块系统详解:@import、@use、@forward 深度解析
前端
兮漫天35 分钟前
bun + vite7 的结合,孕育的 Robot Admin 【靓仔出道】(十一)
前端·vue.js
xianxin_36 分钟前
CSS Text(文本)
前端
秋天的一阵风37 分钟前
😈 藏在对象里的 “无限套娃”?教你一眼识破循环引用诡计!
前端·javascript·面试
电商API大数据接口开发Cris40 分钟前
API 接口接入与开发演示:教你搭建淘宝商品实时数据监控
前端·数据挖掘·api
用户14095081128041 分钟前
原型链、闭包、事件循环等概念,通过手写代码题验证理解深度
前端·javascript
汪子熙42 分钟前
错误消息 Could not find Nx modules in this workspace 的解决办法
前端·javascript
skeletron20111 小时前
🚀AI评测这么玩(2)——使用开源评测引擎eval-engine实现问答相似度评估
前端·后端
前端开发爱好者1 小时前
Vite 7.1.1 疑似遭受大规模 "攻击"!
前端·vue.js·vite