forked from microsoft/BotBuilder-Samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspeech-service.js
More file actions
85 lines (75 loc) · 2.55 KB
/
Copy pathspeech-service.js
File metadata and controls
85 lines (75 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
var uuid = require('node-uuid'),
request = require('request');
var SPEECH_API_KEY = process.env.MICROSOFT_SPEECH_API_KEY;
// The token has an expiry time of 10 minutes https://www.microsoft.com/cognitive-services/en-us/Speech-api/documentation/API-Reference-REST/BingVoiceRecognition
var TOKEN_EXPIRY_IN_SECONDS = 600;
var speechApiAccessToken = '';
exports.getTextFromAudioStream = function (stream) {
return new Promise(
function (resolve, reject) {
if (!speechApiAccessToken) {
try {
authenticate(function () {
streamToText(stream, resolve, reject);
});
} catch (exception) {
reject(exception);
}
} else {
streamToText(stream, resolve, reject);
}
}
);
};
function authenticate(callback) {
var requestData = {
url: 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken',
headers: {
'content-type': 'application/x-www-form-urlencoded',
'Ocp-Apim-Subscription-Key': SPEECH_API_KEY
}
};
request.post(requestData, function (error, response, token) {
if (error) {
console.error(error);
} else if (response.statusCode !== 200) {
console.error(token);
} else {
speechApiAccessToken = 'Bearer ' + token;
// We need to refresh the token before it expires.
setTimeout(authenticate, (TOKEN_EXPIRY_IN_SECONDS - 60) * 1000);
if (callback) {
callback();
}
}
});
}
function streamToText(stream, resolve, reject) {
var speechApiUrl = [
'https://speech.platform.bing.com/recognize?scenarios=smd',
'appid=D4D52672-91D7-4C74-8AD8-42B1D98141A5',
'locale=en-US',
'device.os=wp7',
'version=3.0',
'format=json',
'form=BCSSTT',
'instanceid=0F8EBADC-3DE7-46FB-B11A-1B3C3C4309F5',
'requestid=' + uuid.v4()
].join('&');
var speechRequestData = {
url: speechApiUrl,
headers: {
'Authorization': speechApiAccessToken,
'content-type': 'audio/wav; codec=\'audio/pcm\'; samplerate=16000'
}
};
stream.pipe(request.post(speechRequestData, function (error, response, body) {
if (error) {
reject(error);
} else if (response.statusCode !== 200) {
reject(body);
} else {
resolve(JSON.parse(body).header.name);
}
}));
}