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

相关推荐
会写代码的斯皮尔伯格3 小时前
Spring Boot 3整合Spring AI实战:9轮面试对话解析AI应用开发
openai·微服务架构·java面试·rag·ollama·spring ai·spring boot 3
新智元4 小时前
AI教父Hinton首次现身中国,合照全网刷屏!预警AI觉醒临界点已至
人工智能·openai
新智元6 小时前
无惧封禁!Cursor最佳国产平替诞生,彻底告别代码泄露风险
人工智能·openai
月明啸6 小时前
分析总结node中不同文件名后缀如何导入node内置模块
后端·node.js
泉城老铁6 小时前
Vue中实现Word、Excel、PDF预览的详细步骤
前端·vue.js·node.js
花落人散处8 小时前
SpringAI——完成 Function Calling
java·后端·openai
缘来小哥8 小时前
Nodejs的多版本管理,不仅仅只是nvm的使用
前端·node.js
OceanBase数据库官方博客1 天前
OceanBase 混合检索解读:向量+标量,应该优先查哪个
ai·oceanbase·分布式数据库·向量检索·混合检索
Littlewith1 天前
Node.js:连接Mysql、JXcore打包
java·服务器·c语言·开发语言·数据库·mysql·node.js