This repository has been archived by the owner on May 6, 2022. It is now read-only.
/
AzureSpeechRecognizer.java
281 lines (247 loc) · 9.24 KB
/
AzureSpeechRecognizer.java
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
package io.spokestack.spokestack.microsoft;
import com.microsoft.cognitiveservices.speech.CancellationReason;
import com.microsoft.cognitiveservices.speech.ProfanityOption;
import com.microsoft.cognitiveservices.speech.ResultReason;
import com.microsoft.cognitiveservices.speech.SpeechRecognitionCanceledEventArgs;
import com.microsoft.cognitiveservices.speech.SpeechRecognitionEventArgs;
import com.microsoft.cognitiveservices.speech.SpeechRecognizer;
import com.microsoft.cognitiveservices.speech.audio.AudioConfig;
import com.microsoft.cognitiveservices.speech.audio.AudioInputStream;
import com.microsoft.cognitiveservices.speech.audio.PushAudioInputStream;
import com.microsoft.cognitiveservices.speech.util.EventHandler;
import io.spokestack.spokestack.SpeechConfig;
import io.spokestack.spokestack.SpeechContext;
import io.spokestack.spokestack.SpeechProcessor;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
/**
* microsoft azure speech service recognizer
*
* <p>
* This component implements the speech processor interface using the Azure
* Speech Service for speech recognition.
* </p>
*
* <p>
* When the speech context is triggered, the recognizer begins streaming
* buffered frames to the API for recognition. Once the speech context becomes
* inactive, the recognizer raises a RECOGNIZE event along with the audio
* transcript. Unfortunately, the Azure Speech SDK currently doesn't return
* confidence values alongside transcripts, so confidence is always set to 1.0.
* </p>
*
* <p>
* Use of the Azure Speech Service implies acceptance of Microsoft's license
* terms, which can be found
* <a href=
* "https://csspeechstorage.blob.core.windows.net/drop/license201809.html">
* here</a>.
* </p>
*
* <p>
* This pipeline component requires the following configuration properties:
* </p>
* <ul>
* <li>
* <b>sample-rate</b> (integer): audio sampling rate, in Hz
* </li>
* <li>
* <b>frame-width</b> (integer): speech frame width, in ms
* </li>
* <li>
* <b>locale</b> (string): BCP-47 language code for speech recognition
* </li>
* <li>
* <b>azure-api-key</b> (string): API key for the Azure Speech
* service
* </li>
* <li>
* <b>azure-region</b> (string): Azure Speech service region
* </li>
* </ul>
*/
public class AzureSpeechRecognizer implements SpeechProcessor {
private final com.microsoft.cognitiveservices.speech.SpeechConfig msConfig;
private SpeechRecognizer recognizer;
private PushAudioInputStream audioStream;
private AudioConfig audioConfig;
private boolean active;
private String locale;
// Azure speech requires little-endian (wav-format) data, so we buffer
// audio frames internally to avoid mutating data coming from the speech
// context
private final ByteBuffer buffer;
/**
* initializes a new recognizer instance.
*
* @param speechConfig Spokestack speech configuration
*/
public AzureSpeechRecognizer(SpeechConfig speechConfig) {
String apiKey = speechConfig.getString("azure-api-key");
String region = speechConfig.getString("azure-region");
int sampleRate = speechConfig.getInteger("sample-rate");
if (speechConfig.containsKey("locale")) {
this.locale = speechConfig.getString("locale");
}
if (sampleRate != 16000) {
throw new IllegalArgumentException(
"Azure only supports a 16kHz sample rate; found: "
+ sampleRate);
}
this.buffer = ByteBuffer.allocateDirect(1500)
.order(ByteOrder.LITTLE_ENDIAN);
this.msConfig = createMsConfig(apiKey, region);
}
com.microsoft.cognitiveservices.speech.SpeechConfig createMsConfig(
String apiKey, String region) {
com.microsoft.cognitiveservices.speech.SpeechConfig config =
com.microsoft.cognitiveservices.speech.SpeechConfig
.fromSubscription(apiKey, region);
config.setProfanity(ProfanityOption.Raw);
if (this.locale != null) {
config.setSpeechRecognitionLanguage(this.locale);
}
return config;
}
@Override
public void reset() {
close();
}
/**
* releases the resources associated with the recognizer.
*/
@Override
public void close() {
if (this.audioStream != null) {
this.audioStream.close();
this.audioStream = null;
}
if (this.recognizer != null) {
this.recognizer.close();
this.recognizer = null;
}
}
/**
* processes a frame of audio.
*
* @param speechContext the current speech context
* @param frame the audio frame to detect
*
* @throws Exception if there is an error performing active recognition.
*/
public void process(SpeechContext speechContext, ByteBuffer frame)
throws Exception {
if (speechContext.isActive() && !this.active) {
begin(speechContext);
} else if (!speechContext.isActive() && this.active) {
commit();
} else if (speechContext.isActive()) {
bufferFrame(frame);
}
}
void begin(SpeechContext speechContext) {
this.audioStream = AudioInputStream.createPushStream();
this.audioConfig = AudioConfig.fromStreamInput(this.audioStream);
this.recognizer = createRecognizer(speechContext);
recognizer.startContinuousRecognitionAsync();
this.active = true;
// send any existing frames into the stream
for (ByteBuffer frame : speechContext.getBuffer()) {
bufferFrame(frame);
}
}
SpeechRecognizer createRecognizer(SpeechContext context) {
// factored into a separate method for testing
SpeechRecognizer rec = new SpeechRecognizer(msConfig, audioConfig);
listen(rec, context);
return rec;
}
private void listen(SpeechRecognizer rec, SpeechContext context) {
RecognitionListener recognitionListener =
new RecognitionListener(context);
rec.recognizing.addEventListener(recognitionListener);
rec.recognized.addEventListener(recognitionListener);
CancellationListener cancellationListener =
new CancellationListener(context);
rec.canceled.addEventListener(cancellationListener);
}
void bufferFrame(ByteBuffer frame) {
if (frame != null) {
if (this.buffer.remaining() < frame.capacity()) {
flush();
}
this.buffer.put(frame);
}
}
void commit() throws Exception {
// send the end of audio
flush();
this.audioStream.close();
this.recognizer.stopContinuousRecognitionAsync().get();
this.recognizer.close();
this.audioConfig.close();
this.active = false;
}
private void flush() {
if (this.buffer.hasArray()) {
this.buffer.flip();
this.audioStream.write(this.buffer.array());
this.buffer.clear();
}
}
/**
* Listener for Speech SDK recognition events.
*/
static class RecognitionListener
implements EventHandler<SpeechRecognitionEventArgs> {
private final SpeechContext speechContext;
RecognitionListener(SpeechContext context) {
this.speechContext = context;
}
@Override
public void onEvent(
Object sender,
SpeechRecognitionEventArgs recognitionArgs) {
ResultReason reason = recognitionArgs.getResult().getReason();
String transcript = recognitionArgs.getResult().getText();
if (!transcript.equals("")) {
if (reason == ResultReason.RecognizedSpeech) {
dispatchResult(transcript, SpeechContext.Event.RECOGNIZE);
} else if (reason == ResultReason.RecognizingSpeech) {
dispatchResult(transcript,
SpeechContext.Event.PARTIAL_RECOGNIZE);
}
}
}
private void dispatchResult(String transcript,
SpeechContext.Event event) {
this.speechContext.setTranscript(transcript);
this.speechContext.setConfidence(1.0);
this.speechContext.dispatch(event);
}
}
/**
* Listener for Speech SDK cancellation events.
*/
static class CancellationListener
implements EventHandler<SpeechRecognitionCanceledEventArgs> {
private final SpeechContext speechContext;
CancellationListener(SpeechContext context) {
this.speechContext = context;
}
@Override
public void onEvent(
Object sender,
SpeechRecognitionCanceledEventArgs cancellationArgs) {
if (cancellationArgs.getReason()
== CancellationReason.Error) {
String message = String.format(
"%s (error code %s)",
cancellationArgs.getErrorDetails(),
cancellationArgs.getErrorCode().name());
this.speechContext.setError(new Exception(message));
this.speechContext.dispatch(SpeechContext.Event.ERROR);
}
}
}
}