Skip to content

Instantly share code, notes, and snippets.

@xnorpx
Created July 6, 2020 18:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save xnorpx/c5d12bb0211731980138c7fe33772f0e to your computer and use it in GitHub Desktop.
Save xnorpx/c5d12bb0211731980138c7fe33772f0e to your computer and use it in GitHub Desktop.
// only tested with 1 channel wav file
const { OpusEncoder } = require('@discordjs/opus');
let fs = require('fs');
wav_file = fs.readFileSync('somefile.wav');
const WaveFile = require('wavefile').WaveFile;
let wav = new WaveFile(wav_file);
// Check some of the file properties
console.log(wav.fmt.sampleRate)
console.log(wav.fmt.numChannels)
const encoder = new OpusEncoder(wav.fmt.sampleRate, wav.fmt.numChannels);
encoder.setBitrate(6000); // make sure it sounds like ****
let samples = wav.getSamples(true, Int16Array);
console.log(samples.length)
let ptime = 20 // ms
let samples_per_frame = (wav.fmt.sampleRate / (1000 / ptime)) * wav.fmt.numChannels;
console.log(samples_per_frame)
let output_data = new Uint8Array(samples.length * 2);
for (i = 0; i < samples.length; i += samples_per_frame) {
const encoded = encoder.encode(samples.slice(i,i + samples_per_frame));
output_data.set(encoder.decode(encoded), i * 2);
}
let output_wav = new WaveFile();
wav.fromScratch(wav.fmt.numChannels, wav.fmt.sampleRate, '16', new Int16Array(output_data.buffer));
fs.writeFileSync('out.wav', wav.toBuffer());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment