You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建使用Azure TTS生成音频并返回给前端的Express.js接口?

Express返回Azure TTS生成的音频ArrayBuffer的完整实现方案

核心逻辑说明

  • 不需要转Base64编码:Base64会增加33%左右的体积,直接转Node.js原生Buffer即可,Express的res.send()原生支持Buffer类型的二进制响应
  • 必须设置正确的响应头:要和你在Azure TTS中配置的音频输出格式完全对应,避免浏览器无法解析播放

完整后端路由代码示例

以下代码基于你已经可以正常调用Azure TTS拿到音频ArrayBuffer的前提编写:

const express = require('express');
const router = express.Router();
// 你已经引入的azure tts sdk
const sdk = require("microsoft-cognitiveservices-speech-sdk");

router.get('/api/word/:some_word', async (req, res) => {
  const targetWord = req.params.some_word;

  // --- 这里是你已经实现的调用Azure TTS获取ArrayBuffer的逻辑 ---
  // 示例:你已经拿到了音频的ArrayBuffer,变量名为audioArrayBuffer
  // const audioArrayBuffer = 你调用Azure TTS返回的结果
  // ----------------------------------------------------------

  // 1. 把ArrayBuffer转成Node.js原生Buffer
  const audioBuffer = Buffer.from(audioArrayBuffer);

  // 2. 设置响应头,根据你实际的音频格式调整Content-Type:
  // MP3格式对应 Content-Type: audio/mpeg
  // WAV格式对应 Content-Type: audio/wav
  // OGG格式对应 Content-Type: audio/ogg
  res.set({
    'Content-Type': 'audio/mpeg',
    'Content-Length': audioBuffer.length,
    // 可选配置:设置缓存规则,减少重复请求Azure TTS的成本,max-age单位为秒
    'Cache-Control': 'public, max-age=86400'
  });

  // 3. 直接返回音频Buffer即可
  res.send(audioBuffer);
});

module.exports = router;

前端调用方法

方案1:直接用Audio对象播放(最简单)

无需手动处理二进制流,直接把接口地址作为音频源即可:

const targetWord = "apple";
const audio = new Audio(`/api/word/${targetWord}`);
audio.play().catch(err => console.error('播放失败:', err));

方案2:fetch获取后自定义处理

如果需要对音频流做二次处理,可以用fetch获取二进制数据:

const targetWord = "apple";
fetch(`/api/word/${targetWord}`)
  .then(res => res.arrayBuffer())
  .then(arrayBuffer => {
    // 自定义处理逻辑示例:用AudioContext播放
    const audioContext = new AudioContext();
    audioContext.decodeAudioData(arrayBuffer, buffer => {
      const source = audioContext.createBufferSource();
      source.buffer = buffer;
      source.connect(audioContext.destination);
      source.start();
    })
  })

常见注意事项

  • 请确保Azure TTS配置的输出格式和你设置的Content-Type完全对应,比如你在SpeechConfig里设置的是MP3类输出格式,就用audio/mpeg作为Content-Type
  • 如果接口需要跨域访问,要提前配置CORS中间件,允许前端域名访问
  • 如果生成的音频时长很长,可以改用流式返回减少内存占用,短单词发音用上述方案完全够用

内容的提问来源于stack exchange,提问作者Xavier Taylor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 05:27:03