文字转语音 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)}")
相关推荐
成为大佬先秃头5 分钟前
渐进式JavaScript框架:Vue 组件
前端·javascript·vue.js
程序员勾践11 分钟前
前端仅传path路径给后端,避免攻击
前端
登山人在路上11 分钟前
Vue 2 中响应式失效的常见情况
开发语言·前端·javascript
董世昌4112 分钟前
创建对象的方法有哪些?
开发语言·前端
问道飞鱼13 分钟前
【前端知识】前端项目不同构建模式的差异
前端·webpack·构建·开发模式·生产模式
be or not to be18 分钟前
CSS 布局机制与盒模型详解
前端·css
runepic32 分钟前
Vue3 + Element Plus 实现PDF附件上传下载
前端·pdf·vue
程序员修心1 小时前
CSS 盒子模型与布局核心知识点总结
开发语言·前端·javascript
elangyipi1231 小时前
前端面试题:CSS BFC
前端·css·面试
程序员龙语1 小时前
CSS 核心基础 —— 长度单位、颜色表示与字体样式
前端·css