Compare commits

..

No commits in common. "ddf7ea2f15c22ed6f82be2db919a1412ad7f74e5" and "b770f341d04d031dcc8f190cbec496ec5d469d97" have entirely different histories.

2 changed files with 32 additions and 16 deletions

2
mpd.go
View File

@ -24,7 +24,7 @@ type MPD struct {
func init() {
log.Println("mpd.go loading..")
f, err := os.Create(config.GetString("mpd.config"))
f, err := os.OpenFile(config.GetString("mpd.config"), os.O_RDWR|os.O_CREATE, 0755)
if err != nil {
log.Fatal(err)
}

View File

@ -1,6 +1,8 @@
package discordspeaker
import (
"bytes"
"encoding/binary"
"log"
"sync"
"time"
@ -8,7 +10,7 @@ import (
"github.com/bwmarrin/discordgo"
"github.com/faiface/beep"
"github.com/pkg/errors"
"gopkg.in/hraban/opus.v2"
"layeh.com/gopus"
)
var (
@ -16,13 +18,15 @@ var (
mixer beep.Mixer
samples [][2]float64
done chan struct{}
encoder *opus.Encoder
encoder *gopus.Encoder
voice *discordgo.VoiceConnection
frameSize int = 960
channels int = 2
sampleRate int = 48000
maxBytes int = (frameSize * 2) * 2
pcm []int16
buf []byte
pause bool
)
func Init(dgv *discordgo.VoiceConnection) error {
@ -31,15 +35,17 @@ func Init(dgv *discordgo.VoiceConnection) error {
mu.Lock()
defer mu.Unlock()
Close()
mixer = beep.Mixer{}
buf = make([]byte, maxBytes)
pcm = make([]int16, frameSize*channels)
samples = make([][2]float64, frameSize)
pause = true
voice = dgv
encoder, err = opus.NewEncoder(sampleRate, channels, opus.AppVoIP)
encoder.SetBitrateToMax()
encoder, err = gopus.NewEncoder(sampleRate, channels, gopus.Audio)
if err != nil {
return errors.Wrap(err, "failed to initialize speaker")
@ -87,24 +93,34 @@ func update() {
mu.Lock()
mixer.Stream(samples)
mu.Unlock()
var f32 []float32
for _, sample := range samples {
for _, val := range sample {
f32 = append(f32, float32(val))
for i := range samples {
for c := range samples[i] {
val := samples[i][c]
if val < -1 {
val = -1
}
if val > +1 {
val = +1
}
valInt16 := int16(val * (1<<15 - 1))
low := byte(valInt16)
high := byte(valInt16 >> 8)
buf[i*4+c*2+0] = low
buf[i*4+c*2+1] = high
}
}
}
if Silence(f32) {
if Silence(buf) {
time.Sleep(100 * time.Millisecond)
return
}
n, err := encoder.EncodeFloat32(f32, buf)
binary.Read(bytes.NewReader(buf), binary.LittleEndian, &pcm)
opus, err := encoder.Encode(pcm, frameSize, maxBytes)
if err != nil {
log.Println(err)
time.Sleep(100 * time.Millisecond)
return
}
@ -112,10 +128,10 @@ func update() {
return
}
voice.OpusSend <- buf[:n]
voice.OpusSend <- opus
}
func Silence(in []float32) bool {
func Silence(in []byte) bool {
for _, v := range in {
if v != 0 {
return false