Search code examples
node.jsazureazure-speech

Binary file to base64 nodejs


I'm getting a binary audio file when I call the api tts.speech.microsoft.com and I would like to transform this binary into a base64 string.

I've been trying a lot of things, for example:

Buffer.from(body, "binary").toString("base64");

does not work.

I'm not sure 'binary' is the exact word, but it's not a readable format.

Thank you for your help.


Solution

  • I guess you were following the section Make a request and save the response of the offical document Quickstart: Convert text-to-speech using Node.js to write your code, as below.

    var request = require('request');
    
    let options = {
        method: 'POST',
        baseUrl: 'https://westus.tts.speech.microsoft.com/',
        url: 'cognitiveservices/v1',
        headers: {
            'Authorization': 'Bearer ' + accessToken,
            'cache-control': 'no-cache',
            'User-Agent': 'YOUR_RESOURCE_NAME',
            'X-Microsoft-OutputFormat': 'riff-24khz-16bit-mono-pcm',
            'Content-Type': 'application/ssml+xml'
        },
        body: body
    };
    
    function convertText(error, response, body){
      if (!error && response.statusCode == 200) {
        console.log("Converting text-to-speech. Please hold...\n")
      }
      else {
        throw new Error(error);
      }
      console.log("Your file is ready.\n")
    }
    // Pipe the response to file.
    request(options, convertText).pipe(fs.createWriteStream('sample.wav'));
    

    So I change the offical code above to create a function encodeWithBase64 to encode body with Base64.

    function encodeWithBase64(error, response, body){
      if (!error && response.statusCode == 200) {
        var strBase64 = Buffer.from(body).toString('base64');
        console.log(strBase64);
      }
      else {
        throw new Error(error);
      }
      console.log("Your file is encoded with Base64.\n")
    }
    // Pipe the response to file.
    request(options, convertText);
    

    Or you can use the npm packages base64-stream and get-stream to get the string with Base64 from body.

    var base64 = require('base64-stream');
    const getStream = require('get-stream');
    (async () => {
        var encoder = new base64.Base64Encode();
        var b64s = request(options).pipe(encoder);
        var strBase64 = await getStream(b64s);
        console.log(strBase64);
    })();
    

    Otherwise, stream-string also can do it.

    var base64 = require('base64-stream');
    const ss = require('stream-string');
    var encoder = new base64.Base64Encode();
    var b64s = request(options).pipe(encoder);
    ss(b64s).then(data => {
      console.log(data);
    })