How to handle the response OpenAI Text-To-Speech API in Node.js?

**题意:**如何在 Node.js 中处理 OpenAI 文字转语音 API 的响应?

问题背景:

Here's my code: 以下是我的代码:

TypeScript 复制代码
const speechUrl = 'https://api.openai.com/v1/audio/speech';
    
const headers = {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`
};

async function voiceGenerator(text) {
    console.log('voiceGenerator is triggered');
    console.log('text: ', text);
    const body = {
        "model": "tts-1",
        "input": text,
        "voice": "alloy",
        "response_format": "mp3",
        "speed": 0.9
    };

    return axios.post(speechUrl, body, { headers: headers })
    .then((res) => {
        if (res.status === 200 || res.status === 204) {
            // res.data = Buffer.from(res.data, 'binary');
            return res.data;
        } else {
            console.log('res: ', res);
            throw res;
        }
    })
    .catch((err) => {
        console.error('OpenAI API failed, error: ', err);
        throw err;
    });
}

And my question is that how do I convert the thing I received into mp3 buffer and store it? I don't know what exactly am I receiving. All I know is that the Content-Type is audio/mpeg and Transfer-Encoding is chunked.

我的问题是,如何将我收到的内容转换为 mp3 缓冲区并存储?我不知道我收到的到底是什么。我只知道 `Content-Type` 是 `audio/mpeg`,`Transfer-Encoding` 是分块传输(chunked)。

I can't use openai SDK because it keep throws error no matter when. I had to use API call here. Postman can just get the file by calling it btw.

我不能使用 OpenAI SDK,因为无论何时使用都会抛出错误。我不得不在这里使用 API 调用。顺便提一下,Postman 可以通过调用直接获取文件。

问题解决:

复制代码
async function voiceGenerator(text) {
    console.log('voiceGenerator is triggered');
    console.log('text: ', text);
    const body = {
        "model": "tts-1",
        "input": text,
        "voice": "alloy",
        "response_format": "mp3",
        "speed": 0.9
    };

    return axios.post(speechUrl, body, { headers: headers, responseType: 'arraybuffer' })
    .then((res) => {
        if (res.status === 200 || res.status === 204) {
            const buffer = Buffer.from(res.data);

            return buffer;
        } else {
            console.log('res: ', res);
            throw res;
        }
    })
    .catch((err) => {
        console.error('OpenAI API failed, error: ', err);
        throw err;
    });
}

This is the solution I reached. It turns out that by adding "responseType": "arraybuffer", the API would return the buffer array that you can convert into buffer later on.

这是我得到的解决方案。结果发现,通过添加 `"responseType": "arraybuffer"`,API 会返回一个缓冲区数组,之后你可以将其转换为缓冲区。

相关推荐
LYFlied14 小时前
【一句话概述】Webpack、Vite、Rollup 核心区别
前端·webpack·node.js·rollup·vite·打包·一句话概述
CoderJia程序员甲15 小时前
GitHub 热榜项目 - 日榜(2025-12-15)
git·ai·开源·llm·github
Brian Xia15 小时前
Nano-vLLM 源码分析(一) - 课程大纲
python·ai
爱笑的眼睛1115 小时前
文本分类的范式演进:从统计概率到语言模型提示工程
java·人工智能·python·ai
weixin_4166600715 小时前
插件分享:将AI生成的数学公式无损导出为Word文档
人工智能·ai·word·论文·数学公式·deepseek
欢喜躲在眉梢里17 小时前
基于 openFuyao 社区的无硬件 UB 开发实战指南
运维·数据库·人工智能·vscode·ai·开发工具·go开发
机器之心17 小时前
国产芯片也能跑AI视频实时生成了,商汤Seko 2.0揭秘幕后黑科技
人工智能·openai
爱写Bug的小孙17 小时前
Agent 和ReAct Agent区别
ai·langchain·agent·springai
博谷18 小时前
AI搜索革命:如何让ChatGPT主动推荐你的品牌?
ai
机器之心18 小时前
Thinking Machines首款产品重大更新:K2 Thinking、Qwen3-VL都可以微调了
人工智能·openai