/
audio.go
107 lines (92 loc) · 2.1 KB
/
audio.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
package main
import (
"github.com/oleiade/lane"
"github.com/gorilla/websocket"
"github.com/1lann/dissonance/audio"
"io"
"github.com/tmpim/juroku/dfpwm"
"log"
"github.com/1lann/dissonance/ffmpeg"
)
var (
audioInstances = map[string]*AudioInstance{}
)
const (
channels int = 1
frameRate int = 48000
bufferSize int = 6000
)
// AudioInstance is created for each connected client
type AudioInstance struct {
connection *websocket.Conn
queue *lane.Queue
audio audio.Stream
clientID string
skip bool
stop bool
trackPlaying bool
}
func (ai *AudioInstance) playTrack(audioFile io.Reader) {
audio, err := ffmpeg.NewFFMPEGStream(audioFile, false)
if err != nil {
log.Fatal("ffmpeg:", err)
return
}
ai.audio = audio
rd, wr := io.Pipe()
defer rd.Close()
go func() {
dfpwm.EncodeDFPWM(wr, ai.audio)
wr.Close()
}()
buf := make([]byte, bufferSize)
for {
n, err := rd.Read(buf[:bufferSize])
if err == io.EOF || err == io.ErrUnexpectedEOF || ai.stop || ai.skip {
if a, ok := audioFile.(io.ReadCloser); ok {
a.Close()
}
rd.Close()
return
}
//log.Printf("Read %d bytes from buffer", n)
ai.connection.WriteMessage(websocket.BinaryMessage, buf[:n])
//time.Sleep(time.Duration(n / 6) * time.Millisecond)
//log.Printf("Sleeping %d ms", n / 6)
}
}
func (ai *AudioInstance) processQueue() {
if ai.trackPlaying == false {
for {
ai.skip = false
track := ai.queue.Dequeue()
if ai.stop == true {
break
} else if track != nil {
ai.playTrack(track.(io.Reader))
}
}
}
}
func (ai *AudioInstance) Enqueue(track io.Reader) {
ai.queue.Enqueue(track)
}
func (ai *AudioInstance) Stop() {
ai.stop = true
delete(audioInstances, ai.clientID)
}
func (ai *AudioInstance) Skip() {
ai.skip = true
}
func CreateAudioInstance(connection *websocket.Conn, clientID string) {
ai := new (AudioInstance)
ai.stop = false
ai.skip = false
ai.trackPlaying = false
ai.connection = connection
audioInstances[clientID] = ai
ai.clientID = clientID
ai.queue = lane.NewQueue()
log.Printf("Begin processing queue for %s...", clientID)
ai.processQueue()
}