node百度語音識別
阿新 • • 發佈:2019-01-06
絕對乾貨,直接程式碼詳解
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() { });