Writing a raw opus buffer to a file in NodeJS

Viewed 277

I'm working on Discord voice and I made voice receiver, but I can't seem to be able to write the audio buffer to a file to be able to play it. Here's my code:

stopRecording() {
    this.recording = false;
    let output = Buffer.concat(this.recordedBuffers);
    fs.writeFileSync('./out.opus', output.toString());
    this.recordedBuffers = [];
    console.log('done');
};

The file gets created but it is unplayable. Any ideas?

1 Answers

It may be worth confirming that recordedBuffers contains Ogg Opus file data. The first 32 bytes should show file header data indicating this is an Ogg, Webm, or Mp4 container. Once the mime-type is confirmed, the file extension can be changed from .opus if needed:

/*  .opus = 'OggS ... Opus'
 *  .webm = '... webm ...'
 *  .mp4  = '... mp4 ...'
 *  .wav  = '... WAVE ...'
 */
new TextDecoder().decode(concatenatedBuffers.slice(0, 32))

FFmpeg could also inspect the downloaded file:

$ ffprobe audio.opus 

Input #0, ogg, from 'audio.opus':
  Duration: 00:06:00.11, start: 0.000000, bitrate: 99 kb/s
    Stream #0:0: Audio: opus, 48000 Hz, stereo, fltp
Related