Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do I pipe the output of *discordgo.Packet to ffmpeg? #1546

Open
ThallesP opened this issue Jul 16, 2024 · 0 comments
Open

How do I pipe the output of *discordgo.Packet to ffmpeg? #1546

ThallesP opened this issue Jul 16, 2024 · 0 comments

Comments

@ThallesP
Copy link

ThallesP commented Jul 16, 2024

I'm trying to convert discord's opus packets to .wav using ffmpeg but I can't get it to work with discordgo. I'm a newbie to encoders so i'm probably missing something stupid. Here's my code so far:

package main

import (
	"fmt"
	"os"
	"os/exec"
	"os/signal"
	"syscall"
	"time"

	"github.com/bwmarrin/discordgo"
)

const CHANNEL_ID = "838536675240050708"
const GUILD_ID = "838505728976748624"

func main() {
	dg, err := discordgo.New("Bot " + os.Getenv("BOT_TOKEN"))

	if err != nil {
		panic(err)
	}

	err = dg.Open()

	if err != nil {
		panic(err)
	}

	dgv, err := dg.ChannelVoiceJoin(GUILD_ID, CHANNEL_ID, false, false)

	if err != nil {
		panic(err)
	}

	SaveReceivedAudio(dgv)

	fmt.Println("Bot is now running.  Press CTRL-C to exit.")
	sc := make(chan os.Signal, 1)
	signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
	<-sc

	dg.Close()
}

func SaveReceivedAudio(v *discordgo.VoiceConnection) {
	go func(v *discordgo.VoiceConnection) {
		cmd := exec.Command("/usr/bin/ffmpeg",
			"-ac", "2",
			"-ar", "48000",
			"-f", "s16le",
			"-acodec", "libopus",
			"-i", "-", // take stdin as input
			"/home/thalles/scribe/output.opus",
		)

		cmd.Stderr = os.Stdout

		pipe, err := cmd.StdinPipe()

		if err != nil {
			panic(err)
		}

		err = cmd.Start()

		if err != nil {
			panic(err)
		}

		for {
			select {
			case packet := <-v.OpusRecv:
				/*pkrtp := &rtp.Packet{
					Header: rtp.Header{
						Version:        2,
						PayloadType:    0x78,
						SequenceNumber: packet.Sequence,
						Timestamp:      packet.Timestamp,
						SSRC:           packet.SSRC,
					},
					Payload: packet.Opus,
				}
				//pkrtp.MarshalTo(bufferRTP)
				b, _ := pkrtp.Marshal()*/

				pipe.Write(packet.Opus)
				continue
			case <-time.Tick(10 * time.Second):
				pipe.Close()
				fmt.Println("stopping", cmd.Process.Signal(os.Interrupt))
				return
			}

		}
	}(v)
}

I've seen the use of oggwriter but I'm scared that it'll cause overhead

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant