Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JavaScript webaudio to wav encoder
class WavAudioEncoder {
encode = buffer => {
const channelData = buffer.getChannelData(0);
const length = buffer.length;
const data = []
for (let i = 0; i < length; ++i) {
let x = channelData[i] * 0x7fff;
data.push(Math.round(x < 0 ? Math.max(x, -0x8000) : Math.min(x, 0x7fff)));
}
return this.interpolateArray(data, 16000, buffer.sampleRate);
}
interpolateArray = (data, newSampleRate, oldSampleRate) => {
var fitCount = Math.round(data.length*(newSampleRate/oldSampleRate));
var newData = new Array();
var springFactor = new Number((data.length - 1) / (fitCount - 1));
newData[0] = data[0]; // for new allocation
for ( var i = 1; i < fitCount - 1; i++) {
var tmp = i * springFactor;
var before = new Number(Math.floor(tmp)).toFixed();
var after = new Number(Math.ceil(tmp)).toFixed();
var atPoint = tmp - before;
newData[i] = this.linearInterpolate(data[before], data[after], atPoint);
}
newData[fitCount - 1] = data[data.length - 1]; // for new allocation
return newData;
}
linearInterpolate = (before, after, atPoint) => {
return Math.ceil(before + (after - before) * atPoint);
}
}
export default WavAudioEncoder;
# having recieved `samples` through a websocket...
import struct
audio = struct.pack("<%dh" % len(samples), *samples)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment