Downsampling a PCM audio buffer in javascript - javascript

I am attempting to downsample the sample rate i am getting from audioContext. I believe it is coming in at 44100, and i want it to be 11025. I thought i could just average every 3 samples and it plays back at the correct rate, but the pitch of is too high, as if we were all on helium.
What is the correct way to downsample a float32Array from 44100 to a int16Array at 11025 samples.
var context = new Flash.audioContext();
var audioInput = context.createMediaStreamSource(stream);
var recorder = context.createScriptProcessor(null, 1, 1);
recorder.onaudioprocess = onAudio;
audioInput.connect(recorder);
recorder.connect(context.destination);
var onAudio = function (e) {
var left = e.inputBuffer.getChannelData(0);
bStream.write(Flash.convertFloat32ToInt16(left));
}
var convertFloat32ToInt16 = function(buffer) {
var l = buffer.length;
var point = Math.floor(l/3);
var buf = new Int16Array(point);
for (var x = l; x > 0;) {
var average = (buffer[x] + buffer[x-1] + buffer[x-2]) / 3;
buf[point] = average*0x7FFF;
point -= 1;
x -= 3;
}
return buf.buffer;
}

For anyone else who needs the answer.
var downsampleBuffer = function (buffer, sampleRate, outSampleRate) {
if (outSampleRate == sampleRate) {
return buffer;
}
if (outSampleRate > sampleRate) {
throw "downsampling rate show be smaller than original sample rate";
}
var sampleRateRatio = sampleRate / outSampleRate;
var newLength = Math.round(buffer.length / sampleRateRatio);
var result = new Int16Array(newLength);
var offsetResult = 0;
var offsetBuffer = 0;
while (offsetResult < result.length) {
var nextOffsetBuffer = Math.round((offsetResult + 1) * sampleRateRatio);
var accum = 0, count = 0;
for (var i = offsetBuffer; i < nextOffsetBuffer && i < buffer.length; i++) {
accum += buffer[i];
count++;
}
result[offsetResult] = Math.min(1, accum / count)*0x7FFF;
offsetResult++;
offsetBuffer = nextOffsetBuffer;
}
return result.buffer;
}
this will return a sample rate smaller than the one passed to it, while also converting it to a int16Array instead of a float32.

Related

Need to upsample audio from 8k to 16k

I was using below code for downsampling my audio while recording
let inputSampleRate; let inputBuffer = [];
function init(x) {
inputSampleRate = x;
}
function process(inputFrame) {
for (let i = 0; i < inputFrame.length; i++) {
inputBuffer.push((inputFrame[i]) * 32767);
}
const PV_SAMPLE_RATE = 16000;
const PV_FRAME_LENGTH = 512;
while ((inputBuffer.length * PV_SAMPLE_RATE / inputSampleRate) > PV_FRAME_LENGTH) {
let outputFrame = new Int16Array(PV_FRAME_LENGTH);
let sum = 0;
let num = 0;
let outputIndex = 0;
let inputIndex = 0;
while (outputIndex < PV_FRAME_LENGTH) {
sum = 0;
num = 0;
while (inputIndex < Math.min(inputBuffer.length, (outputIndex + 1) * inputSampleRate / PV_SAMPLE_RATE)) {
sum += inputBuffer[inputIndex];
num++;
inputIndex++;
}
outputFrame[outputIndex] = sum / num;
outputIndex++;
}
postMessage(outputFrame);
inputBuffer = inputBuffer.slice(inputIndex);
}
}
Can anyone please suggest how can I edit this one, so that it can be used to upsample my audio from 8k to 16k?
The traditional way to do upsampling (and downsampling) can be found at Wikipedia article about upsampling.
If you want something really cheap and dirty, just linearly interpolate between samples. So if you have samples x0 and x1, the upsampled values are y0=x0, y2=x1, and the new sample y1=(x0+x1)/2. This isn't great and you might hear artifacts.
Edit:
In your code, you can try something like this:
s0 = inputBuffer[inputIndex];
s1 = inputBuffer[inputIndex + 1];
outputFrame[outputIndex] = s0;
outputFrame[outputIndex + 1] = (s0 + s1)/2;
outputFrame[outputIndex + 2] = s1
You'll have to keep track of the indices so you don't try to access beyond the length of the arrays. This is totally untested.

