-
Notifications
You must be signed in to change notification settings - Fork 37
/
chunk.go
40 lines (32 loc) · 959 Bytes
/
chunk.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
package audiosocket
import (
"io"
"time"
"github.com/pkg/errors"
)
// DefaultSlinChunkSize is the number of bytes which should be sent per slin
// AudioSocket message. Larger data will be chunked into this size for
// transmission of the AudioSocket.
const DefaultSlinChunkSize = 320 // 8000Hz * 20ms * 2 bytes
// SendSlinChunks takes signed linear data and sends it over an AudioSocket connection in chunks of the given size.
func SendSlinChunks(w io.Writer, chunkSize int, input []byte) error {
var chunks int
if chunkSize < 1 {
chunkSize = DefaultSlinChunkSize
}
t := time.NewTicker(20 * time.Millisecond)
defer t.Stop()
for i := 0; i < len(input); {
<-t.C
chunkLen := chunkSize
if i+chunkSize > len(input) {
chunkLen = len(input) - i
}
if _, err := w.Write(SlinMessage(input[i : i+chunkLen])); err != nil {
return errors.Wrap(err, "failed to write chunk to AudioSocket")
}
chunks++
i += chunkLen
}
return nil
}