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

相关推荐
小薛博客1 小时前
4、前后端联调文生文、文生图事件
java·ai
蜡笔小柯南4 小时前
解决:npm install报错,reason: certificate has expired
前端·npm·node.js
LucianaiB8 小时前
使用GpuGeek高效完成LLaMA大模型微调:实践与心得分享
ai·llama·ai自动化·gpugeek
素雪风华10 小时前
构建RAG混合开发---PythonAI+JavaEE+Vue.js前端的实践
java·vue.js·python·ai·语言模型·llms·qwen千问大模型
程序员拂雨11 小时前
Next.js 知识框架总结
node.js
哎哟喂_!13 小时前
Node.js 循环依赖问题详解:原理、案例与解决方案
前端·chrome·node.js
Coding的叶子13 小时前
Node.js 安装 + React Flow 快速入门:环境安装与项目搭建
react.js·node.js·react flow·fgai·react agent
胡玉洋15 小时前
从新手到高手:全面解析 AI 时代的「魔法咒语」——Prompt
人工智能·ai·prompt·transformer·协议
GISer_Jing16 小时前
编译原理AST&以Babel为例进行解读、Webpack中自定义loader与plugin
前端·webpack·node.js
GISer_Jing16 小时前
Webpack中Compiler详解以及自定义loader和plugin详解
前端·webpack·node.js