Discord.JS voice Recording and Data Compression

Viewed 2896

I'm currently making a Discord bot that has a "User Recording" feature, and I was in a VC testing it, and kind of noticed that the output .pcm file was ~20GB after 13 minutes.

        this.voiceChannel = await message.member.voice.channel.join()
        this.reciever = this.voiceChannel.receiver
        this.voiceChannel.on('debug', (debug) => {
            let packet = JSON.parse(debug.slice(8))
            console.log(packet.op)

            if(!packet.d || packet.d && packet.d.speaking != 1) return;
            let user = this.client.users.resolve(packet.d.user_id)
            if(packet.d.speaking) {
                let userStream = this.reciever.createStream(user, {mode: 'pcm', end: 'manual'})
                let writeStream = require('fs').createWriteStream('./recording.pcm', {})
                this.us = userStream
                this.ws = writeStream

                this.us.on("data", (chunk) =>{
                    console.log(chunk)
                    this.us.pipe(this.ws)
                })
                this.ws.on("pipe", console.log)
            }
        })

Is there any way possible to compress the .pcm file from.. I dunno, 20GB down to 5-10 MB? This seems odd as each Buffer that comes from Discord.js is a whopping 4000 bytes (4KB) (This also had my Disk capped out at 100% and writing at 60MB/s)

1 Answers

I'm going to answer my own question, but I believe I know what I did wrong.

this.us.on("data", (chunk) =>{
    console.log(chunk)
    this.us.pipe(this.ws)
})

I was incorrect in that section, because I was sending data whenever data was received, not once, but twice. I also used the zlib module (https://npmjs.org/package/zlib) and that helped even more with Data / Voice Compression.

this.us.on("data", (chunk) => {
    let slowBuf = this.zlib.deflate(chunk, (er, res) => {
        console.log(res)
        this.ws.write(res)
    })
})

That worked like a charm and is now writing data at 600KB per 2 minutes or so of testing.

Related