-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
75 lines (60 loc) · 1.4 KB
/
main.go
File metadata and controls
75 lines (60 loc) · 1.4 KB
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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/faiface/beep"
"github.com/faiface/beep/speaker"
)
func AudioPipe(audio []float64) beep.Streamer {
idx := 0
return beep.StreamerFunc(func(samples [][2]float64) (n int, ok bool) {
var i int
for i = range samples {
if i+idx >= len(audio) {
return i, false
}
samples[i][0], samples[i][1] = audio[i+idx], audio[i+idx]
}
idx += i
return len(samples), true
})
}
type AudioBuffer struct {
Buffer []float64 `json:"buf"`
SampleRate int `json:"sampleRate"`
BufferSize int `json:"bufferSize"`
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
var aud AudioBuffer
err := json.NewDecoder(r.Body).Decode(&aud)
if err != nil {
log.Panic(err)
}
go Play(aud)
})
http.ListenAndServe(":1926", nil)
}
func Play(audio AudioBuffer) {
err := speaker.Init(beep.SampleRate(audio.SampleRate), audio.BufferSize)
if err != nil {
log.Panic(err)
}
done := make(chan bool)
speaker.Play(beep.Seq(AudioPipe(audio.Buffer), beep.Callback(func() {
fmt.Println("Done!")
done <- true
})))
<-done
}
func Speaker(audio []float64) {
speaker.Init(48000, 8192)
done := make(chan bool)
speaker.Play(beep.Seq(AudioPipe(audio), beep.Callback(func() {
fmt.Println("Done!")
done <- true
})))
<-done
}