文字转语音 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)}")
相关推荐
艾小码1 天前
别再开无效复盘会了!前端工程师这样复盘,成长速度快人一步
前端
苏无逢1 天前
CSS基础查缺补漏(持续更新补充)
前端·css
翻斗花园刘大胆1 天前
JavaWeb之快递管理系统(完结)
java·开发语言·前端·jvm·spring·servlet·java-ee
正义的大古1 天前
OpenLayers地图交互 -- 章节四:修改交互详解
前端·javascript·vue.js
深耕AI1 天前
【9/10】前端认证整合:Vue.js 中处理 JWT,实现登录页面和受保护路由
前端·javascript·vue.js
摩羯座-185690305941 天前
VVIC 平台商品详情接口高效调用方案:从签名验证到数据解析全流程
java·前端·数据库·爬虫·python
我是华为OD~HR~栗栗呀1 天前
华为od-前端面经-22届非科班
java·前端·c++·后端·python·华为od·华为
知识分享小能手1 天前
React学习教程,从入门到精通,React Router 语法知识点及使用方法详解(28)
前端·javascript·学习·react.js·前端框架·vue·react
黄毛火烧雪下1 天前
React中Class 组件 vs Hooks 对照
前端·javascript·react.js
gnip1 天前
工作常用设计模式
前端·javascript