如何在Node.js中处理OpenAI文本转语音API的响应?

这是我的代码:

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;    });}

我的问题是,我如何将接收到的内容转换为mp3缓冲区并存储?我不知道我到底接收到了什么。我只知道Content-Typeaudio/mpegTransfer-Encodingchunked

我不能使用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;    });}

这是我找到的解决方案。原来,通过添加”responseType”: “arraybuffer”,API会返回一个缓冲区数组,你可以稍后将其转换为缓冲区。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注