I’ve been trying to download audios off the Whatsapp API, however no matter what I try it will not let me.
I first make a call to retrieve the URL of the audio and that works fine, however when I try to download the audio it always errors out.
I’ve tried using fetch and axios, and after playing around with Postman I got it to work there, and I can see my audio but I haven’t managed to get it to work in Node.
I’ve tried using many different headers, but to no avail.
Usually I get a 400 error, but playing around with the headers I’ve managed to get ‘fetch failed’ error, but I’m kinda stuck there, don’t know what else to try.
There are other questions like this one but I’ve tried their answers to no avail already.
My code:
`
async function downloadAudio(url,outputPath, audioType){
var file = fs.createWriteStream(path.join(outputPath, `audio.${audioType}`) );
try {
var response = await fetch(url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Host': new URL(url).host,
'User-Agent': 'PostmanRuntime/7.42.0',
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
'Transfer-Encoding': 'chunked',
'Content-Type': 'audio/ogg',
},
});
if (!response.ok) {
throw new Error(`Failed to get '${url}' (${response.status})`);
}
response.body.pipe(file);
return new Promise((resolve, reject) => {
file.on('finish', () => {
file.close();
console.log(`Downloaded audio to ${outputPath}`);
resolve();
});
file.on('error', (err) => {
fs.unlink(outputPath, () => {});
reject(err);
});
});
} catch (error) {
console.error(`Error downloading the audio: ${error.message} n${error}`);
}
}`