如何在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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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