javascript canvas: draw moving average line with curves

So basically, I want to draw a curved average line over a certain amount of points of a time-series line chart. Like this:
I want it to span the entire length of the chart but I can't figure out how to calculate the start and end points because the average would (I think) be a point in the middle of each section. Looking at a stock chart with moving average you can see what I want to acheive:
I calculate the averages first by splitting the data array up into chunks based on a period of time. So if I start with:
[
{ time: 1, value: 2 },
{ time: 2, value: 4 },
{ time: 3, value: 5 },
{ time: 4, value: 7 },
]
I get to:
var averages = [
{
x: 1.5,
y: 3,
},
{
x: 3.5 (the average time)
y: 6 (the average value)
},
]
This is what I've tried where I end up with an incomplete line, one that doesnt start at the beginning of the chart and doesnt stop at the end, but stars and ends inside the chart at the first average time:
ctx.moveTo((averages[0].x), averages[0].y);
for(var i = 0; i < averages.length-1; i ++)
{
var x_mid = (averages[i].x + averages[i+1].x) / 2;
var y_mid = (averages[i].y + averages[i+1].y) / 2;
var cp_x1 = (x_mid + averages[i].x) / 2;
var cp_x2 = (x_mid + averages[i+1].x) / 2;
ctx.quadraticCurveTo(cp_x1, averages[i].y ,x_mid, y_mid);
ctx.quadraticCurveTo(cp_x2, averages[i+1].y ,averages[i+1].x, averages[i+1].y);
}
ctx.stroke();
How would you do this?
To get a moving mean you need to just get the mean of n points either side of the current sample.
For example
// array of data points
const movingMean = []; // the resulting means
const data = [12,345,123,53,134,...,219]; // data with index representing x axis
const sampleSize = 5;
for(var i = sampleSize; i < data.length - sampleSize; i++){
var total = 0;
for(var j = i- sampleSize; j < i + sampleSize; j++){
total += data[j];
}
movingMean[i] = total / (sampleSize * 2);
}
This method does not pull the mean forward giving the most accurate mean for each data point.
The problem with this method is that you do not get a mean for the first n and last n samples, where n is the number of samples either side of the mean.
You can do an alternative that will pull the mean forward a little but by applying a weighted mean you can reduce the bias a little
for(var i = sampleSize; i < data.length + Math.floor(sampleSize / 4); i++){
var total = 0;
var count = 0;
for(var j = sampleSize; j > 0; j --){
var index = i - (sampleSize - j);
if(index < data.length){
total += data[index] * j; // linear weighting
count += j;
}
}
movingMean[i-Math.floor(sampleSize / 4)] = total / count;
}
This method keeps that mean closer to the current sample end.
The example show a random data set and the two types of means plotted over it. Click to get a new plot. The red line is the moving mean and the blue is the weighted mean. Note how the blue line tends to follow the data a little slow.
The green line is a weighted mean that has a sample range 4 times greater than the other two.
// helper functions
const doFor = (count, callback) => {var i = 0; while (i < count) { callback(i ++) } };
const setOf = (count, callback) => {var a = [],i = 0; while (i < count) { a.push(callback(i ++)) } return a };
const rand = (min, max = min + (min = 0)) => Math.random() * (max - min) + min;
const randG = (dis, min, max) => {var r = 0; doFor(dis,()=>r+=rand(min,max)); return r / dis};
function getMinMax(data){
var min = data[0];
var max = data[0];
doFor(data.length - 1, i => {
min = Math.min(min,data[i+1]);
max = Math.max(max,data[i+1]);
});
var range = max-min;
return {min,max,range};
}
function plotData(data,minMax){
ctx.beginPath();
for(var i = 0; i < data.length; i++){
if(data[i] !== undefined){
var y = (data[i] - minMax.min) / minMax.range;
y = y *(ctx.canvas.height - 2) + 1;
ctx.lineTo(i/2,y);
}
}
ctx.stroke();
}
function getMovingMean(data,sampleSize){
const movingMean = []; // the resulting means
for(var i = sampleSize; i < data.length - sampleSize; i++){
var total = 0;
for(var j = i- sampleSize; j < i + sampleSize; j++){
total += data[j];
}
movingMean[i] = total / (sampleSize * 2);
}
return movingMean[i];
}
function getMovingMean(data,sampleSize){
const movingMean = []; // the resulting means
for(var i = sampleSize; i < data.length - sampleSize; i++){
var total = 0;
for(var j = i- sampleSize; j < i + sampleSize; j++){
total += data[j];
}
movingMean[i] = total / (sampleSize * 2);
}
return movingMean;
}
function getWeightedMean(data,sampleSize){
const weightedMean = [];
for(var i = sampleSize; i < data.length+Math.floor(sampleSize/4); i++){
var total = 0;
var count = 0;
for(var j = sampleSize; j > 0; j --){
var index = i - (sampleSize - j);
if(index < data.length){
total += data[index] * j; // linear weighting
count += j;
}
}
weightedMean[i-Math.floor(sampleSize/4)] = total / count;
}
return weightedMean;
}
const dataSize = 1000;
const sampleSize = 50;
canvas.width = dataSize/2;
canvas.height = 200;
const ctx = canvas.getContext("2d");
function displayData(){
ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);
var dataPoint = 100;
var distribution = Math.floor(rand(1,8));
var movement = rand(2,20);
const data = setOf(dataSize,i => dataPoint += randG(distribution, -movement, movement));
const movingMean = getMovingMean(data, sampleSize);
const weightedMean = getWeightedMean(data, sampleSize*2);
const weightedMean1 = getWeightedMean(data, sampleSize*8);
var minMax = getMinMax(data);
ctx.strokeStyle = "#ccc";
plotData(data,minMax);
ctx.strokeStyle = "#F50";
plotData(movingMean,minMax);
ctx.strokeStyle = "#08F";
plotData(weightedMean,minMax);
ctx.strokeStyle = "#4C0";
plotData(weightedMean1,minMax);
}
displayData();
document.onclick = displayData;
body { font-family : arial; }
.red { color : #F50; }
.blue { color : #0AF; }
.green { color : #4C0; }
canvas { position : absolute; top : 0px; left :130px; }
<canvas id="canvas"></canvas>
<div class="red">Moving mean</div>
<div class="blue">Weighted mean</div>
<div class="green">Wide weighted mean</div>
<div>Click for another sample</div>

Execution time for successful search Binary Search algorithm

I have implemented Binary Search Algorithm using Node.js. I am recording the time taken by the algorithm to search for a number in a random generated array. I am able to output the time taken by the algorithm for an unsuccessful search.
But I am not able to figure out how to measure the time taken by the algorithm to successfully search a number in an array.
Here is my code -
function binarySearch(A,K)
{
var l = 0; // min
var r = A.length - 1; //max
var n = A.length;
var time = process.hrtime();
while(l <= r)
{
var m = Math.floor((l + r)/2);
if(K == A[m])
{
return m;
}
else if(K < A[m])
{
r = m - 1;
}
else
{
l = m + 1;
}
}
time = process.hrtime(time);
console.log('%d',time[1]/1000000);
return -1;
}
var randomlyGenerateArray = function(size)
{
var array = [];
for (var i = 0; i < size; i++)
{
var temp = Math.floor(Math.random() * maxArrayValue);
array.push(temp);
}
return array;
}
var sortNumber = function(a, b)
{
return a - b;
}
var program = function()
{
for (var i = 0; i <= 10000; i += 10)
{
var randomArray = randomlyGenerateArray(i);
var sort = randomArray.sort(sortNumber);
var randomKey = 100;
var result = binarySearch(sort, randomKey);
if(result < 0)
{
console.log("Element not found");
}
else
{
console.log('Element found in position ',result);
}
}
}
var maxArrayValue = 1000;
program();
I am using var time = process.hrtime(); to start the timer at the beginning of the algorithm and using time = process.hrtime(time); to end the timer and output it in the console.
How can I measure the time taken by the algorithm to successfully search a number in an array.
Any help would be greatly appreciated.
Start your timer before calling the binary search function and end it after the call .. regardless of whether the search is successful or not, you will get the time ..
var time = process.hrtime();
var result = binarySearch(sort, randomKey);
time = process.hrtime(time);
......

Why does the following Short ID generator always pause after a specific number of iterations

I am writing my own short Id generator. Running into some trouble testing the anticipated number of clashes, the script always seems to pause after a certain number of iterations. It prints 3.6999999999999997% clashes = 0 (that is after 37,000,000 iterations) and then pauses for a long time before printing 3.8% clashes = 0.
I have no real idea why this is?
var alreadyExistsCounter = 0;
var oneMillion = 1000000;
var iterations = oneMillion * 100;
var ALPHABET = '23456789abdegjkmnpqrvwxyz';
var hash = {};
var ID_LENGTH = 10;
var generate = function() {
var rtn = '';
for (var i = 0; i < ID_LENGTH; i++) {
rtn += ALPHABET.charAt(Math.floor(Math.random() * ALPHABET.length));
}
return rtn;
}
for (var i = 0; i < iterations;i++){
var sh = generate();
if (hash[sh]){
alreadyExistsCounter = alreadyExistsCounter +1;
}
hash[sh] = true;
if (i % 100000 === 0){
var pct = i / iterations * 100;
console.log( pct + '% clashes = ' + alreadyExistsCounter );
}
}

Variable scope within methods

I was teaching myself how to make a binary genetic algorithm the other day. The goal was to make it so that it would match a randomly generated 35 length binary string. I ran into a problem where methods were editing variables that I did not think were in its scope. This caused my solution to slowly degrade in fitness instead of increase! After I found out where this was happening I fixed it by newP[0].join('').split('') so that newP[0] itself would not be edited. For convenience I've marked where the problem was happening below in comments.
While I have fixed this problem I'd like to hopefully get an understanding as to why this happens and also prevent without doing the join/split silliness.
Here is the code:
var GeneticAlgorithm = function () {};
GeneticAlgorithm.prototype.mutate = function(chromosome, p) {
for(var i = 0; i < chromosome.length; i++) {
if(Math.random() < p) {
chromosome[i] = (chromosome[i] == 0) ? 1 : 0;
}
}
return chromosome;
};
GeneticAlgorithm.prototype.crossover = function(chromosome1, chromosome2) {
var split = Math.round(Math.random() * chromosome1.length);
var c1 = chromosome1;
var c2 = chromosome2;
for(var i = 0; i < split; i++) {
c1[i] = chromosome2[i];
c2[i] = chromosome1[i];
}
return [c1, c2];
};
// fitness = function for finding fitness score of an individual/chromosome (0-1)
// length = length of string (35)
// p_c = percentage chance of crossover (0.6)
// p_m = percentage change of mutation (0.002)
GeneticAlgorithm.prototype.run = function(fitness, length, p_c, p_m, iterations) {
var iterations = 100;
var size = 100;
// p = population, f = fitnesses
var p = [];
var f = [];
for(var i = 0; i < size; i++) {
p.push(this.generate(length));
f.push(fitness(p[i].join('')));
}
while( iterations > 0 && Math.max.apply(Math, f) < 0.999 ) {
var mates = [];
var newP = [];
var newF = [];
mates = this.select(p, f);
newP.push(mates[0], mates[1]);
while(newP.length < size) {
/*-------------------> Problem! <-------------------*/
mates = [newP[0].join('').split(''), newP[1].join('').split('')];
/*
* If I passed newP[0] when mates[0] changed newP[0] would also change
*/
if(Math.random() < p_c) {
mates = this.crossover(mates[0], mates[1]);
}
mates[0] = this.mutate(mates[0], p_m);
mates[1] = this.mutate(mates[1], p_m);
newP.push(mates[0], mates[1]);
}
for(var i = 0; i < size; i++) {
newF.push(fitness(newP[i].join('')));
}
p = newP;
f = newF;
iterations--;
}
return p[f.indexOf(Math.max.apply(Math, f))].join('');
};

Categories