微信网页接口有3个录音相关接口
开始录音接口
wx.startRecord();
停止录音接口
wx.stopRecord({
success: function (res) {
var localId = res.localId;
}
});
监听录音自动停止接口
wx.onVoiceRecordEnd({
// 录音时间超过一分钟没有停止的时候会执行 complete 回调
complete: function (res) {
var localId = res.localId;
}
});
还有1个语音转换接口
识别音频并返回识别结果接口
wx.translateVoice({
localId: '', // 需要识别的音频的本地Id,由录音相关接口获得
isShowProgressTips: 1, // 默认为1,显示进度提示
success: function (res) {
alert(res.translateResult); // 语音识别的结果
}
});
所以可以利用这几个接口实现语音搜索
config签名验证前面微信分享有写过,这里不再写
网页样式
<% if @open %>
<div class="search-micro">
<div class="talk" id="talk" data-type="product"><%= icon 'microphone' %> 按住说话</div>
</div>
<% end %>
需要判断是否微信浏览器,所以open为判断
@open = false
if is_wechat_brower
@open = true
end
js
wx.config({
debug: false,
appId: '<%= @jsapi_config[:appid] %>', // 必填,公众号的唯一标识
timestamp: <%= @jsapi_config[:timestamp] %>, // 必填,生成签名的时间戳
nonceStr: '<%= @jsapi_config[:noncestr] %>', // 必填,生成签名的随机串
signature: '<%= @jsapi_config[:signature] %>',// 必填,签名
jsApiList: ['startRecord', 'stopRecord', 'onVoiceRecordEnd', 'translateVoice'] // 必填,需要使用的JS接口列表
});
wx.ready(function(){
var localId;
//开始录音
$('#talk').on('touchstart',function(e){
e.preventDefault();
var $this = $(this);
$this.addClass('red');
//开始录音
wx.startRecord();
});
//停止录音接口
$('#talk').on('touchend', function(){
var $this = $(this);
$this.removeClass('red');
//停止录音接口
wx.stopRecord({
success: function (res) {
// alert(res.localId);
localId = res.localId;
wx.translateVoice({
localId: localId, // 需要识别的音频的本地Id,由录音相关接口获得
isShowProgressTips: 1, // 默认为1,显示进度提示
success: function (res) {
// alert(res.translateResult);
result = res.translateResult;
//去掉最后一个句号
result = result.substring(0,result.length-1);
var searchUrl = "/mobile/search?utf8=✓&search_type=product&text=" + result;
window.location.href = searchUrl;
}
});
}
});
});
//监听录音自动停止接口
wx.onVoiceRecordEnd({
//录音时间超过一分钟没有停止的时候会执行 complete 回调
complete: function (res) {
localId = res.localId;
// alert(localId);
$('#talk').removeClass('red');
wx.translateVoice({
localId: localId, // 需要识别的音频的本地Id,由录音相关接口获得
isShowProgressTips: 1, // 默认为1,显示进度提示
success: function (res) {
// alert(res.translateResult);
result = res.translateResult;
//去掉最后一个句号
result = result.substring(0,result.length-1);
var searchUrl = "/mobile/search?utf8=✓&search_type=product&text=" + result;
window.location.href = searchUrl;
}
});
}
});
});
wx.error(function(res){
// config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
// alert(res);
});
这里有个问题,就是语音识别接口返回结果默认有一个句号结尾 ,至少我这里是这样,所以需要把最后一个字符去掉