#After I can get audio from history item api, how can I convert the file into buffer in nodejs
1 messages · Page 1 of 1 (latest)
AI-generated Answer for wyncg
To convert the audio file received from the GET /v1/history/{history_item_id}/audio API into a buffer in Node.js, you can use the following approach:
- Make the API request using a library like
axiosor the built-inhttpmodule. - The API response will be a stream, which you can read into a buffer.
Here's an example using axios:
const axios = require('axios');
const fs = require('fs');
const historyItemId = 'your_history_item_id';
const apiKey = 'your_api_key';
axios({
method: 'get',
url: `https://api.elevenlabs.io/v1/history/${historyItemId}/audio`,
headers: {
'xi-api-key': apiKey
},
responseType: 'stream'
})
.then(response => {
const chunks = [];
response.data.on('data', chunk => chunks.push(chunk));
response.data.on('end', () => {
const buffer = Buffer.concat(chunks);
// You can now use the buffer, e.g., write it to a file
fs.writeFileSync('output.mp3', buffer);
});
})
.catch(error => {
console.error('Error:', error);
});
In this example:
- We import the required modules (
axiosandfs). - We set the
history_item_idandapi_keyvalues. - We make the API request using
axioswith theresponseTypeset to'stream'. - In the response handler, we create an empty array
chunksto store the incoming data chunks. - We listen for the
'data'event on the response stream and push each chunk to thechunksarray. - We listen for the
'end'event, which signals that the entire stream has been received. - After the
'end'event, we concatenate all the chunks into a singleBufferusingBuffer.concat(chunks). - Finally, we can use the resulting
bufferas needed, e.g., write it to a file usingfs.writeFileSync('output.mp3', buffer).
Note that you'll need to replace 'your_history_item_id' and 'your_api_key' with the actual values for your use case.
References
Title: Get Audio From History Item - ElevenLabs
Path: https://elevenlabs.io/docs/api-reference/get-audio-from-history-item