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


http://www.mrgr.cn/news/22732.html

相关文章:

  • 基于单片机的盲人智能水杯系统(论文+源码)
  • 声音克隆工具CosyVoice
  • 极狐GiLab 17.3 重点功能解读 升级指南
  • 基于微信小程序+Java+SSM+Vue+MySQL的考研论坛
  • ESP32 UDP 05
  • SpringBoot集成MyBatis-Plus
  • 电商数据API接口|唯品会商品详情数据的接入说明【附测试实例】
  • 并网光伏发电对电网电能质量的影响和治理方案
  • 解决:web of science文献检索点不动,只能用作者检索的情况
  • 还不会数据恢复?试试这4款软件吧!
  • 一、java基础面试题
  • 变量与命名
  • 盘点10款顶级加密软件,让企业数据安全得到保障!
  • 1.Python解释器和Pycharm安装设定
  • 代码训练营 Day 27|455.分发饼干 | 376. 摆动序列 | 53. 最大子序和
  • Linux网络:网络协议栈协议
  • 知名公司成间谍帮凶,多名涉密人员参与其中
  • Log4j 1.x如何升级到Log4j 2.x
  • 【Python编程的例子】
  • 【Prometheus】PromQL聚合函数详细用法与应用实战