Index.ets
11.1 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
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import { LengthUnit } from '@kit.ArkUI';
import worker, { MessageEvents } from '@ohos.worker';
import { BusinessError } from '@kit.BasicServicesKit';
import { picker } from '@kit.CoreFileKit';
import { Permissions } from '@kit.AbilityKit';
import { allAllowed, requestPermissions } from './Permission';
import { audio } from '@kit.AudioKit';
@Entry
@Component
struct Index {
@State title: string = 'Next-gen Kaldi: VAD + ASR';
@State currentIndex: number = 0;
@State resultForFile: string = '';
@State progressForFile: number = 0;
@State selectFileBtnEnabled: boolean = false;
@State lang: string = 'English';
@State resultForMic: string = '';
@State micStarted: boolean = false;
@State message: string = 'Start recording';
@State micInitDone: boolean = false;
private controller: TabsController = new TabsController();
private workerInstance?: worker.ThreadWorker
private readonly scriptURL: string = 'entry/ets/workers/NonStreamingAsrWithVadWorker.ets'
private mic?: audio.AudioCapturer;
private sampleList: Float32Array[] = []
flatten(samples: Float32Array[]): Float32Array {
let n = 0;
for (let i = 0; i < samples.length; ++i) {
n += samples[i].length;
}
const ans: Float32Array = new Float32Array(n);
let offset: number = 0;
for (let i = 0; i < samples.length; ++i) {
ans.set(samples[i], offset);
offset += samples[i].length;
}
return ans;
}
async initMic() {
const permissions: Permissions[] = ["ohos.permission.MICROPHONE"];
let allowed: boolean = await allAllowed(permissions);
if (!allowed) {
console.log("request to access the microphone");
const status: boolean = await requestPermissions(permissions);
if (!status) {
console.error('access to microphone is denied')
this.resultForMic = "Failed to get microphone permission. Please retry";
return;
}
allowed = await allAllowed(permissions);
if (!allowed) {
console.error('failed to get microphone permission');
this.resultForMic = "Failed to get microphone permission. Please retry";
return;
}
} else {
console.log("allowed to access microphone");
}
const audioStreamInfo: audio.AudioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_16000,
channels: audio.AudioChannel.CHANNEL_1,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW,
};
const audioCapturerInfo: audio.AudioCapturerInfo = {
source: audio.SourceType.SOURCE_TYPE_MIC, capturerFlags: 0
};
const audioCapturerOptions: audio.AudioCapturerOptions = {
streamInfo: audioStreamInfo, capturerInfo: audioCapturerInfo
};
audio.createAudioCapturer(audioCapturerOptions, (err, data) => {
if (err) {
console.error(`error code is ${err.code}, error message is ${err.message}`);
this.resultForMic = 'Failed to init microphone';
} else {
console.info(`init mic successfully`);
this.mic = data;
this.mic.on('readData', this.micCallback);
if (this.workerInstance) {
this.workerInstance.postMessage({ msgType: 'init-vad-mic', context: getContext() });
}
}
});
}
async aboutToAppear() {
this.workerInstance = new worker.ThreadWorker(this.scriptURL, {
name: 'NonStreaming ASR worker'
});
this.workerInstance.onmessage = (e: MessageEvents) => {
const msgType = e.data['msgType'] as string;
console.log(`received msg from worker: ${msgType}`);
if (msgType == 'init-vad-mic-done') {
this.micInitDone = true;
}
if (msgType == 'init-non-streaming-asr-done') {
this.selectFileBtnEnabled = true;
this.resultForFile = `Initializing done.\n\nPlease select a wave file of 16kHz in language ${this.lang}`;
}
if (msgType == 'non-streaming-asr-vad-decode-done') {
this.resultForFile = e.data['text'] as string + '\n';
}
if (msgType == 'non-streaming-asr-vad-decode-partial') {
if (this.resultForFile == '') {
this.resultForFile = e.data['text'] as string;
} else {
this.resultForFile += '\n\n' + e.data['text'] as string;
}
}
if (msgType == 'non-streaming-asr-vad-decode-error') {
this.resultForFile = e.data['text'] as string;
}
if (msgType == 'non-streaming-asr-vad-decode-progress') {
this.progressForFile = e.data['progress'] as number;
this.selectFileBtnEnabled = this.progressForFile >= 100;
}
if (msgType == 'non-streaming-asr-vad-mic-partial') {
if (this.resultForMic == '') {
this.resultForMic = e.data['text'] as string;
} else {
this.resultForMic += '\n\n' + e.data['text'] as string;
}
}
if (msgType == 'non-streaming-asr-vad-mic-error') {
this.resultForMic = e.data['text'] as string;
}
}
const context = getContext();
this.resultForFile = 'Initializing models';
this.workerInstance.postMessage({ msgType: 'init-vad', context });
this.workerInstance.postMessage({ msgType: 'init-non-streaming-asr', context });
await this.initMic();
}
@Builder
TabBuilder(title: string, targetIndex: number, selectedImg: Resource, normalImg: Resource) {
Column() {
Image(this.currentIndex == targetIndex ? selectedImg : normalImg).size({ width: 25, height: 25 })
Text(title).fontColor(this.currentIndex == targetIndex ? '#28bff1' : '#8a8a8a')
}.width('100%').height(50).justifyContent(FlexAlign.Center).onClick(() => {
this.currentIndex = targetIndex;
this.controller.changeIndex(this.currentIndex);
})
}
build() {
Column() {
Tabs({ barPosition: BarPosition.End, controller: this.controller }) {
TabContent() {
Column({ space: 10 }) {
Text(this.title).fontSize(20).fontWeight(FontWeight.Bold);
Button('Select .wav file (16kHz) ')
.enabled(this.selectFileBtnEnabled)
.fontSize(13)
.width(296)
.height(60)
.onClick(() => {
this.resultForFile = '';
this.progressForFile = 0;
const documentSelectOptions = new picker.DocumentSelectOptions();
documentSelectOptions.maxSelectNumber = 1;
documentSelectOptions.fileSuffixFilters = ['.wav'];
const documentViewPicker = new picker.DocumentViewPicker();
documentViewPicker.select(documentSelectOptions).then((result: Array<string>) => {
console.log(`Result: ${result}`);
if (!result[0]) {
this.resultForFile = 'Please select a file to decode';
this.selectFileBtnEnabled = true;
return;
}
if (this.workerInstance) {
this.workerInstance.postMessage({
msgType: 'non-streaming-asr-vad-decode', filename: result[0],
});
} else {
console.log(`this worker instance is undefined ${this.workerInstance}`);
}
}).catch((err: BusinessError) => {
console.error(`Failed to select file, code is ${err.code}, message is ${err.message}`);
})
})
Text(`Supported languages: ${this.lang}`)
if (this.progressForFile > 0) {
Row() {
Progress({ value: 0, total: 100, type: ProgressType.Capsule })
.width('80%')
.height(20)
.value(this.progressForFile);
Text(`${this.progressForFile.toFixed(2)}%`).width('15%')
}.width('100%').justifyContent(FlexAlign.Center)
}
TextArea({ text: this.resultForFile })
.width('100%')
.lineSpacing({ value: 10, unit: LengthUnit.VP })
.height('100%');
}.alignItems(HorizontalAlign.Center).justifyContent(FlexAlign.Start)
}.tabBar(this.TabBuilder('From file', 0, $r('app.media.icon_doc'), $r('app.media.icon_doc_default')))
TabContent() {
Column({ space: 10 }) {
Text(this.title).fontSize(20).fontWeight(FontWeight.Bold);
Button(this.message).enabled(this.micInitDone).onClick(() => {
console.log('clicked mic button');
this.resultForMic = '';
if (this.mic) {
if (this.micStarted) {
this.mic.stop();
this.message = "Start recording";
this.micStarted = false;
console.log('mic stopped');
const samples = this.flatten(this.sampleList);
let s = 0;
for (let i = 0; i < samples.length; ++i) {
s += samples[i];
}
console.log(`samples ${samples.length}, sum: ${s}`);
if (this.workerInstance) {
console.log('decode mic');
this.workerInstance.postMessage({
msgType: 'non-streaming-asr-vad-mic', samples,
});
} else {
console.log(`this worker instance is undefined ${this.workerInstance}`);
}
} else {
this.sampleList = [];
this.mic.start();
this.message = "Stop recording";
this.micStarted = true;
console.log('mic started');
}
}
});
Text(`Supported languages: ${this.lang}`)
TextArea({ text: this.resultForMic })
.width('100%')
.lineSpacing({ value: 10, unit: LengthUnit.VP })
.width('100%')
.height('100%');
}.alignItems(HorizontalAlign.Center).justifyContent(FlexAlign.Start)
}
.tabBar(this.TabBuilder('From mic', 1, $r('app.media.ic_public_input_voice'),
$r('app.media.ic_public_input_voice_default')))
TabContent() {
Column({ space: 10 }) {
Text(this.title).fontSize(20).fontWeight(FontWeight.Bold);
TextArea({
text: `
Everyting is open-sourced.
It runs locally, without accessing the network
See also https://github.com/k2-fsa/sherpa-onnx
新一代 Kaldi QQ 和微信交流群: 请看
https://k2-fsa.github.io/sherpa/social-groups.html
微信公众号: 新一代 Kaldi
`
}).width('100%').height('100%').focusable(false)
}.justifyContent(FlexAlign.Start)
}.tabBar(this.TabBuilder('Help', 2, $r('app.media.info_circle'), $r('app.media.info_circle_default')))
}.scrollable(false)
}.width('100%').justifyContent(FlexAlign.Start)
}
private micCallback = (buffer: ArrayBuffer) => {
const view: Int16Array = new Int16Array(buffer);
const samplesFloat: Float32Array = new Float32Array(view.length);
for (let i = 0; i < view.length; ++i) {
samplesFloat[i] = view[i] / 32768.0;
}
this.sampleList.push(samplesFloat);
}
}