Reputation: 493
I have Node/Express server set up in which several thousand audio files are stored within the src folder. I currently have a route set up that sends JSON data in the response object. I wish to also send an mp3 audio file that can be parsed at the front end and be converted to an audio object. I cannot figure out how to encode the audio file such that it may be sent. I have looked into Blobs (these don't seem to be possible in Node) and converting the binary file into a string that may be sent as part of the response body.
Any ideas as to how this may be possible?
Upvotes: 1
Views: 6059
Reputation: 71
As mentioned by @code, you can implement this in your Express app:
res.sendFile(__dirname, "/src/audioFile.mp3");
On your frontend, you can follow these steps. Here's an example using MUI CardMedia:
async getAudio() {
const response = await api.get(`/endpoint`, {
responseType: "blob",
});
return response.data;
}
const [pipelineAudioFile, setPipelineAudioFile] = useState<any>(null);
useEffect(() => {
const audio = await getAudio(id);
const url = URL.createObjectURL(audio);
setPipelineAudioFile(url);
}, []);
{pipelineAudioFile &&
<CardMedia
component="audio"
controls
src={pipelineAudioFile}
/>
}
Upvotes: 0
Reputation: 6319
You can directly send the audio file with something like:
res.sendFile(__dirname, "/src/audioFile.mp3");
Or you could Base64 encode the audio file for your frontend to parse:
fs.readFile("./src/audioFile.mp3", function(err, result) {
res.send(result.toString("base64"));
});
Upvotes: 3