-
Notifications
You must be signed in to change notification settings - Fork 7
/
filters.go
68 lines (53 loc) · 1.5 KB
/
filters.go
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
package dsp
import (
"github.com/mattetti/audio"
"github.com/mattetti/audio/transforms/filters"
)
// fakedFreq returns faked cutoff frequency and sample rate if the given
// sample rate is less than 0.
// it is a workaround for https://github.com/eripe970/go-dsp-utils/issues/4
func fakedFreq(cutOffFreq, sampleRate float64) (float64, int) {
sr := int(sampleRate)
m := 1.0
for sr == 0 {
m = m * 1000
cutOffFreq = cutOffFreq * 1000
sr = int(sampleRate * m)
}
return cutOffFreq, sr
}
func (s *Signal) LowPassFilter(cutOffFreq float64) (*Signal, error) {
cutOffFreq, sampleRate := fakedFreq(cutOffFreq, s.SampleRate)
buffer := audio.NewPCMFloatBuffer(s.Signal, &audio.Format{SampleRate: sampleRate})
err := filters.LowPass(buffer, cutOffFreq)
if err != nil {
return nil, err
}
return &Signal{
SampleRate: s.SampleRate,
Signal: buffer.Floats,
}, nil
}
func (s *Signal) HighPassFilter(cutOffFreq float64) (*Signal, error) {
cutOffFreq, sampleRate := fakedFreq(cutOffFreq, s.SampleRate)
buffer := audio.NewPCMFloatBuffer(s.Signal, &audio.Format{SampleRate: sampleRate})
err := filters.HighPass(buffer, cutOffFreq)
if err != nil {
return nil, err
}
return &Signal{
SampleRate: s.SampleRate,
Signal: buffer.Floats,
}, nil
}
func (s *Signal) BandPassFilter(lower, upper float64) (*Signal, error) {
signal1, err := s.LowPassFilter(upper)
if err != nil {
return nil, err
}
signal2, err := signal1.HighPassFilter(lower)
if err != nil {
return nil, err
}
return signal2, nil
}