在仍在学习 Go 的过程中,我正在尝试正确读取 Opus 文件并将其发送到Discord的语音通道(仅支持 Opus 编解码器)。最初使用此脚本时,我能够传递 WAV,脚本会将其编码为 Opus,然后通过通道将其发送到 Discord。相反,我想发送一个现成的 Opus 文件。然而,相反,我听到了乱码,这意味着我在阅读它时做错了什么。
这是一个精简但完整的示例(减去电子邮件、密码和服务器 ID),魔术发生在playSong
. 我觉得这与我的音频缓冲区有关,但仍然在学习技巧。
读取作品文件并将其传递给频道的正确方法是什么?如果需要一个作品文件来测试,在这里找到一个。任何帮助表示赞赏。谢谢!
package main
import (
"encoding/binary"
"fmt"
"io"
"os"
"os/exec"
"runtime"
"strings"
"github.com/bwmarrin/discordgo"
"github.com/oleiade/lane"
)
type voiceInstancesMap map[string]*VoiceInstance
var (
run *exec.Cmd
voiceInstances = voiceInstancesMap{}
)
const (
email string = ""
password string = ""
serverID string = ""
channels int = 2 // 1 for mono, 2 for stereo
frameRate int = 48000 // audio sampling rate
)
type VoiceInstance struct {
discord *discordgo.Session
queue *lane.Queue
serverID string
}
func (vi *VoiceInstance) playSong() {
f, err := os.Open("./test.opus")
defer f.Close()
audiobuf := make([]byte, 1024)
vi.discord.Voice.Speaking(true)
defer vi.discord.Voice.Speaking(false)
for {
err = binary.Read(f, binary.LittleEndian, &audiobuf)
if err == io.EOF || err == io.ErrUnexpectedEOF {
break
}
if err != nil {
fmt.Println("error reading from ffmpeg stdout :", err)
break
}
fmt.Println("Sending audio")
vi.discord.Voice.OpusSend <- audiobuf
}
}
func (vi *VoiceInstance) connectVoice() {
vi.discord, _ = discordgo.New(email, password)
// Open the websocket and begin listening.
err := vi.discord.Open()
if err != nil {
fmt.Println(err)
}
channels, err := vi.discord.GuildChannels(vi.serverID)
var voiceChannel string
voiceChannels := []string{}
for _, channel := range channels {
if channel.Type == "voice" {
voiceChannels = append(voiceChannels, channel.ID)
if strings.Contains(strings.ToLower(channel.Name), "music") && voiceChannel == "" {
voiceChannel = channel.ID
}
}
}
if voiceChannel == "" {
fmt.Println("Selecting first channel")
voiceChannel = voiceChannels[0]
}
err = vi.discord.ChannelVoiceJoin(vi.serverID, voiceChannel, false, true)
if err != nil {
fmt.Println(err)
return
}
// Hacky loop to prevent sending on a nil channel.
// TODO: Find a better way.
for vi.discord.Voice.Ready == false {
runtime.Gosched()
}
}
func main() {
vi := new(VoiceInstance)
voiceInstances[serverID] = vi
fmt.Println("Connecting Voice...")
vi.serverID = serverID
vi.queue = lane.NewQueue()
vi.connectVoice()
vi.playSong()
}