node.js - 二进制文件转base64 nodejs

标签 node.js azure azure-speech

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

我一直在尝试很多事情,例如:

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

不起作用。

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

感谢您的帮助。

最佳答案

我猜您正在关注 Make a request and save the response 部分引用官方文档快速入门:使用 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'));

因此,我更改了上面的官方代码,创建了一个函数 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);
})

关于node.js - 二进制文件转base64 nodejs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54423627/

相关文章:

javascript - 是否可以让交互式 Node.js shell 使用 vi 模式?

javascript - session 不是持久的 [PASSPORT]

python - 无法在没有 .NET Azure Python Function App v2 的情况下创建函数

azure - 管理azure函数中的并发请求

python - 语音SDK拖拽错误: Exception with an error code: 0xe (SPXERR_MIC_NOT_AVAILABLE)

laravel - Azure 语音到文本 Webhook header X-MicrosoftSpeechServices-Signature 算法?

node.js - Sequelize.authenticate() 对 Docker 内部的 google cloud sql 连接不起作用(没有成功或错误响应)

javascript - NodeJS 相当于 hmac-sha256 授权的 C# 代码

MongoLab 上的 Node.js 和 MongoDB : "Sockets Closed" On Every Insert

node.js - Microsoft Azure 认知语音转文本 - 返回未定义的 API 错误