「这是我参与11月更文挑战的第6天,活动详情查看:2021最后一次更文挑战」
前言
最近在开发语音评测功能的时候,发现在公众号中使用弛声sdk进行录音评测的时候,录音结束后到返回评测结果比较慢,在做小程序相关功能的时候则明显快多了。那么这里面有什么不同么?为什么公众号sdk这个过程耗时更长?
公众号sdk
先来看看公众号sdk的源码 api.chivoxapp.com/js/wx/AiEng…
需要格式化一下便于查看。其中录音结束处理的部分代码流程如下:
AiEngine.prototype.stopRecord = function (options) {
var that = this;
wx.ready(function () {
wx.stopRecord({
success: function (res) {
...
that._lastVoice = {
localId: res.localId,
tokenId: that._param.request.tokenId,
startTime: that._startTime,
endTime: that._endTime,
duration: that._endTime - that._startTime
};
that._voices[that._lastVoice.tokenId] = that._lastVoice;
that.uploadFile(that._token, that._lastVoice, that._param);
...
},
fail: function (res) {
...
}
});
});
};
可以看到当停止录音调用了uploadFile函数,这个函数的代码如下:
AiEngine.prototype.uploadFile = function (token, file, param) {
var that = this;
wx.ready(function () {
wx.uploadVoice({
localId: file.localId,
isShowProgressTips: param.isShowProgressTips,
success: function (res) {
file.serverId = res.serverId;
that._httpClient.Post({
...
});
},
fail: function (res) {
...
}
});
});
};
可以看到先调用了微信的uploadVoice将声音文件上传到微信的服务器上,然后将音频文件的url和其他信息post给弛声,这样弛声再通过url下载音频分析。
由于中间有一步上传到微信服务器的过程,然后弛声再下载,所以无形的增加了流程的时间。
小程序sdk
但是我在使用小程序sdk的时候,发现上次解析快了很多,难道有什么不同?
再来看看小程序的js文件api.chivoxapp.com/js/wxa/AiEn…
代码中,处理录音部分的代码如下:
c.prototype.startRecord = function(e) {
var d = this;
wx.startRecord({
success: function(f) {
if (d._endTime === 0) {
...
} else {
if (typeof f === "undefined") {
...
} else {
d._lastVoice = {
localId: f.tempFilePath,
tokenId: e.request.tokenId,
startTime: d._startTime,
endTime: d._endTime,
duration: d._endTime - d._startTime
};
d._voices[d._lastVoice.tokenId] = d._lastVoice;
d.uploadFile(d._token, d._lastVoice, e)
}
}
},
fail: function() {
...
}
})
};
可以看到当停止录音调用了uploadFile函数,这个函数代码如下:
c.prototype.uploadFile = function(e, d, g) {
var f = this;
wx.uploadFile({
url: f._host + "/" + f._route + "/eval",
filePath: d.localId,
name: f._utils.generateGuid(),
...
})
};
可以看到这里就与公众号sdk有些差异,这里调用了微信的uploadFile直接将音频文件上传给弛声解析。这样就比公众号少了一步上传到微信服务器再下载的过程,自然等待时间就会少很多。
原因
那么为什么公众号不能直接上传给弛声,因为不论公众号还是小程序录音后得到的都不是音频文件的路径,而是一个微信自定义格式的文件ID,通过这个ID我们无法直接拿到文件路径。而小程序提供了一个通过ID就可以将文件上传到自定义服务器的api,公众号只提供了一个通过ID上传到微信服务器的api,所以公众号处理起来要慢一些