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 会返回一个缓冲区数组,之后你可以将其转换为缓冲区。

相关推荐
海绵宝宝de派小星4 小时前
特征工程技巧与最佳实践
ai
CoderJia程序员甲5 小时前
GitHub 热榜项目 - 日榜(2026-01-22)
ai·开源·大模型·github·ai教程
Tom·Ge7 小时前
Claude Code 和 Cursor 有何异同
ai
哥布林学者10 小时前
吴恩达深度学习课程五:自然语言处理 第二周:词嵌入(六)情绪分类和词嵌入除偏
深度学习·ai
CoderJia程序员甲12 小时前
GitHub 热榜项目 - 日榜(2026-01-24)
git·ai·开源·llm·github
玉梅小洋13 小时前
Unity Muse 完整使用文档:Sprite+Texture专项
unity·ai·游戏引擎
带刺的坐椅13 小时前
Claude Code Agent Skills vs. Solon AI Skills:从工具增强到框架规范的深度对齐
java·ai·agent·claude·solon·mcp·skills
组合缺一13 小时前
MCP 进化:让静态 Tool 进化为具备“上下文感知”的远程 Skills
java·ai·llm·agent·mcp·skills
方方洛14 小时前
技术实践总结:schema-bridgion:json、xml、yaml、toml文件相互转换
xml·前端·typescript·node.js·json
爱跑步的程序员~14 小时前
大模型prompt工程指南
ai·prompt