DEV Community

Ariyan Ashfaque Mostafa
Ariyan Ashfaque Mostafa

Posted on

How to convert audio.mp3 to audio.flac?

Google cloud speech to text only accepts flac or raw formatted audio files. I want to convert an audio.mp3/wav file to audio.flac but the converter functions I am using is not working properly. Can anyone suggest me a better way to convert audio.mp3/wav file to audio.flac.

export const SpeechToText = function (audioFileData, contentType) {
  try {
    let reader = new FileReader();
    contentType = contentType.toLowerCase();
    return new Promise((resolve) => {
      reader.onload = function (event: any) {
        let data = event.target.result.split(",");
        let b64Data = data[1];
        let blob = getBlobFromBase64Data(b64Data, contentType);
        let blobUrl = URL.createObjectURL(blob);
        let fileName = audioFileData.name.substring(
          0,
          audioFileData.name.lastIndexOf(".")
        );

        let convertedAudio = {
          path: blobUrl,
          type: contentType,
          name: `${fileName}.flac`,
        };

        resolve(convertedAudio);
      };
      reader.readAsDataURL(audioFileData);
    });
  } catch (e) {
    console.log("Error occurred while converting : ", e);
  }
};

function getBlobFromBase64Data(b64Data, contentType, sliceSize = 512) {
  const byteCharacters = atob(b64Data);
  const byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);

    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }

  const blob = new Blob(byteArrays, { type: contentType });
  return blob;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)