【问题标题】:Binary file to base64 nodejs二进制文件到base64 nodejs
【发布时间】:2019-01-29 14:48:18
【问题描述】:

当我调用 api tts.speech.microsoft.com 时,我得到一个二进制音频文件,我想将此二进制文件转换为 base64 字符串。

我一直在尝试很多东西,例如:

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

不起作用。

我不确定“二进制”是否准确,但它不是一种可读格式。

感谢您的帮助。

【问题讨论】:

  • 你能澄清“不起作用”吗?代码看起来正确。还有二进制数据是从哪里来的?有些东西比如 fs.readFile 有转换成 base64 的快捷方式。
  • 我通过电话呼叫此端点,并尝试播放声音。当我尝试使用另一个 base64 字符串时,它可以工作,所以我知道这部分的代码是可以的。 @Dominic
  • 其他 base64 字符串从何而来?我的预感是您的原始二进制内容不正确/与工作内容的格式相同
  • 您可以在这里看到转换代码没有任何问题 - repl.it/@DominicTobias/WorstUtilizedComputers(将二进制“apple”转换为 base64 并返回)。所以问题出在您尚未发布的代码中,与工作数据相比,您的二进制数据很可能不正确
  • body 的格式是什么?它只是作为缓冲区/字节数组传入吗?

标签: node.js azure azure-speech


【解决方案1】:

我猜你是按照官方文档Quickstart: Convert text-to-speech using Node.jsMake a request and save the response 部分来编写代码的,如下所示。

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

所以我修改了上面的官方代码,创建了一个函数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);

或者您可以使用 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);
})();

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 2011-12-07
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    相关资源
    最近更新 更多