#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)

rain willowBOT
#
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:

  1. Make the API request using a library like axios or the built-in http module.
  2. 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:

  1. We import the required modules (axios and fs).
  2. We set the history_item_id and api_key values.
  3. We make the API request using axios with the responseType set to 'stream'.
  4. In the response handler, we create an empty array chunks to store the incoming data chunks.
  5. We listen for the 'data' event on the response stream and push each chunk to the chunks array.
  6. We listen for the 'end' event, which signals that the entire stream has been received.
  7. After the 'end' event, we concatenate all the chunks into a single Buffer using Buffer.concat(chunks).
  8. Finally, we can use the resulting buffer as needed, e.g., write it to a file using fs.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