Make sure the mpd fifo doesnt block and don't send silence over the udp connection.

nostruct
Stein Ivar Berghei 2022-11-28 10:52:23 +01:00
parent 7f288e541d
commit 13cfa0afb6
2 changed files with 26 additions and 31 deletions

29
mpd.go
View File

@ -3,11 +3,11 @@ package main
import (
"bytes"
"context"
"io"
"log"
"os"
"os/exec"
"strconv"
"syscall"
"text/template"
"time"
@ -17,7 +17,7 @@ import (
)
type MPD struct {
file *os.File
file int
f beep.Format
}
@ -121,8 +121,9 @@ func init() {
func NewMPD() (*MPD, error) {
out := new(MPD)
f, err := os.Open(config.GetString("mpd.fifo"))
f, err := syscall.Open(config.GetString("mpd.fifo"), syscall.O_CREAT|syscall.O_RDONLY|syscall.O_CLOEXEC|syscall.O_NONBLOCK, 0644)
log.Println(f, err)
//f, err := os.Open(config.GetString("mpd.fifo"))
if err != nil {
return nil, err
}
@ -145,29 +146,15 @@ func (m *MPD) Err() error {
func (m *MPD) Stream(samples [][2]float64) (n int, ok bool) {
tmp := make([]byte, m.f.NumChannels+2)
status, err := app.mpd.Status()
if err != nil {
return 0, false
}
for i := range samples {
if status["state"] != "play" {
samples[i] = [2]float64{}
ok = true
continue
}
dn, err := m.file.Read(tmp)
dn, err := syscall.Read(m.file, tmp)
if dn == len(tmp) {
samples[i], _ = m.f.DecodeSigned(tmp)
ok = true
}
if err == io.EOF {
ok = false
break
}
if err != nil {
log.Println(err)
ok = false
samples[i] = [2]float64{}
ok = true
break
}
}

View File

@ -5,6 +5,7 @@ import (
"encoding/binary"
"log"
"sync"
"time"
"github.com/bwmarrin/discordgo"
"github.com/faiface/beep"
@ -12,8 +13,6 @@ import (
"layeh.com/gopus"
)
const bufferSize = 1000
var (
mu sync.Mutex
mixer beep.Mixer
@ -90,14 +89,6 @@ func Clear() {
mu.Unlock()
}
func Pause(p bool) {
pause = p
}
func IsPaused() bool {
return pause
}
func update() {
mu.Lock()
mixer.Stream(samples)
@ -120,7 +111,13 @@ func update() {
}
}
if Silence(buf) {
time.Sleep(100 * time.Millisecond)
return
}
binary.Read(bytes.NewReader(buf), binary.LittleEndian, &pcm)
opus, err := encoder.Encode(pcm, frameSize, maxBytes)
if err != nil {
log.Println(err)
@ -130,5 +127,16 @@ func update() {
if !voice.Ready || voice.OpusSend == nil {
return
}
voice.OpusSend <- opus
}
func Silence(in []byte) bool {
for _, v := range in {
if v != 0 {
return false
}
}
return true
}