dsprb 1.0.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +182 -0
- data/CITATION.cff +30 -0
- data/LICENSE +15 -9
- data/README.md +395 -97
- data/lib/dsprb/autocorrelation.rb +2 -2
- data/lib/dsprb/biquad.rb +6 -5
- data/lib/dsprb/check.rb +43 -0
- data/lib/dsprb/curve.rb +3 -3
- data/lib/dsprb/dct.rb +34 -14
- data/lib/dsprb/decimator.rb +37 -18
- data/lib/dsprb/energy.rb +4 -4
- data/lib/dsprb/formants.rb +43 -46
- data/lib/dsprb/fourier.rb +91 -17
- data/lib/dsprb/framing.rb +2 -2
- data/lib/dsprb/lpc.rb +52 -30
- data/lib/dsprb/mel_filterbank.rb +5 -6
- data/lib/dsprb/mfcc.rb +13 -4
- data/lib/dsprb/polynomial.rb +123 -0
- data/lib/dsprb/prepared.rb +21 -0
- data/lib/dsprb/spectral_moments.rb +3 -1
- data/lib/dsprb/spectrum.rb +17 -10
- data/lib/dsprb/version.rb +1 -1
- data/lib/dsprb/wav.rb +1 -1
- data/lib/dsprb/waveform.rb +1 -4
- data/lib/dsprb/window.rb +18 -3
- data/lib/dsprb/yin.rb +135 -52
- data/lib/dsprb.rb +6 -1
- data/sig/dsprb.rbs +86 -3
- metadata +13 -8
data/README.md
CHANGED
|
@@ -1,58 +1,62 @@
|
|
|
1
|
-
# dsprb
|
|
1
|
+
# dsprb · 純 Ruby 語音訊號分析
|
|
2
2
|
|
|
3
|
-
Speech signal
|
|
4
|
-
|
|
3
|
+
Speech signal analysis in pure Ruby: WAV decoding, power spectra, MFCC, YIN pitch tracking,
|
|
4
|
+
formant frequencies and bandwidths by linear prediction, spectral moments, energy measures,
|
|
5
|
+
biquad filters and decimation. No dependencies, no native extensions, deterministic output.
|
|
5
6
|
|
|
6
|
-
|
|
7
|
-
|
|
7
|
+
用純 Ruby 做語音訊號分析:讀 WAV 檔、算功率頻譜跟 MFCC、用 YIN 追基頻、用線性預測求共振峰的頻率跟頻寬,
|
|
8
|
+
還有頻譜動差、能量、雙二階濾波器跟降取樣。沒有相依套件,不用編譯原生擴充,同樣的輸入一定得到同樣的結果。
|
|
8
9
|
|
|
9
|
-
|
|
10
|
+
**English** · [中文](#中文)
|
|
10
11
|
|
|
11
|
-
|
|
12
|
-
amplitude, in microphone response, in speaking rate, and in every sample value, while agreeing on
|
|
13
|
-
everything a listener perceives: the pitch contour, the resonances of the vocal tract, the noise
|
|
14
|
-
spectrum of the fricatives.
|
|
12
|
+
## English
|
|
15
13
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
14
|
+
Two recordings of the same syllable differ in amplitude, microphone, speaking rate and every sample
|
|
15
|
+
value, yet agree on what a listener hears: the pitch contour, the resonances of the vocal tract,
|
|
16
|
+
the noise spectrum of the fricatives. This library measures those quantities with the classical
|
|
17
|
+
algorithms of acoustic phonetics. [taiwancards](https://github.com/taiwancards/taiwancards) uses
|
|
18
|
+
it to score learners' pronunciation of Taiwanese Mandarin.
|
|
20
19
|
|
|
21
|
-
|
|
20
|
+
### Install
|
|
21
|
+
|
|
22
|
+
Ruby 3.4 or later.
|
|
22
23
|
|
|
23
24
|
```ruby
|
|
24
25
|
gem "dsprb"
|
|
25
26
|
```
|
|
26
27
|
|
|
27
|
-
|
|
28
|
+
```sh
|
|
29
|
+
gem install dsprb
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
The gem is `dsprb`; the module is `DSP`. An invalid size, rate or range raises `ArgumentError`
|
|
33
|
+
naming the argument and the value; an unknown window name raises `DSP::UnknownStrategyError`.
|
|
34
|
+
|
|
35
|
+
### Waveforms
|
|
28
36
|
|
|
29
|
-
`DSP::Wav` decodes 8, 16, 24 and 32 bit PCM
|
|
30
|
-
`WAVE_FORMAT_EXTENSIBLE`, and
|
|
31
|
-
a `DSP::Waveform`,
|
|
37
|
+
`DSP::Wav` decodes 8, 16, 24 and 32 bit PCM and 32 and 64 bit IEEE float, including
|
|
38
|
+
`WAVE_FORMAT_EXTENSIBLE`, and averages multi-channel streams to mono. Anything else raises
|
|
39
|
+
`DSP::FormatError`. Every analysis takes a `DSP::Waveform`, which carries the sample rate with the
|
|
40
|
+
samples.
|
|
32
41
|
|
|
33
42
|
```ruby
|
|
34
43
|
require "dsprb"
|
|
35
44
|
|
|
36
|
-
signal = DSP.read("utterance.wav")
|
|
45
|
+
signal = DSP.read("utterance.wav") # or DSP.decode(bytes)
|
|
37
46
|
|
|
38
47
|
signal.length # => 16000
|
|
39
48
|
signal.sample_rate # => 16000.0
|
|
40
49
|
signal.duration # => 1.0
|
|
41
50
|
signal.nyquist # => 8000.0
|
|
42
|
-
```
|
|
43
|
-
|
|
44
|
-
Signals synthesized in memory are ordinary arrays:
|
|
45
51
|
|
|
46
|
-
|
|
47
|
-
signal = DSP::Waveform.new(samples: samples, sample_rate: 16_000)
|
|
52
|
+
DSP::Waveform.new(samples: samples, sample_rate: 16_000) # from an array of numbers
|
|
48
53
|
```
|
|
49
54
|
|
|
50
|
-
|
|
55
|
+
### Pitch
|
|
51
56
|
|
|
52
57
|
`DSP::Yin` implements the YIN estimator: squared difference over lag, cumulative mean
|
|
53
|
-
normalization, absolute-threshold period selection
|
|
54
|
-
|
|
55
|
-
method affordable in Ruby.
|
|
58
|
+
normalization, absolute-threshold period selection and parabolic refinement. The signal is first
|
|
59
|
+
decimated to a working rate, which keeps the O(window × lag) search affordable in Ruby.
|
|
56
60
|
|
|
57
61
|
```ruby
|
|
58
62
|
track = DSP.pitch(signal)
|
|
@@ -60,67 +64,122 @@ track = DSP.pitch(signal)
|
|
|
60
64
|
track.length # => 120
|
|
61
65
|
track.hop_seconds # => 0.008
|
|
62
66
|
track.voiced_ratio # => 1.0
|
|
63
|
-
track.voiced_f0 # => [196.
|
|
67
|
+
track.voiced_f0 # => [196.04, ...]
|
|
68
|
+
track.times # frame start times, in seconds
|
|
69
|
+
track.confidence # 1 - d'(τ), the depth of the chosen dip, 0.0 when unvoiced
|
|
64
70
|
|
|
65
71
|
track.each_voiced { |frequency, time, confidence| ... }
|
|
66
72
|
```
|
|
67
73
|
|
|
68
|
-
Unvoiced frames report `0.0
|
|
69
|
-
|
|
74
|
+
Unvoiced frames report `0.0`, so `track.f0` is always a dense numeric sequence. Options of
|
|
75
|
+
`DSP.pitch` and `DSP::Yin.new`:
|
|
76
|
+
|
|
77
|
+
| Option | Default | Meaning |
|
|
78
|
+
| -------------------- | -------- | --------------------------------------------------------------- |
|
|
79
|
+
| `minimum_frequency:` | `70.0` | lowest f0 searched, Hz |
|
|
80
|
+
| `maximum_frequency:` | `500.0` | highest f0 searched, Hz |
|
|
81
|
+
| `hop_seconds:` | `0.008` | frame step |
|
|
82
|
+
| `threshold:` | `0.15` | the first dip below it is taken as the period |
|
|
83
|
+
| `voiced_threshold:` | `0.35` | a frame whose deepest dip stays above it is unvoiced |
|
|
84
|
+
| `working_rate:` | `5512.5` | integer decimation toward this rate before the search, Hz |
|
|
85
|
+
| `minimum_rms:` | `0.0` | frames quieter than this are reported unvoiced without a search |
|
|
70
86
|
|
|
71
|
-
|
|
87
|
+
Silence carries no pitch and is most of a short recording; a gate such as `minimum_rms: 0.01`
|
|
88
|
+
skips the search there.
|
|
72
89
|
|
|
73
|
-
|
|
74
|
-
|
|
90
|
+
### Cepstral features
|
|
91
|
+
|
|
92
|
+
`DSP::Mfcc` chains a power spectrum, a mel filterbank and a DCT-II.
|
|
75
93
|
|
|
76
94
|
```ruby
|
|
77
95
|
frames = DSP.mfcc(signal)
|
|
78
96
|
|
|
79
|
-
frames.length
|
|
80
|
-
frames.first.length
|
|
97
|
+
frames.length # => 98
|
|
98
|
+
frames.first.length # => 13
|
|
99
|
+
|
|
100
|
+
DSP.mfcc(signal, coefficients: 20, filters: 40, warp: 1.1)
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
`DSP.mfcc` takes `coefficients:` (13), `window_seconds:` (0.025), `hop_seconds:` (0.010) and
|
|
104
|
+
`size:`, the FFT size. The size defaults to the smallest power of two that holds a frame: 512 at
|
|
105
|
+
16 kHz, 1024 at 22050 Hz; a size shorter than the frame raises `ArgumentError`. Filterbank options
|
|
106
|
+
pass through: `filters:` (26), `low:` (50.0 Hz), `high:` (Nyquist) and `warp:` (1.0), the vocal
|
|
107
|
+
tract length factor that scales the band centers; above 1 the bank moves up, which suits shorter
|
|
108
|
+
vocal tracts. Frames are Hamming-windowed after a 0.97 preemphasis; `DSP::Mfcc#sequence` changes
|
|
109
|
+
either:
|
|
110
|
+
|
|
111
|
+
```ruby
|
|
112
|
+
mfcc = DSP::Mfcc.for(sample_rate: 16_000, coefficients: 20, filters: 40)
|
|
113
|
+
mfcc.sequence(signal, window: :hann, preemphasis: nil)
|
|
81
114
|
```
|
|
82
115
|
|
|
83
|
-
The
|
|
116
|
+
The stages work on their own, for example a log-mel spectrogram:
|
|
84
117
|
|
|
85
118
|
```ruby
|
|
86
|
-
spectrum = DSP::Spectrum.new(512)
|
|
119
|
+
spectrum = DSP::Spectrum.new(512) # FFT size, a power of two
|
|
87
120
|
filterbank = DSP::MelFilterbank.new(sample_rate: 16_000, size: 512, filters: 26, warp: 1.05)
|
|
121
|
+
window = DSP::Window.hamming(400) # also hann, blackman, rectangular
|
|
88
122
|
|
|
89
123
|
log_mel = signal.frames(window: 400, hop: 160).map do |frame|
|
|
90
|
-
filterbank.log_energies(spectrum.power(DSP::Window.apply(frame,
|
|
124
|
+
filterbank.log_energies(spectrum.power(DSP::Window.apply(frame, window)))
|
|
91
125
|
end
|
|
92
126
|
```
|
|
93
127
|
|
|
94
|
-
|
|
128
|
+
`Spectrum#power` returns `size / 2 + 1` bins. A frame shorter than the size is zero padded; samples
|
|
129
|
+
past the size are ignored. `#magnitude`, `#frequencies(sample_rate)` and
|
|
130
|
+
`#bin_of(frequency, sample_rate)` complete it.
|
|
131
|
+
|
|
132
|
+
### Formants
|
|
133
|
+
|
|
134
|
+
`DSP::Formants` Hamming-windows and pre-emphasizes a frame, fits an all-pole model to it by the
|
|
135
|
+
Levinson-Durbin recursion and reads the formants from the roots of the predictor polynomial, which
|
|
136
|
+
`DSP::Polynomial.roots` finds by the Aberth-Ehrlich iteration. A root r e^{iω} above the real axis
|
|
137
|
+
is a resonance at ω fs / 2π with bandwidth −ln(r) fs / π. Roots within 50 Hz of 0 or Nyquist and
|
|
138
|
+
roots wider than 1000 Hz are discarded, the rest are sorted by frequency. Two formants 300 Hz
|
|
139
|
+
apart, as F1 and F2 of [u], stay two formants.
|
|
95
140
|
|
|
96
|
-
|
|
97
|
-
envelope it implies. `DSP::Formants` picks the envelope maxima, refines them parabolically on the
|
|
98
|
-
log magnitude, and merges peaks that a single resonance split in two.
|
|
141
|
+
The whole waveform is one analysis frame: pass 20 to 30 ms of a vowel, not a recording.
|
|
99
142
|
|
|
100
143
|
```ruby
|
|
101
|
-
DSP.formants(vowel)
|
|
102
|
-
# => [752.8, 2335.8, 3695.6, 5416.1]
|
|
144
|
+
DSP.formants(vowel) # => [F1, F2, F3, F4] in Hz, fewer if fewer roots qualify
|
|
103
145
|
|
|
104
|
-
DSP::Formants.new.peaks(vowel).first
|
|
105
|
-
#
|
|
146
|
+
peak = DSP::Formants.new.peaks(vowel).first
|
|
147
|
+
peak.frequency # Hz
|
|
148
|
+
peak.bandwidth # Hz, below 1000
|
|
149
|
+
peak.amplitude # natural log of the all-pole envelope at that frequency
|
|
106
150
|
```
|
|
107
151
|
|
|
108
|
-
|
|
152
|
+
Options of `DSP.formants` and `DSP::Formants.new`: `maximum_frequency:` (5500.0 Hz), the analysis
|
|
153
|
+
ceiling; `count:` (4), the number of formants, which sets the model order to 2 × count + 2;
|
|
154
|
+
`edge_margin:` (50.0 Hz). The ceiling is reached by decimating by an integer factor, the largest
|
|
155
|
+
that keeps the rate at or above twice the ceiling: 22050 and 44100 Hz input are analysed at
|
|
156
|
+
11025 Hz, 48000 Hz at 12000 Hz, but 16000 Hz input is not decimated and is analysed up to 8000 Hz.
|
|
157
|
+
Lower the ceiling to 5000 Hz for adult male voices.
|
|
158
|
+
|
|
159
|
+
On the vowels of 1047 recorded syllables from three voices, the median difference from Praat's
|
|
160
|
+
Burg analysis is 7 Hz for F1 and 11 Hz for F2; the
|
|
161
|
+
[CHANGELOG](CHANGELOG.md#210--2026-12-06) breaks this down by vowel for one of the voices.
|
|
162
|
+
|
|
163
|
+
The predictor and the root finder are public:
|
|
109
164
|
|
|
110
165
|
```ruby
|
|
111
166
|
model = DSP::Lpc.solve(frame, order: 10)
|
|
112
167
|
|
|
113
|
-
model.order
|
|
114
|
-
model.
|
|
115
|
-
model.
|
|
168
|
+
model.order # => 10
|
|
169
|
+
model.coefficients # [1.0, a1, ..., a10]
|
|
170
|
+
model.error # residual energy of the prediction
|
|
171
|
+
model.envelope(points: 512) # 1 / |A(e^{iω})|² from 0 to Nyquist
|
|
172
|
+
|
|
173
|
+
DSP::Polynomial.roots([1.0, -3.0, 2.0]) # => the roots 2 and 1, as Complex
|
|
116
174
|
```
|
|
117
175
|
|
|
118
|
-
|
|
176
|
+
### Spectral moments
|
|
119
177
|
|
|
120
|
-
Centroid, spread, skewness and excess kurtosis of
|
|
121
|
-
|
|
178
|
+
Centroid, spread, skewness and excess kurtosis of a power spectrum over a band, the standard
|
|
179
|
+
descriptors of fricative noise. The band defaults to 500 Hz up to 200 Hz below Nyquist.
|
|
122
180
|
|
|
123
181
|
```ruby
|
|
182
|
+
power = DSP::Spectrum.new(1024).power(frame)
|
|
124
183
|
moments = DSP::SpectralMoments.of(power, sample_rate: 16_000, size: 1024, low: 500.0)
|
|
125
184
|
|
|
126
185
|
moments.centroid # => 4904.8
|
|
@@ -129,65 +188,304 @@ moments.skewness # => 0.742
|
|
|
129
188
|
moments.kurtosis # => -0.708
|
|
130
189
|
```
|
|
131
190
|
|
|
132
|
-
|
|
191
|
+
### Energy, filters, resampling
|
|
133
192
|
|
|
134
193
|
```ruby
|
|
135
|
-
DSP::Energy.frame_db(frame)
|
|
136
|
-
DSP::Energy.zero_crossing_rate(frame)
|
|
137
|
-
DSP::Energy.envelope_db(samples, window: 400, hop: 160)
|
|
194
|
+
DSP::Energy.frame_db(frame) # mean power, in decibels
|
|
195
|
+
DSP::Energy.zero_crossing_rate(frame) # crossings per sample interval
|
|
196
|
+
DSP::Energy.envelope_db(samples, window: 400, hop: 160) # sliding energy, one value per hop
|
|
197
|
+
|
|
198
|
+
DSP.highpass(signal, cutoff: 60.0) # removes rumble and DC offset
|
|
199
|
+
DSP.lowpass(signal, cutoff: 4000.0, sections: 2) # two Q = 0.707 biquads, -6 dB at cutoff
|
|
200
|
+
DSP::Biquad.lowpass(sample_rate: 16_000, cutoff: 1000.0, q: 2.0).apply(samples)
|
|
201
|
+
DSP.decimate(signal, 4) # windowed-sinc low-pass, every 4th sample
|
|
202
|
+
|
|
203
|
+
DSP::Framing.preemphasis(samples, coefficient: 0.97)
|
|
204
|
+
DSP::Curve.resample(contour, 16) # contours onto a common grid
|
|
205
|
+
DSP::Scales.hz_to_semitones(392.0, reference: 196.0) # => 12.0
|
|
206
|
+
DSP::Scales.hz_to_mel(1000.0) # => 999.99
|
|
207
|
+
```
|
|
138
208
|
|
|
139
|
-
|
|
140
|
-
DSP.lowpass(signal, cutoff: 4000.0, sections: 2) # cascaded Butterworth sections
|
|
141
|
-
DSP.decimate(signal, 4) # windowed-sinc anti-aliasing
|
|
209
|
+
### Limits
|
|
142
210
|
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
211
|
+
- Speed is that of Ruby. On Ruby 4.0 with YJIT and 22050 Hz input, `Formants#call` takes about
|
|
212
|
+
0.3 ms per 25 ms frame and `Yin#call` about 26 ms for 2 s of a vowel at 120 to 180 Hz, 40 ms for
|
|
213
|
+
2 s of noise.
|
|
214
|
+
- WAV is the only file format. Rates change only by integer decimation.
|
|
215
|
+
- FFT sizes are powers of two, at least 4.
|
|
216
|
+
- An f0 within about 0.5 % of `maximum_frequency` can come out unvoiced: parabolic refinement may
|
|
217
|
+
place it just above the maximum. Set the maximum a little above the highest f0 you expect.
|
|
146
218
|
|
|
147
|
-
|
|
219
|
+
### Used in taiwancards
|
|
148
220
|
|
|
149
221
|
[taiwancards](https://github.com/taiwancards/taiwancards) teaches Taiwanese Mandarin and scores
|
|
150
|
-
learner recordings against native templates
|
|
222
|
+
learner recordings against native templates with this library.
|
|
223
|
+
|
|
224
|
+
- **Conditioning.** The recording is decimated by an integer factor toward 22050 Hz. The energy
|
|
225
|
+
envelope and zero crossing rate find the speech; the energy envelopes of a copy low-passed at
|
|
226
|
+
800 Hz and a copy high-passed at 1200 Hz separate the onset of voicing from the release burst.
|
|
227
|
+
- **Tone.** Mandarin lexical tone is carried by the f0 contour. The track from `DSP.pitch` is
|
|
228
|
+
cleaned of octave errors, converted to semitones and resampled to 16 points with
|
|
229
|
+
`DSP::Curve.resample`, where the four tones become comparable shapes.
|
|
230
|
+
- **Timbre.** Thirteen MFCC per frame, with the warp set per speaker so that a child and an adult
|
|
231
|
+
saying the same vowel land close together.
|
|
232
|
+
- **Vowel quality.** F1 and F2 place a vowel on the vowel plane, where ㄧ, ㄩ and ㄨ differ.
|
|
233
|
+
- **Fricatives.** Spectral moments separate ㄕ from ㄙ by centroid and skewness.
|
|
234
|
+
|
|
235
|
+
The sequences differ in length because speaking rate differs, so they are aligned and averaged
|
|
236
|
+
with [dtwrb](https://github.com/taiwancards/dtwrb), the companion library for dynamic time warping
|
|
237
|
+
and barycenter averaging.
|
|
238
|
+
|
|
239
|
+
### Design
|
|
151
240
|
|
|
152
|
-
|
|
153
|
-
|
|
241
|
+
Every stage is an object that precomputes what it can and then freezes: `DSP::Fourier::Radix2`
|
|
242
|
+
its twiddle factors, `DSP::MelFilterbank` its bands, `DSP::Decimator` its kernel,
|
|
243
|
+
`DSP::Lpc::Envelope` its cosine grid, `DSP::Dct::Two` its basis. They hold no mutable state and
|
|
244
|
+
are safe to share across threads; build them once, outside the loop. `DSP::Window.hamming` and its
|
|
245
|
+
siblings, `DSP::Decimator.for`, `DSP::Dct::Two.for` and `DSP::Lpc::Envelope.for` return one shared
|
|
246
|
+
frozen instance per parameter set.
|
|
154
247
|
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
`DSP::
|
|
158
|
-
|
|
248
|
+
`DSP::Spectrum` uses `DSP::Fourier::Real` by default. Any object with `#power(frame)` can replace
|
|
249
|
+
it, or a complex transform with `#call(real, imaginary)` and `#size`, such as
|
|
250
|
+
`DSP::Fourier::Radix2`. `DSP::Mfcc#sequence` takes any window function that answers
|
|
251
|
+
`#call(length)`.
|
|
159
252
|
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
the same region of the feature space.
|
|
253
|
+
`DSP::Waveform`, `DSP::PitchTrack`, `DSP::SpectralMoments`, `DSP::Biquad`, `DSP::Lpc::Model` and
|
|
254
|
+
`DSP::Formants::Peak` are `Data` value objects: frozen, compared by value, copied with `#with`.
|
|
163
255
|
|
|
164
|
-
|
|
165
|
-
|
|
256
|
+
Developed and maintained in Taipei, Taiwan by Den Patin 丁丹旭 (<hi@dpat.in>), independent
|
|
257
|
+
researcher, linguist and software engineer.
|
|
166
258
|
|
|
167
|
-
|
|
168
|
-
mainly in centroid and skewness, not in duration or energy.
|
|
259
|
+
### License
|
|
169
260
|
|
|
170
|
-
|
|
171
|
-
averaged with [dtwrb](https://github.com/taiwancards/dtwrb), the companion library for dynamic time
|
|
172
|
-
warping and barycenter averaging.
|
|
261
|
+
MIT — see [LICENSE](LICENSE).
|
|
173
262
|
|
|
174
|
-
|
|
175
|
-
telemetry — uses the same spectral and predictive machinery.
|
|
263
|
+
## 中文
|
|
176
264
|
|
|
177
|
-
|
|
265
|
+
同一個音節錄兩次,音量、麥克風、說話速度跟每一個取樣值都不一樣,可是聽的人聽到的東西是一樣的:音高的走勢、
|
|
266
|
+
聲道的共振,還有擦音的噪音頻譜。這個函式庫用聲學語音學的經典演算法把這些量算出來。
|
|
267
|
+
[taiwancards](https://github.com/taiwancards/taiwancards) 用它幫學習者的臺灣華語發音打分數。
|
|
178
268
|
|
|
179
|
-
|
|
180
|
-
caches its twiddle factors, `DSP::MelFilterbank` its triangular bands, `DSP::Decimator` its kernel.
|
|
181
|
-
They hold no mutable state, share nothing globally, and are safe to reuse across threads. Build them
|
|
182
|
-
once, outside the loop.
|
|
269
|
+
### 安裝
|
|
183
270
|
|
|
184
|
-
|
|
185
|
-
function of an MFCC sequence, the filterbank of a `DSP::Mfcc`. A different FFT backend needs only
|
|
186
|
-
`#call(real, imaginary)` and `#size`.
|
|
271
|
+
需要 Ruby 3.4 以上。
|
|
187
272
|
|
|
188
|
-
|
|
189
|
-
|
|
273
|
+
```ruby
|
|
274
|
+
gem "dsprb"
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
```sh
|
|
278
|
+
gem install dsprb
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
套件叫 `dsprb`,模組叫 `DSP`。大小、取樣率或範圍不對的時候會丟出 `ArgumentError`,訊息裡會寫出是哪個
|
|
282
|
+
參數、收到什麼值;窗函數的名字打錯會丟出 `DSP::UnknownStrategyError`。
|
|
283
|
+
|
|
284
|
+
### 波形
|
|
285
|
+
|
|
286
|
+
`DSP::Wav` 可以讀 8、16、24、32 位元的 PCM 跟 32、64 位元的 IEEE 浮點數,`WAVE_FORMAT_EXTENSIBLE`
|
|
287
|
+
也可以;多聲道會平均成單聲道。其他格式會丟出 `DSP::FormatError`。所有分析都吃 `DSP::Waveform`,取樣率
|
|
288
|
+
跟取樣值放在同一個物件裡,不會配錯。
|
|
289
|
+
|
|
290
|
+
```ruby
|
|
291
|
+
require "dsprb"
|
|
292
|
+
|
|
293
|
+
signal = DSP.read("utterance.wav") # 或 DSP.decode(bytes)
|
|
294
|
+
|
|
295
|
+
signal.length # => 16000
|
|
296
|
+
signal.sample_rate # => 16000.0
|
|
297
|
+
signal.duration # => 1.0
|
|
298
|
+
signal.nyquist # => 8000.0
|
|
299
|
+
|
|
300
|
+
DSP::Waveform.new(samples: samples, sample_rate: 16_000) # 直接用數字陣列建立
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
### 基頻
|
|
304
|
+
|
|
305
|
+
`DSP::Yin` 實作 YIN:算每個延遲的平方差、做累積平均正規化、取第一個低過門檻的谷當週期,再用拋物線內插
|
|
306
|
+
微調。分析前會先把訊號降取樣到工作取樣率,O(窗長 × 延遲) 的搜尋在 Ruby 裡才跑得動。
|
|
307
|
+
|
|
308
|
+
```ruby
|
|
309
|
+
track = DSP.pitch(signal)
|
|
310
|
+
|
|
311
|
+
track.length # => 120
|
|
312
|
+
track.hop_seconds # => 0.008
|
|
313
|
+
track.voiced_ratio # => 1.0
|
|
314
|
+
track.voiced_f0 # => [196.04, ...]
|
|
315
|
+
track.times # 每個音框的起點,單位是秒
|
|
316
|
+
track.confidence # 1 - d'(τ),選到的谷有多深;無聲是 0.0
|
|
317
|
+
|
|
318
|
+
track.each_voiced { |frequency, time, confidence| ... }
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
無聲的音框回傳 `0.0`,不是 `nil`,所以 `track.f0` 一定是連續的數字陣列。`DSP.pitch` 跟 `DSP::Yin.new`
|
|
322
|
+
的參數:
|
|
323
|
+
|
|
324
|
+
- `minimum_frequency:`,預設 `70.0`:搜尋的最低基頻(Hz)。
|
|
325
|
+
- `maximum_frequency:`,預設 `500.0`:搜尋的最高基頻(Hz)。
|
|
326
|
+
- `hop_seconds:`,預設 `0.008`:音框間隔。
|
|
327
|
+
- `threshold:`,預設 `0.15`:第一個低過這個值的谷就當成週期。
|
|
328
|
+
- `voiced_threshold:`,預設 `0.35`:最深的谷還高過這個值,這個音框就算無聲。
|
|
329
|
+
- `working_rate:`,預設 `5512.5`:用整數倍降取樣,取最大的倍數,但取樣率不會低過這個值。
|
|
330
|
+
- `minimum_rms:`,預設 `0.0`:比這個還小聲的音框直接當無聲,不做搜尋。
|
|
331
|
+
|
|
332
|
+
靜音沒有音高,而且常常佔了短錄音的大半;設個門檻,像是 `minimum_rms: 0.01`,靜音的部分就不用搜尋。
|
|
333
|
+
|
|
334
|
+
### 倒頻譜特徵
|
|
335
|
+
|
|
336
|
+
`DSP::Mfcc` 把功率頻譜、梅爾濾波器組跟 DCT-II 串在一起。
|
|
337
|
+
|
|
338
|
+
```ruby
|
|
339
|
+
frames = DSP.mfcc(signal)
|
|
340
|
+
|
|
341
|
+
frames.length # => 98
|
|
342
|
+
frames.first.length # => 13
|
|
343
|
+
|
|
344
|
+
DSP.mfcc(signal, coefficients: 20, filters: 40, warp: 1.1)
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
`DSP.mfcc` 的參數有 `coefficients:`(13)、`window_seconds:`(0.025)、`hop_seconds:`(0.010)跟
|
|
348
|
+
FFT 大小 `size:`。`size:` 預設是裝得下一個音框的最小 2 的次方:16 kHz 是 512,22050 Hz 是 1024;給的
|
|
349
|
+
大小比音框短會丟出 `ArgumentError`。濾波器組的參數會直接傳下去:`filters:`(26)、`low:`(50.0 Hz)、
|
|
350
|
+
`high:`(奈奎斯特頻率)跟 `warp:`(1.0)。`warp:` 是聲道長度正規化的係數,會等比例移動每個頻帶的中心;
|
|
351
|
+
比 1 大的話整組往高頻移,適合聲道比較短的人。每個音框先做 0.97 的預強調,再乘 Hamming 窗;要換的話用
|
|
352
|
+
`DSP::Mfcc#sequence`:
|
|
353
|
+
|
|
354
|
+
```ruby
|
|
355
|
+
mfcc = DSP::Mfcc.for(sample_rate: 16_000, coefficients: 20, filters: 40)
|
|
356
|
+
mfcc.sequence(signal, window: :hann, preemphasis: nil)
|
|
357
|
+
```
|
|
358
|
+
|
|
359
|
+
每個步驟也可以單獨用,像是算對數梅爾頻譜圖:
|
|
360
|
+
|
|
361
|
+
```ruby
|
|
362
|
+
spectrum = DSP::Spectrum.new(512) # FFT 大小,要是 2 的次方
|
|
363
|
+
filterbank = DSP::MelFilterbank.new(sample_rate: 16_000, size: 512, filters: 26, warp: 1.05)
|
|
364
|
+
window = DSP::Window.hamming(400) # 另外還有 hann、blackman、rectangular
|
|
365
|
+
|
|
366
|
+
log_mel = signal.frames(window: 400, hop: 160).map do |frame|
|
|
367
|
+
filterbank.log_energies(spectrum.power(DSP::Window.apply(frame, window)))
|
|
368
|
+
end
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
`Spectrum#power` 回傳 `size / 2 + 1` 個頻率點。音框比 FFT 大小短的話後面補零,超過的部分直接忽略。
|
|
372
|
+
另外還有 `#magnitude`、`#frequencies(sample_rate)` 跟 `#bin_of(frequency, sample_rate)`。
|
|
373
|
+
|
|
374
|
+
### 共振峰
|
|
375
|
+
|
|
376
|
+
`DSP::Formants` 先把音框乘上 Hamming 窗、做預強調,用 Levinson-Durbin 遞迴求全極點模型,再從預測多項式的
|
|
377
|
+
根讀出共振峰;根是 `DSP::Polynomial.roots` 用 Aberth-Ehrlich 迭代法求的。實軸上方的根 r e^{iω} 就是
|
|
378
|
+
一個共振,頻率是 ω fs / 2π,頻寬是 −ln(r) fs / π。離 0 Hz 或奈奎斯特頻率不到 50 Hz 的根、頻寬超過
|
|
379
|
+
1000 Hz 的根都會丟掉,剩下的照頻率排好。像 [u] 的 F1 跟 F2 只差 300 Hz,也會分成兩個共振峰。
|
|
380
|
+
|
|
381
|
+
整段波形就是一個分析音框,所以要傳 20 到 30 ms 的母音進去,不要傳整段錄音。
|
|
382
|
+
|
|
383
|
+
```ruby
|
|
384
|
+
DSP.formants(vowel) # => [F1, F2, F3, F4],單位 Hz;符合條件的根不夠的話會比較少
|
|
385
|
+
|
|
386
|
+
peak = DSP::Formants.new.peaks(vowel).first
|
|
387
|
+
peak.frequency # Hz
|
|
388
|
+
peak.bandwidth # Hz,一定不到 1000
|
|
389
|
+
peak.amplitude # 全極點包絡在這個頻率的自然對數
|
|
390
|
+
```
|
|
391
|
+
|
|
392
|
+
`DSP.formants` 跟 `DSP::Formants.new` 的參數:`maximum_frequency:`(5500.0 Hz)是分析的上限;
|
|
393
|
+
`count:`(4)是要幾個共振峰,模型的階數是 2 × count + 2;`edge_margin:`(50.0 Hz)。上限是靠整數倍
|
|
394
|
+
降取樣做到的,取最大的倍數,但取樣率不會低過上限的兩倍:22050 跟 44100 Hz 的輸入會在 11025 Hz 分析,
|
|
395
|
+
48000 Hz 在 12000 Hz,可是 16000 Hz 的輸入不會降取樣,會分析到 8000 Hz。成年男性的聲音可以把上限調到
|
|
396
|
+
5000 Hz。
|
|
397
|
+
|
|
398
|
+
在三個發音人、1047 個錄音音節的母音上,跟 Praat 的 Burg 分析比,F1 的差距中位數是 7 Hz,F2 是 11 Hz;
|
|
399
|
+
其中一個發音人每個母音的數字列在 [CHANGELOG](CHANGELOG.md#210--2026-12-06) 的表裡。
|
|
400
|
+
|
|
401
|
+
預測器跟求根的函式也可以直接用:
|
|
402
|
+
|
|
403
|
+
```ruby
|
|
404
|
+
model = DSP::Lpc.solve(frame, order: 10)
|
|
405
|
+
|
|
406
|
+
model.order # => 10
|
|
407
|
+
model.coefficients # [1.0, a1, ..., a10]
|
|
408
|
+
model.error # 預測的殘差能量
|
|
409
|
+
model.envelope(points: 512) # 1 / |A(e^{iω})|²,從 0 到奈奎斯特頻率
|
|
410
|
+
|
|
411
|
+
DSP::Polynomial.roots([1.0, -3.0, 2.0]) # => 兩個根 2 跟 1,型別是 Complex
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
### 頻譜動差
|
|
415
|
+
|
|
416
|
+
在一段頻帶裡算功率頻譜的質心、展度、偏態跟超額峰態,是描述擦音噪音最常用的量。頻帶預設從 500 Hz 到
|
|
417
|
+
奈奎斯特頻率減 200 Hz。
|
|
418
|
+
|
|
419
|
+
```ruby
|
|
420
|
+
power = DSP::Spectrum.new(1024).power(frame)
|
|
421
|
+
moments = DSP::SpectralMoments.of(power, sample_rate: 16_000, size: 1024, low: 500.0)
|
|
422
|
+
|
|
423
|
+
moments.centroid # => 4904.8
|
|
424
|
+
moments.spread # => 1064.8
|
|
425
|
+
moments.skewness # => 0.742
|
|
426
|
+
moments.kurtosis # => -0.708
|
|
427
|
+
```
|
|
428
|
+
|
|
429
|
+
### 能量、濾波、重新取樣
|
|
430
|
+
|
|
431
|
+
```ruby
|
|
432
|
+
DSP::Energy.frame_db(frame) # 平均功率,單位 dB
|
|
433
|
+
DSP::Energy.zero_crossing_rate(frame) # 每個取樣間隔的過零次數
|
|
434
|
+
DSP::Energy.envelope_db(samples, window: 400, hop: 160) # 滑動能量,每個間隔一個值
|
|
435
|
+
|
|
436
|
+
DSP.highpass(signal, cutoff: 60.0) # 去掉低頻雜音跟直流偏移
|
|
437
|
+
DSP.lowpass(signal, cutoff: 4000.0, sections: 2) # 兩個 Q = 0.707 的雙二階,截止頻率 -6 dB
|
|
438
|
+
DSP::Biquad.lowpass(sample_rate: 16_000, cutoff: 1000.0, q: 2.0).apply(samples)
|
|
439
|
+
DSP.decimate(signal, 4) # 先用加窗 sinc 低通,再每 4 點取 1 點
|
|
440
|
+
|
|
441
|
+
DSP::Framing.preemphasis(samples, coefficient: 0.97)
|
|
442
|
+
DSP::Curve.resample(contour, 16) # 把曲線對到同一組格點
|
|
443
|
+
DSP::Scales.hz_to_semitones(392.0, reference: 196.0) # => 12.0
|
|
444
|
+
DSP::Scales.hz_to_mel(1000.0) # => 999.99
|
|
445
|
+
```
|
|
446
|
+
|
|
447
|
+
### 限制
|
|
448
|
+
|
|
449
|
+
- 速度就是 Ruby 的速度。在 Ruby 4.0 開 YJIT、輸入 22050 Hz 的情況下,`Formants#call` 一個 25 ms
|
|
450
|
+
的音框大約 0.3 ms;`Yin#call` 跑 2 秒 120 到 180 Hz 的母音大約 26 ms,2 秒的噪音大約 40 ms。
|
|
451
|
+
- 檔案格式只支援 WAV。取樣率只能用整數倍降取樣來改。
|
|
452
|
+
- FFT 大小要是 2 的次方,最小是 4。
|
|
453
|
+
- 基頻離 `maximum_frequency` 不到 0.5 % 左右的時候,拋物線內插可能把它推到上限外面,結果變成無聲。
|
|
454
|
+
上限請設得比預期的最高基頻再高一點。
|
|
455
|
+
|
|
456
|
+
### 在 taiwancards 裡怎麼用
|
|
457
|
+
|
|
458
|
+
[taiwancards](https://github.com/taiwancards/taiwancards) 是教臺灣華語的網站,用這個函式庫把學習者的
|
|
459
|
+
錄音跟母語者的範本比較、打分數。
|
|
460
|
+
|
|
461
|
+
- **前處理。** 錄音先用整數倍降取樣到接近 22050 Hz。能量包絡跟過零率找出說話的範圍;再把一份低通到
|
|
462
|
+
800 Hz、一份高通到 1200 Hz,比較兩份的能量包絡,分出聲帶開始振動的時間點跟除阻的爆破。
|
|
463
|
+
- **聲調。** 華語的字調就在基頻曲線上。`DSP.pitch` 的結果先修掉八度錯誤、換成半音,再用
|
|
464
|
+
`DSP::Curve.resample` 取樣成 16 個點,四個聲調就變成可以直接比較的形狀。
|
|
465
|
+
- **音色。** 每個音框 13 個 MFCC,`warp:` 依每個人設定,小孩跟大人唸同一個母音會落在差不多的位置。
|
|
466
|
+
- **母音。** F1 跟 F2 決定母音在母音圖上的位置,ㄧ、ㄩ、ㄨ 的差別就在這裡。
|
|
467
|
+
- **擦音。** 頻譜動差的質心跟偏態可以分出 ㄕ 跟 ㄙ。
|
|
468
|
+
|
|
469
|
+
說話速度不一樣,序列的長度也不一樣,所以再用姊妹函式庫 [dtwrb](https://github.com/taiwancards/dtwrb)
|
|
470
|
+
做動態時間扭曲跟重心平均。
|
|
471
|
+
|
|
472
|
+
### 設計
|
|
473
|
+
|
|
474
|
+
每個步驟都是一個物件,能先算的先算好,然後凍結:`DSP::Fourier::Radix2` 存旋轉因子,
|
|
475
|
+
`DSP::MelFilterbank` 存頻帶,`DSP::Decimator` 存濾波器係數,`DSP::Lpc::Envelope` 存餘弦表,
|
|
476
|
+
`DSP::Dct::Two` 存基底。這些物件沒有可變的狀態,可以在多個執行緒裡共用;建一次就好,不要放在迴圈裡建。
|
|
477
|
+
`DSP::Window.hamming` 這類窗函數、`DSP::Decimator.for`、`DSP::Dct::Two.for` 跟
|
|
478
|
+
`DSP::Lpc::Envelope.for` 同樣的參數只會建一個共用的凍結物件。
|
|
479
|
+
|
|
480
|
+
`DSP::Spectrum` 預設用 `DSP::Fourier::Real`。可以換成任何有 `#power(frame)` 的物件,或是有
|
|
481
|
+
`#call(real, imaginary)` 跟 `#size` 的複數轉換,像 `DSP::Fourier::Radix2`。`DSP::Mfcc#sequence`
|
|
482
|
+
的 `window:` 可以是任何有 `#call(length)` 的窗函數。
|
|
483
|
+
|
|
484
|
+
`DSP::Waveform`、`DSP::PitchTrack`、`DSP::SpectralMoments`、`DSP::Biquad`、`DSP::Lpc::Model` 跟
|
|
485
|
+
`DSP::Formants::Peak` 都是 `Data` 值物件:凍結、用值比較、用 `#with` 複製。
|
|
486
|
+
|
|
487
|
+
由 Den Patin 丁丹旭(<hi@dpat.in>)在臺灣臺北開發與維護。獨立研究者,做語言學跟軟體工程。
|
|
190
488
|
|
|
191
|
-
|
|
489
|
+
### 授權條款
|
|
192
490
|
|
|
193
|
-
|
|
491
|
+
MIT,詳見 [LICENSE](LICENSE)。
|
|
@@ -4,9 +4,9 @@ module DSP
|
|
|
4
4
|
module Autocorrelation
|
|
5
5
|
module_function
|
|
6
6
|
|
|
7
|
-
#
|
|
7
|
+
# r[k] = sum_i x[i] x[i + k], k = 0..order, without a denominator.
|
|
8
8
|
def call(frame, order)
|
|
9
|
-
|
|
9
|
+
Check.non_negative!(order, "order")
|
|
10
10
|
|
|
11
11
|
length = frame.length
|
|
12
12
|
|
data/lib/dsprb/biquad.rb
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
module DSP
|
|
4
|
-
Biquad = Data.define(:b0, :b1, :b2, :a1, :a2)
|
|
5
|
-
|
|
4
|
+
Biquad = Data.define(:b0, :b1, :b2, :a1, :a2)
|
|
5
|
+
|
|
6
|
+
class Biquad
|
|
7
|
+
# Maximally flat passband alignment.
|
|
6
8
|
BUTTERWORTH_Q = Math.sqrt(2.0) / 2.0
|
|
7
9
|
|
|
8
|
-
# Normalized cutoff bounds, keeping the design away from DC and Nyquist.
|
|
9
10
|
MINIMUM_NORMALIZED = 1e-4
|
|
10
11
|
MAXIMUM_NORMALIZED = 0.49
|
|
11
12
|
|
|
@@ -36,7 +37,7 @@ module DSP
|
|
|
36
37
|
|
|
37
38
|
private_class_method :design
|
|
38
39
|
|
|
39
|
-
# Direct form II transposed
|
|
40
|
+
# Direct form II transposed: two accumulators of state.
|
|
40
41
|
def call(samples)
|
|
41
42
|
first = 0.0
|
|
42
43
|
second = 0.0
|
|
@@ -57,7 +58,7 @@ module DSP
|
|
|
57
58
|
|
|
58
59
|
# Cascading n identical sections yields a filter of order 2n.
|
|
59
60
|
def apply(samples, sections: 1)
|
|
60
|
-
|
|
61
|
+
Check.positive!(sections, "sections")
|
|
61
62
|
|
|
62
63
|
sections.times.reduce(samples) { |signal, _| call(signal) }
|
|
63
64
|
end
|