Created
July 6, 2020 18:58
-
-
Save xnorpx/c5d12bb0211731980138c7fe33772f0e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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