Created
September 18, 2018 09:24
-
-
Save richtier/68a4c944a1bdc1bf678b5a8cd7c1fc14 to your computer and use it in GitHub Desktop.
JavaScript webaudio to wav encoder
This file contains 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
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; | |
This file contains 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
# 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