带有websocket的TTS:从二进制数据创建WAV失败

时间:2017-10-09 13:44:39

标签: node.js ibm-cloud ibm-watson

我尝试使用node.js服务器上的websocket连接从二进制数据创建WAV。我使用BluemixTTS创建语音。这是我目前的代码:

'use strict';
const WebSocket = require('ws');
var express = require('express');
var watson = require('watson-developer-cloud');
var vcapServices = require('vcap_services');
var extend = (extend = require('util')._extend);
var fs = require('fs');


var ttsConfig = extend(
    {
        version: 'v1',
        url: 'https://stream.watsonplatform.net/text-to-speech/api',
        username: 'myusernamehere',
        password: "mypasswordhere"
    },
    vcapServices.getCredentials('text_to_speech')
);

var ttsAuthService = watson.authorization(ttsConfig);


var  websocket;
ttsAuthService.getToken({ url: ttsConfig.url }, function(err, token) {
    if (err) {
        console.log('Error retrieving token: ', err);

        return;
    }

    var voice = 'en-US_AllisonVoice';
    var wsURI = 'wss://stream.watsonplatform.net/text-to-speech/api/v1/synthesize?voice=' +
        voice + '&watson-token=' + token;


    websocket = new WebSocket(wsURI);
    websocket.onopen = function(evt) { onOpen(evt) };
    websocket.onclose = function(evt) { onClose(evt) };
    websocket.onmessage = function(evt) { onMessage(evt) };
    websocket.onerror = function(evt) { onError(evt) };

});

function onOpen(evt) {

    var message = {
        text: 'Hello world',
        accept: 'audio/wav',
        timings: ['words']
    };
    websocket.send(JSON.stringify(message));
}
var messages;
var audioStream = null;

function onMessage(evt) {
    if (typeof evt.data === 'string') {
        messages += evt.data;
    } else {

        if(audioStream == null){
            audioStream = evt.data;
        }else{
            audioStream += evt.data;
        }
    }

}

function onClose(evt) {

    console.log(messages);
    var wstream = fs.createWriteStream('test.wav');
    wstream.write((audioStream));
    wstream.end();

}

function  onError(evt) {

}

我获取令牌,触发指定audio / wav的TTS,在onMessage方法中构建我的缓冲区,然后将其写入.wav文件。一切似乎都很好。

然而,该文件以某种方式被破坏,并且无法使用任何音乐播放器打开。我是否会错过一些特殊的编码?

感谢任何帮助 问候, Rambazamba

1 个答案:

答案 0 :(得分:0)

由于数据包含缓冲区,每次收到消息时都必须直接在文件中写入缓冲区,然后在onClose事件中关闭文件流。像这样:

var messages;
var wstream = fs.createWriteStream('test.wav');
function onMessage(evt) {
    if (typeof evt.data === 'string') {
        messages += evt.data;
    } else {
        wstream.write(evt.data)
    }

}

function onClose(evt) {
    console.log(messages);
    wstream.end();
}

function  onError(evt) {

}