-
Notifications
You must be signed in to change notification settings - Fork 0
/
triangle.go
72 lines (57 loc) · 1.39 KB
/
triangle.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
69
70
71
72
package triangle
import (
"math"
"time"
"github.com/heucuva/go-qwertysynth/internal/synth/wave"
"github.com/pkg/errors"
)
type triangle struct {
data []float32
sampleRate float64
}
func (w triangle) Data() []float32 {
return w.data
}
func (w triangle) SampleRate() float64 {
return w.sampleRate
}
var _ wave.Generator = Triangle
func Triangle(opts ...wave.GeneratorParam) (wave.Wave, error) {
s := settings{
amp: defaultAmp,
phase: defaultPhase,
frequency: defaultFrequency,
sampleRate: defaultSampleRate,
duration: defaultDuration,
}
for _, opt := range opts {
if err := opt(&s); err != nil {
return nil, err
}
}
if s.frequency == 0 {
return nil, errors.Wrap(wave.ErrInvalidParameterValue, "frequency")
}
if s.duration == 0 {
onePeriod := float64(time.Second) / s.frequency
s.duration = time.Duration(onePeriod)
}
length := int(math.Round(s.duration.Seconds() * s.sampleRate))
samplesPerPeriod := s.sampleRate / s.frequency
w := &triangle{
data: make([]float32, length),
sampleRate: s.sampleRate,
}
periodRadians := 2.0 * math.Pi
radConverter := periodRadians / samplesPerPeriod
a := float64(s.amp)
p := periodRadians / 2.0
theta := 1.5*p + float64(s.phase)
for i := range w.data {
mod := math.Mod(theta, p*2.0)
y := a - (2.0*a/p)*(p-math.Abs(mod-p))
w.data[i] = float32(y)
theta += radConverter
}
return w, nil
}