Reputation: 45
I want to send a voice clip to facebook messenger and have it translated to text using Google Cloud Speech to text. However, facebook messenger format set the url to the file, and I have no idea to convert it to base 64. If it's an image like .png and .jpg, it's fine, there are packages for that. But I am trying to convert audio like .mp3 and .m4a files. Is there any tool for that to work with nodejs.
I would prefer not to save the audio file as a local file, beause I am deploying a server using Google App Engine, and doing so will just make the matter super complicated.
Upvotes: 0
Views: 5292
Reputation: 11
import mineType from 'mime-types';
const getBase64 = async (url) => {
try {
const response = await axios.get(url, { responseType: 'arraybuffer' });
const base64 = Buffer.from(response.data, 'binary').toString('base64');
return "data:" + mineType.lookup(url) + ";base64," + base64;
}catch (e) {
return "";
}
}
Upvotes: 1
Reputation: 45
I got what I need from here. While the question is about image, the code seems to work fine sound.
const getBase64 = async (url) => {
try {
var result = await axios
.get(url, {
responseType: 'arraybuffer'
})
.then(response => new Buffer.from(response.data, 'binary').toString('base64'))
return { data: result}
}catch (e) {
return {error: e};
}
}
Upvotes: 1
Reputation: 301
You can look into the FileReader API and possibly the AudioData API - between those two you should have everything you need. With sending audio files over the wire, you don't transfer them as base64. I believe it is either binary or blob iirc.
You can use the FileReader api - read in your audio file using FileReader.readAsArrayBuffer() which will convert your file into a mapped array. From there, you can turn it into a blob object and push it wherever you need.
var uInt8Array = new Uint8Array(mappedArray);
var arrayBuffer = uInt8Array.buffer;
var blob = new Blob([arrayBuffer]);
var url = URL.createObjectURL(blob);
I use this same approach when working with Amazon's Polly to turn text into speech
Upvotes: 0