前言
前端通过录音授权获取录音编码文件上传到阿里云一句话识别并返回结果
前端录音:https://github.com/xiangyuecn/Recorder/blob/master/recorder.wav.min.js
后台识别:https://help.aliyun.com/document_detail/84442.html
1.效果图
2.前端
html
<img class="record_btn" src="record_icon.png"/>
<textarea ></textarea >
<div id="record_cont">
<div class="tips">
<img class="stop_btn" src="shutdown.png" />
<p><span class="time">0:00</span>/1:00</p>
<div class="txt">语音录入中...</div>
<div class="close">X</div>
</div>
</div>
<script type="text/javascript" src="recorder.wav.min.js"></script>
<script>
var rec;
/**
* 获取录音权限
*/
function getRecordPermission(){
rec=Recorder({
type:"wav"
});
//打开麦克风授权获得相关资源
rec.open(function(){
recording_permission = true;
// 3.开始录音
recordStart();
},function(msg,isUserNotAllow){
//用户拒绝了权限或浏览器不支持
alert((isUserNotAllow?"用户拒绝了权限,":"")+"无法录音");
});
};
/**
* 获取识别内容
*/
function getIdentifyContent(source){
//停止录音,得到了录音文件blob二进制对象
rec.stop(function(blob,duration){
/*
blob文件对象,可以用FileReader读取出内容
*/
var form=new FormData();
form.append("upfile",blob,"recorder.pcm"); //和普通form表单并无二致,后端接收到upfile参数的文件,文件名为recorder.pcm
//直接用ajax上传
$.ajax({
url:'/trans' //上传接口地址
,type:"POST"
,contentType:false //让xhr自动处理Content-Type header,multipart/form-data需要生成随机的boundary
,processData:false //不要处理data,让xhr自动处理
,data:form
,success:function(res){
if (typeof JSON.parse(res) === "object") {
res = JSON.parse(res);
if ($.trim(res._status_) === 'fail') {
alert(res._message_);
}else{
source.val(res._message_);
}
timer = 0;
time = '0:00';
second = 0;
// 关闭弹窗
$('#record_cont').removeClass('active');
$('#record_cont .tips .time').html(time);
$('#record_cont .tips .txt').text('语音录入中...');
$('#record_cont .tips').removeClass('stop');
}
}
,error:function(s){
console.error("上传失败",s);
}
});
},function(msg){
alert("录音失败:"+msg);
});
};
var timer = 0;
var time = '0:00';
var second =