-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsampler.go
167 lines (149 loc) · 4.11 KB
/
sampler.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
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
package audio
import (
"encoding/json"
"errors"
"fmt"
"github.com/gordonklaus/portaudio"
"io/ioutil"
)
// ConfigurationEntry is an individual MIDI note number and sound file name.
type ConfigurationEntry struct {
NoteNum int
FileName string
}
// Configuration is a list of associated MIDI note numbers and sound file names.
type Configuration []ConfigurationEntry
func loadConfig(configFileName string) (Configuration, error) {
config := Configuration{}
data, err := ioutil.ReadFile(configFileName)
if err != nil {
s := fmt.Sprintf("Could not read config file: %v\nError: %v",
configFileName, err.Error())
return Configuration{}, errors.New(s)
}
if err := json.Unmarshal(data, &config); err != nil {
return Configuration{}, err
}
return config, nil
}
// Represents a ring buffer for interlaced audio data.
type RingBuffer struct {
Data []int16
Len int
Index int
NumChannels int
}
// Creates a new, (intended to be audio-interlaced) ring buffer.
func NewRingBuffer(length int, numChannels int) RingBuffer {
return RingBuffer{make([]int16, length*numChannels), length, 0, numChannels}
}
// Steps to the next index of the ring buffer, wrapping if necessary.
func (b *RingBuffer) Next() {
b.Index++
if b.Index == b.Len {
b.Index = 0
}
}
// Clobbers data while increasing the buffer capacity.
func (b *RingBuffer) IncreaseLen(length int) {
switch {
case len(b.Data) == 0:
b.Data = make([]int16, length*b.NumChannels)
case len(b.Data) < length:
b.Data = append(b.Data, make([]int16, (b.NumChannels*length)-len(b.Data))...)
}
b.Len = len(b.Data)
}
// A simple software sampler.
type Sampler struct {
clips map[int]*Clip
stream *portaudio.Stream
buffer RingBuffer
}
// Creates a new software sampler.
func NewSampler(numChannels int) (*Sampler, error) {
s := new(Sampler)
s.clips = make(map[int]*Clip)
s.buffer = NewRingBuffer(0, numChannels)
return s, nil
}
// Creates a new software sampler
// loaded with audio files specified in a JSON configuration file.
func NewLoadedSampler(configFileName string) (*Sampler, error) {
config, err := loadConfig(configFileName)
if err != nil {
return &Sampler{}, err
}
numChannels := 2
s, err := NewSampler(numChannels)
if err != nil {
return &Sampler{}, err
}
for _, entry := range config {
clip, err := NewClipFromWave(entry.FileName)
if err != nil {
return &Sampler{}, err
}
s.AddClip(clip, entry.NoteNum)
}
return s, nil
}
// Adds a new audio-clip to be played back by the sampler.
func (s *Sampler) AddClip(c *Clip, noteNum int) {
s.clips[noteNum] = c
s.buffer.IncreaseLen(c.LenPerChannel())
}
func (s *Sampler) Run() error {
return s.RunAtRate(44100)
}
// Runs the sampler, commencing output to an audio device.
func (s *Sampler) RunAtRate(sampleRate int) error {
if err := portaudio.Initialize(); err != nil {
return err
}
var err error
s.stream, err = portaudio.OpenDefaultStream(0, 2, float64(sampleRate), 0, s.processAudio)
if err != nil {
return err
}
return s.stream.Start()
}
// Stops (pauses) an audio sampler.
func (s *Sampler) Stop() error {
return s.stream.Stop()
}
// Closes the sampler's audio stream.
func (s *Sampler) Close() error {
return s.stream.Close()
}
// Plays the specified sample at a specified volume.
func (s *Sampler) Play(noteNum int, volume float32) {
clip, ok := s.clips[noteNum]
if !ok {
return
}
i := s.buffer.Index
for j, _ := range clip.Samples[0] {
for chanNum := 0; chanNum < len(clip.Samples); chanNum++ {
sample := clip.Samples[chanNum][j]
s.buffer.Data[i] += int16((float32(sample) * volume))
i++
if i == s.buffer.Len {
i = 0
}
}
}
}
// Audio processing function needed by the audio device.
// This method should be private, but needs to be exported for use by
// the underlying audio device.
func (s *Sampler) processAudio(_, out []int16) {
// Read from the input buffer pointer or write to the output buffer pointer.
// if interlaced do stuff if not interlaced do other stuff.
for i := range out { // Iterate over the empty slice, populate with values.
index := s.buffer.Index
out[i] = s.buffer.Data[index]
s.buffer.Data[index] = 0
s.buffer.Next()
}
}