当前位置: 首页 > news >正文

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

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

问题背景:

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

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

相关文章:

  • 数据安全的重要性:守护数字时代的基石
  • Elasticsearch
  • 【CSS】如何写渐变色文字并且有打光效果
  • 华为人工智能重要服务总结
  • HALCON根据需要创建自定义函数
  • 【无人机设计与控制】 四轴飞行器的位移控制
  • 真实案例分享:零售企业如何避免销售数据的无效分析?
  • Android 优雅封装Glide
  • SprinBoot+Vue校园数字化图书馆系统的设计与实现
  • Oracle高级压缩和透明数据加密组合实验
  • 读软件设计的要素05概念的特性
  • 基于STM32设计的智能安防系统(微信小程序)(218)
  • linux学习之线程
  • Linux网络编程IO管理
  • JLabel设置字体大小颜色背景色
  • Go语言结构体和元组全面解析
  • 代码随想录八股训练营第三十三天| C++
  • 火狐浏览器设置秘籍:让https协议下的ws不加密时运行无阻(WebSocket connection HTTPS)
  • 【个人笔记】VCS工具与命令
  • HashMap中常用的函数
  • 马上评丨机械停车库成“僵尸库”,设计不能闭门造车
  • 李祥翔评《孔子哲学思微》︱理性秩序与美学秩序的碰撞
  • 辽宁省信访局副局长于江调任辽宁省监狱管理局局长
  • 文化体验+商业消费+服务创新,上海搭建入境旅游新模式
  • 中国人民银行行长潘功胜会见世界银行行长彭安杰
  • 明查|把太平洋垃圾污染问题甩锅中国,特朗普用的是P过的图