如何在 Node.js 中处理 OpenAI Text-To-Speech API 的响应?

问题描述 投票:0回答:1

这是我的代码:

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-Type
audio/mpeg
Transfer-Encoding
chunked

我无法使用openai SDK,因为它无论何时都会抛出错误。我必须在这里使用 API 调用。顺便说一句,邮递员可以通过调用它来获取文件。

node.js response openai-api
1个回答
0
投票
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 将返回缓冲区数组,您可以稍后将其转换为缓冲区。

© www.soinside.com 2019 - 2024. All rights reserved.