1

I have a base64 string of audio file. I want to save this as a file in local folder with nodejs. I have integrated and done this with the fs library and got mp3 file in local folder, but not able to play. Could you please support me to solve this issue. here is my code in nodejs.

let base64File = 'data:audio/mp3;base64,UklGRiRAHwBXQVZFZm10IBAAAAABAAIAgLsAAAD...........';
const DIR = BASE_PATH + 'src/storage/voice/';
const filename = 'sample.mp3';
const fileurl = DIR + filetname;
const fileContents = Buffer.from(base64File, 'base64');
fs.writeFile(fileurl, fileContents, (err) => {
   if (err) return console.error(err);
   console.log('file saved to ', filetname);
});
Rugma
  • 13
  • 1
  • 4
  • 2
    You have to cut off the `data:audio/mp3;base64,` part of the string. The whole string is not a base64 string but a [data uri](https://en.wikipedia.org/wiki/Data_URI_scheme), containing a base64 string. – jps Nov 17 '21 at 15:05
  • I tried this also.. but not able to play downloaded file – Rugma Nov 17 '21 at 15:08
  • 2
    it's also not a mp3 but a wav file, judging from the decoded header: `RIFF$@�WAVEfmt ��` – jps Nov 17 '21 at 15:10

1 Answers1

2

As mentioned, your Base64 audio is a raw RIFF/WAV file, and can be directly written as a .wav file

const fs = require('fs')

const wavUrl = 'data:audio/wav;base64,UklGRryMMgBXQVZFZm10IBAAAAABAAIARKwAABCxAgAEA...'
const buffer = Buffer.from(
  wavUrl.split('base64,')[1],  // only use encoded data after "base64,"
  'base64'
)
fs.writeFileSync('./audio.wav', buffer)
console.log(`wrote ${buffer.byteLength.toLocaleString()} bytes to file.`)

If you truly have an Opus or MP3 file, you must decode it to raw PCM audio first, then create a buffer with both WAV headers and the PCM data before writing the .wav file.

anthumchris
  • 8,245
  • 2
  • 28
  • 53