TenVadRemoveSilence.java
2.6 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
// Copyright 2025 Xiaomi Corporation
// This file shows how to use a ten-vad model to remove silences from
// a wave file.
import com.k2fsa.sherpa.onnx.*;
import java.util.ArrayList;
import java.util.Arrays;
public class TenVadRemoveSilence {
public static void main(String[] args) {
// please download ./ten-vad.onnx from
// https://github.com/k2-fsa/sherpa-onnx/releases/tag/asr-models
String model = "./ten-vad.onnx";
TenVadModelConfig tenVad =
TenVadModelConfig.builder()
.setModel(model)
.setThreshold(0.5f)
.setMinSilenceDuration(0.25f)
.setMinSpeechDuration(0.5f)
.setWindowSize(256)
.setMaxSpeechDuration(5.0f)
.build();
VadModelConfig config =
VadModelConfig.builder()
.setTenVadModelConfig(tenVad)
.setSampleRate(16000)
.setNumThreads(1)
.setDebug(true)
.setProvider("cpu")
.build();
Vad vad = new Vad(config);
// You can download the test file from
// https://github.com/k2-fsa/sherpa-onnx/releases/tag/asr-models
String testWaveFilename = "./lei-jun-test.wav";
WaveReader reader = new WaveReader(testWaveFilename);
int numSamples = reader.getSamples().length;
int windowSize = tenVad.getWindowSize();
int numIter = numSamples / windowSize;
ArrayList<float[]> segments = new ArrayList<float[]>();
for (int i = 0; i != numIter; ++i) {
int start = i * windowSize;
int end = start + windowSize;
float[] samples = Arrays.copyOfRange(reader.getSamples(), start, end);
vad.acceptWaveform(samples);
if (vad.isSpeechDetected()) {
while (!vad.empty()) {
// if you want to get the starting time of this segment, you can use
/* float startTime = vad.front().getStart() / 16000.0f; */
segments.add(vad.front().getSamples());
vad.pop();
}
}
}
vad.flush();
while (!vad.empty()) {
// if you want to get the starting time of this segment, you can use
/* float startTime = vad.front().getStart() / 16000.0f; */
segments.add(vad.front().getSamples());
vad.pop();
}
// get total number of samples
int n = 0;
for (float[] s : segments) {
n += s.length;
}
float[] allSamples = new float[n];
int i = 0;
for (float[] s : segments) {
System.arraycopy(s, 0, allSamples, i, s.length);
i += s.length;
}
String outFilename = "lei-jun-test-no-silence.wav";
WaveWriter.write(outFilename, allSamples, 16000);
System.out.printf("Saved to %s\n", outFilename);
vad.release();
}
}