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

相关推荐
七夜zippoe8 小时前
流式输出:让 AI 回答像打字机一样实时返回(SSE 全链路实战)
人工智能·spring·ai·流式输出·ssf
装不满的克莱因瓶8 小时前
【AI时代必学】一篇文章教会你从零搭建Serverless架构
java·人工智能·ai·云原生·架构·serverless
七夜zippoe10 小时前
多轮对话管理:Session/记忆在 Java 后端怎么存(存储设计实战)
java·开发语言·ai·session·记忆
木头左10 小时前
【Node.js】Markdown 转带图片 Word 文档实战:docx 库转换器设计与 5 个踩坑
node.js·word·markdown·文档自动化
思特奇时空智能10 小时前
大规模点要素地图渲染性能优化实践
vue.js·arcgis·性能优化·node.js·html·gis·webgl
AAA修煤气灶刘哥11 小时前
为什么你的Codex 重连到 5/5 才开始工作?理解重试、协议回退与代理链路
人工智能·架构·openai
吴名氏.13 小时前
Java转AI Agent教程(第十五周)政策时效:过期政策不该被召回,也不能被删掉
java·人工智能·python·ai·ai agent
小七-七牛开发者1 天前
周 1 上线 | DSH 喜提原神进场动画,Anthropic 启动 IPO 路演;黄仁勋辞任;微软全球大宕机超 24 小时
ai·大模型·agent·token·工作流·claudecode·ai coding
GISer_Jing1 天前
GitHub热点I
后端·ai·langchain
QuZhengRong1 天前
【AI】Agent 全栈进阶|AgentScope 沙箱源码解析
python·学习·ai·agent·沙箱