我有一个代理服务器,需要在外部API服务器上提出一个请求,从一些文本合成语音. 在API文档中,有一句话告诉我:请求之后,我会得到第一个带有头的响应,之后我会得到流模式的二进制数据,因为响应的主体中有'Transfer—Encoding:chuned'.
所以,我用responseType: 'stream'
做这个东西和这个代码
export const synthesizeVoice = async (contentType: ContentType,
dataForSynthesize: string,
format: string = 'wav16',
voice: string = 'Nec_24000') => {
const token = await authHandler.getAuthData();
const date = new Date(); const timestamp = date.getTime();
const file = fs.createWriteStream(timestamp + '.wav'); // I'm storing getted data on server, so this one needed for that
const response = await axios({
method: 'POST',
url: SAPI.SS_SYNTH,
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': (contentType === 'ssml') ? 'application/ssml' : 'application/text',
},
params: {
format: format,
voice: voice,
},
data: dataForSynthesize,
responseType: 'stream',
});
// I'm writting getted data to a file
response.data.pipe(file);
// and return a path on method above in call stack to return getted binary data on front
return file.path;
};
我的主要问题,在得到响应的第一块(如果我没有弄错)我的方法返回文件的路径(在那一刻文件不是完整的形式)和前面来不是完整的音频文件.
我怎么能等待得到完整的二进制数据并在那之后才发送他们的数据,或者我应该使用来self 的前端的流请求来按块获得数据?
还有,也许这种方式不好,我应该用别的东西?
UPD: Working code
axios({
// nothing to changes here, I've just hidden it to short code example
})
.then(resp => {
// Event listeners on files didn't working in my case, so
// I used it with axios response
resp.data.pipe(file);
resp.data.on('end', () => {
file.close();
res.set({
'Content-Type': 'audio/wav16',
});
const resFile = fs.createReadStream(file.path).pipe(res);
});
})
.catch(err => {
console.log(err.message)
});