这是我的代码:
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调用。顺便说一下,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会返回一个缓冲区数组,你可以稍后将其转换为缓冲区。