Passed
Pull Request — master (#5)
by
unknown
01:35
created

bot.*Connection.Stop   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
package bot
2
3
import (
4
	"bufio"
5
	"encoding/binary"
6
	"errors"
7
	"fmt"
8
	"io"
9
10
	"github.com/FlameInTheDark/gopus"
11
)
12
13
const (
14
	// CHANNELS count of audio channels
15
	CHANNELS int = 2
16
	// FRAME_RATE ...
17
	FRAME_RATE int = 48000
0 ignored issues
show
introduced by
don't use ALL_CAPS in Go names; use CamelCase
Loading history...
18
	// FRAME_SIZE ...
19
	FRAME_SIZE int = 960
0 ignored issues
show
introduced by
don't use ALL_CAPS in Go names; use CamelCase
Loading history...
20
	// MAX_BYTES max bytes per sample
21
	MAX_BYTES int = (FRAME_SIZE * 2) * 2
0 ignored issues
show
introduced by
don't use ALL_CAPS in Go names; use CamelCase
Loading history...
22
)
23
24
func (connection *Connection) EncodeOpusAndSend(reader io.Reader) error {
0 ignored issues
show
introduced by
exported method Connection.EncodeOpusAndSend should have comment or be unexported
Loading history...
25
	if connection.playing {
26
		return errors.New("song already playing")
27
	}
28
29
	connection.playing = true
30
	_ = connection.voiceConnection.Speaking(true)
31
	defer func() { _ = connection.voiceConnection.Speaking(false) }()
32
33
	breader := bufio.NewReaderSize(reader, 16384)
34
	buffer := make([]int16, FRAME_SIZE*CHANNELS)
35
	encoder, err := gopus.NewEncoder(FRAME_RATE, CHANNELS, gopus.Audio)
36
	if err != nil {
37
		fmt.Println("Can's create a gopus encoder", err)
38
		return err
39
	}
40
41
	voice := connection.voiceConnection
42
loop:
43
	for {
44
		select {
45
		case _ = <-connection.quitChan:
46
			break loop
47
		default:
48
			err = binary.Read(breader, binary.LittleEndian, &buffer)
49
			if err == io.EOF || err == io.ErrUnexpectedEOF {
50
				return nil
51
			} else if err != nil {
52
				return err
53
			}
54
			opus, err := encoder.Encode(buffer, FRAME_SIZE, MAX_BYTES)
55
			if err != nil {
56
				fmt.Println("Gopus encoding error,", err)
57
				return err
58
			}
59
			if !voice.Ready || voice.OpusSend == nil {
60
				fmt.Printf("Discordgo not ready for opus packets. %+v : %+v", voice.Ready, voice.OpusSend)
61
				return err
62
			}
63
			voice.OpusSend <- opus
64
		}
65
	}
66
67
	return nil
68
}
69
70
// Stop stops playback
71
func (connection *Connection) Stop() {
72
	connection.playing = false
73
	connection.quitChan <- struct{}{}
74
}
75