绝对干货,直接代码详解
1. 截取一段音频文件(wav)
eg:audio.wav
2. 验证语音识别账户
var config_data= {
apiKey: "4eymBfpmT4Laaaaaaaa",
secretKey: "daa65d352b7ec5583aaaaaaaaaaaaaaa",
cuid: "sewise_pakison",
format: "wav",
rate: 16000
};
var httpobj=require('./http.js');
httpobj.httpget('openapi.baidu.com',"http://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials" + "&client_id=" + config_data.apiKey + "&client_secret=" + config_data.secretKey,'GET',function(ret){
console.log(ret);
})
3. 利用dns模块解析百度语音的域名IP地址
var dns=require('dns');
dns.resolve('vop.baidu.com',function(err,data){
console.log(data);
})
4. 最后一步最重要,创建流将wav文件上传到百度语音接口进行解析
var file = fs.readFileSync( './audio.wav');
var len = file.length;
var dns=require('dns');
dns.resolve('vop.baidu.com',function(err,data){
if(err) return;
var request = http.request({
hostname:data[0],
host : 'vop.baidu.com',
port : 80,
path : '/server_api?token='+ret.access_token+'&cuid='+config_data.cuid,
method : 'POST',
headers : {
'Content-Type' : 'audio/wav; rate='+config_data.rate,
'Content-Length' :len,
'Host':'vop.baidu.com'
}
}, function (response) {
var data = '';
response.on('data', function(chunk) {
data += chunk.toString();
});
response.on('end', function() {
var result=JSON.parse(data);
if(result.err_no==0){
console.log(result.result[0]);
}else{
console.log('failed')
}
});
});
fs.createReadStream('./audio.wav', { bufferSize: 4 * 1024 })
// set "end" to false in the options so .end() isnt called on the request
.pipe(request)
.on('end', function() {
});