简体   繁体   English

二进制文件到base64 nodejs

[英]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. 当我调用api tts.speech.microsoft.com时,我得到一个二进制音频文件,我想将此二进制文件转换为base64字符串。

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. 谢谢您的帮助。

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. 我猜您正在按照Make a request and save the response官方文档Quickstart: Convert text-to-speech using Node.js以编写您的代码”部分的内容进行操作,如下所示。

 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. 因此,我更改了上面的官方代码,以创建一个函数encodeWithBase64以使用Base64编码body

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 . 或者,您可以使用npm软件包base64-streamget-streambody获得带有Base64的字符串。

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. 否则, stream-string也可以做到这一点。

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);
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM