Get precise notes with riffwave.js - javascript

Does anyone know if its possible to get a precise note (C, C#, D, Eb, etc) from a javascript library like riffwave.js?
The demo makes me think is possible but I'm not sure how to transpose the piano frequency
for a given note into the data array required for the generated wave file.

Sure! You'd want to create some mapping function from key to frequency (could just be a dictionary).
To synthesize a given frequency with riffwave.js, you would do something like this
function simHertz(hz) {
var audio = new Audio();
var wave = new RIFFWAVE();
var data = [];
wave.header.sampleRate = 44100;
var seconds = 1;
for (var i = 0; i < wave.header.sampleRate * seconds; i ++) {
data[i] = Math.round(128 + 127 * Math.sin(i * 2 * Math.PI * hz / wave.header.sampleRate));
}
wave.Make(data);
audio.src = wave.dataURI;
return audio;
}
var audio = simHertz(1000);
audio.play();

Related

Create sound effect with Tone.js notes?

How can I create one of these sound effects with Tone.js notes
Is this even possible? When given are these notes:
"C","C#","Db","D","D#","Eb","E","E#","Fb","F","F#","Gb","G","G#","Ab","A","A#","Bb","B","B#","Cb"...
Can I now somehow use tone.js to create a sound effect like "Tada!"? I think it needs more than just the notes/tones, it needs also somehow pitching and time manimulation?
Simple C tone played for 400ms:
polySynth.triggerAttack("C");
setTimeout(x=>polySynth.triggerRelease("C"),400);
Here a working Jsfiddle with Tone.js to experiment.
I don't have a very experienced ear, but most of these sound like major chords (base, third, fifth) to me, some with an added octave. For example, C4, E4, G4, C5:
const chord = ["C4", "E4", "G4", "C5"];
const duration = 0.5;
const delay = 0.05;
const now = Tone.now();
for (let i = 0; i < chord.length; i++) {
const note = chord[i];
polySynth.triggerAttackRelease(note, duration, now + i * delay);
}
If you want to randomize the root note, it might be useful to work with frequencies directly, instead of note names. The A above middle C is usually taken as 440 Hz, and each successive semi-tone above that is a factor of Math.pow(2, 1/12) higher:
const rootFrequency = 440;
const chordSemitones = [0, 4, 7, 12];
const duration = 0.5;
const delay = 0.1;
const now = Tone.now();
for (let i = 0; i < chordSemitones.length; i++) {
const pitch = rootFrequency * Math.pow(2, chordSemitones[i] / 12);
polySynth.triggerAttackRelease(pitch, duration, now + i * delay);
}

A DFT analysis in a low speed data sampling

I have some sample data of vibrations analysis from sensors installed on electrical motors. The sampling is made once or, at most, 3 times per day. The values can be expressed in g, gE or mm/s.
I’m developing a personal algorithm in JavaScript to process some samples and perform a DFT. It’s a simple code that uses brute force to process my results. I compared the results (real and imaginary parts) from JavaScript and from MATLAB results and they matched perfectly.
However, my sampling rate is very slow. Because of this, I have a lot of questions which I couldn’t find the answers on my searches:
Is it possible to apply a DFT analysis on a slow sampling data as this?
How can I determine the correct frequency scale for the X axis? It’s complicated for me because I don’t have an explicit Fs (sampling rate) value.
In my case, would it be interesting to apply some window function like Hanning Window (suitable for vibrations analyses)?
JavaScriptCode:
//Signal is a pure one-dimensional of real data (vibration values)
const fft = (signal) => {
const pi2 = 6.2832 //pi const
let inputLength = signal.length;
let Xre = new Array(inputLength); //DFT real part
let Xim = new Array(inputLength); //DFT imaginary part
let P = new Array(inputLength); //Power of spectrum
let M = new Array(inputLength); //Magnitude of spectrum
let angle = 2 * Math.PI / inputLength;
//Hann Window
signal = signal.map((x, index) => {
return x * 0.5 * (1 - Math.cos((2 * Math.PI * index) / (inputLength - 1)));
});
for (let k = 0; k < inputLength; ++k) { // For each output element
Xre[k] = 0; Xim[k] = 0;
for (let n = 0; n < inputLength; ++n) { // For each input element
Xre[k] += signal[n] * Math.cos(angle * k * n);
Xim[k] -= signal[n] * Math.sin(angle * k * n);
}
P[k] = Math.pow(Xre[k], 2) + Math.pow(Xim[k], 2);
M[k] = Math.sqrt(Math.pow(Xre[k], 2) + Math.pow(Xim[k], 2));
}
return { Xre: Xre, Xim: Xim, P: P, M: M.slice(0, Math.round((inputLength / 2) + 1)) };
}
The first figure shows the charts results (time domain on the left side and frequency domain on the right side).
The second figure shows a little bit of my data samples:
Obs.: I'm sorry for the writing. I'm still a beginner English student.
The frequency doesn't matter. A frequency as low as 1/day is just as fine as any other frequency. But consider the Nyquist-Shannon theorem.
This is problematic. You need a fix sampling frequency for a DFT. You could do interpolation as preprocessing. But better would be to do the sampling at fix times.

Why is precomputing sin(x) *slower* than using Math.sin() in Javascript?

I've found what appears to be an interesting anomaly in JavaScript. Which centres upon my attempts to speed up trigonometric transformation calculations by precomputing sin(x) and cos(x), and simply referencing the precomputed values.
Intuitively, one would expect pre-computation to be faster than evaluating the Math.sin() and Math.cos() functions each time. Especially if your application design is going to use only a restricted set of values for the argument of the trig functions (in my case, integer degrees in the interval [0°, 360°), which is sufficient for my purposes here).
So, I ran a little test. After pre-computing the values of sin(x) and cos(x), storing them in 360-element arrays, I wrote a short test function, activated by a button in a simple test HTML page, to compare the speed of the two approaches. One loop simply multiplies a value by the pre-computed array element value, whilst the other loop multiplies a value by Math.sin().
My expectation was that the pre-computed loop would be noticeably faster than the loop involving a function call to a trig function. To my surprise, the pre-computed loop was slower.
Here's the test function I wrote:
function MyTest()
{
var ITERATION_COUNT = 1000000;
var angle = Math.floor(Math.random() * 360);
var test1 = 200 * sinArray[angle];
var test2 = 200 * cosArray[angle];
var ref = document.getElementById("Output1");
var outData = "Test 1 : " + test1.toString().trim() + "<br><br>";
outData += "Test 2 : "+test2.toString().trim() + "<br><br>";
var time1 = new Date(); //Time at the start of the test
for (var i=0; i<ITERATION_COUNT; i++)
{
var angle = Math.floor(Math.random() * 360);
var test3 = (200 * sinArray[angle]);
//End i loop
}
var time2 = new Date();
//This somewhat unwieldy procedure is how we find out the elapsed time ...
var msec1 = (time1.getUTCSeconds() * 1000) + time1.getUTCMilliseconds();
var msec2 = (time2.getUTCSeconds() * 1000) + time2.getUTCMilliseconds();
var elapsed1 = msec2 - msec1;
outData += "Test 3 : Elapsed time is " + elapsed1.toString().trim() + " milliseconds<br><br>";
//Now comparison test with the same number of sin() calls ...
var time1 = new Date();
for (var i=0; i<ITERATION_COUNT; i++)
{
var angle = Math.floor(Math.random() * 360);
var test3 = (200 * Math.sin((Math.PI * angle) / 180));
//End i loop
}
var time2 = new Date();
var msec1 = (time1.getUTCSeconds() * 1000) + time1.getUTCMilliseconds();
var msec2 = (time2.getUTCSeconds() * 1000) + time2.getUTCMilliseconds();
var elapsed2 = msec2 - msec1;
outData += "Test 4 : Elapsed time is " + elapsed2.toString().trim() + " milliseconds<br><br>";
ref.innerHTML = outData;
//End function
}
My motivation for the above, was that multiplying by a pre-computed value fetched from an array would be faster than invoking a function call to a trig function, but the results I obtain are interestingly anomalous.
Some sample runs yield the following results (Test 3 is the pre-computed elapsed time, Test 4 the Math.sin() elapsed time):
Run 1:
Test 3 : Elapsed time is 153 milliseconds
Test 4 : Elapsed time is 67 milliseconds
Run 2:
Test 3 : Elapsed time is 167 milliseconds
Test 4 : Elapsed time is 69 milliseconds
Run 3 :
Test 3 : Elapsed time is 265 milliseconds
Test 4 : Elapsed time is 107 milliseconds
Run 4:
Test 3 : Elapsed time is 162 milliseconds
Test 4 : Elapsed time is 69 milliseconds
Why is invoking a trig function twice as fast as referencing a precomputed value from an array, when the precomputed approach, intuitively at least, should be the faster by an appreciable margin? All the more so because I'm using integer arguments to index the array in the precomputed loop, whilst the function call loop also includes an extra calculation to convert from degrees to radians?
There's something interesting happening here, but at the moment, I'm not sure what. Usually, array accesses to precomputed data are a lot faster than calling intricate trig functions (or at least, they were back in the days when I coded similar code in assembler!), but JavaScript seems to turn this on its head. The only reason I can think of, is that JavaScript adds a lot of overhead to array accesses behind the scenes, but if this were so, this would impact upon a lot of other code, that appears to run at perfectly reasonable speed.
So, what exactly is going on here?
I'm running this code in Google Chrome:
Version 60.0.3112.101 (Official Build) (64-bit)
running on Windows 7 64-bit. I haven't yet tried it in Firefox, to see if the same anomalous results appear there, but that's next on the to-do list.
Anyone with a deep understanding of the inner workings of JavaScript engines, please help!
Optimiser has skewed the results.
Two identical test functions, well almost.
Run them in a benchmark and the results are surprising.
{
func : function (){
var i,a,b;
D2R = 180 / Math.PI
b = 0;
for (i = 0; i < count; i++ ) {
// single test start
a = (Math.random() * 360) | 0;
b += Math.sin(a * D2R);
// single test end
}
},
name : "summed",
},{
func : function (){
var i,a,b;
D2R = 180 / Math.PI;
b = 0;
for (i = 0; i < count; i++ ) {
// single test start
a = (Math.random() * 360) | 0;
b = Math.sin(a * D2R);
// single test end
}
},
name : "unsummed",
},
The results
=======================================
Performance test. : Optimiser check.
Use strict....... : false
Duplicates....... : 4
Samples per cycle : 100
Tests per Sample. : 10000
---------------------------------------------
Test : 'summed'
Calibrated Mean : 173µs ±1µs (*1) 11160 samples 57,803,468 TPS
---------------------------------------------
Test : 'unsummed'
Calibrated Mean : 0µs ±1µs (*1) 11063 samples Invalid TPS
----------------------------------------
Calibration zero : 140µs ±0µs (*)
(*) Error rate approximation does not represent the variance.
(*1) For calibrated results Error rate is Test Error + Calibration Error.
TPS is Tests per second as a calculated value not actual test per second.
The benchmarker barely picked up any time for the un-summed test (Had to force it to complete).
The optimiser knows that only the last result of the loop for the unsummed test is needed. It only does for the last iteration all the other results are not used so why do them.
Benchmarking in javascript is full of catches. Use a quality benchmarker, and know what the optimiser can do.
Sin and lookup test.
Testing array and sin. To be fair to sin I do not do a deg to radians conversion.
tests : [{
func : function (){
var i,a,b;
b=0;
for (i = 0; i < count; i++ ) {
a = (Math.random() * 360) | 0;
b += a;
}
},
name : "Calibration",
},{
func : function (){
var i,a,b;
b = 0;
for (i = 0; i < count; i++ ) {
a = (Math.random() * 360) | 0;
b += array[a];
}
},
name : "lookup",
},{
func : function (){
var i,a,b;
b = 0;
for (i = 0; i < count; i++ ) {
a = (Math.random() * 360) | 0;
b += Math.sin(a);
}
},
name : "Sin",
}
],
And the results
=======================================
Performance test. : Lookup compare to calculate sin.
Use strict....... : false
Data view........ : false
Duplicates....... : 4
Cycles........... : 1055
Samples per cycle : 100
Tests per Sample. : 10000
---------------------------------------------
Test : 'Calibration'
Calibrator Mean : 107µs ±1µs (*) 34921 samples
---------------------------------------------
Test : 'lookup'
Calibrated Mean : 6µs ±1µs (*1) 35342 samples 1,666,666,667TPS
---------------------------------------------
Test : 'Sin'
Calibrated Mean : 169µs ±1µs (*1) 35237 samples 59,171,598TPS
-All ----------------------------------------
Mean : 0.166ms Totals time : 17481.165ms 105500 samples
Calibration zero : 107µs ±1µs (*);
(*) Error rate approximation does not represent the variance.
(*1) For calibrated results Error rate is Test Error + Calibration Error.
TPS is Tests per second as a calculated value not actual test per second.
Again had the force completions as the lookup was too close to the error rate. But the calibrated lookup is almost a perfect match to the clock speed ??? coincidence.. I am not sure.
I believe this to be a benchmark issue on your side.
var countElement = document.getElementById('count');
var result1Element = document.getElementById('result1');
var result2Element = document.getElementById('result2');
var result3Element = document.getElementById('result3');
var floatArray = new Array(360);
var typedArray = new Float64Array(360);
var typedArray2 = new Float32Array(360);
function init() {
for (var i = 0; i < 360; i++) {
floatArray[i] = typedArray[i] = Math.sin(i * Math.PI / 180);
}
countElement.addEventListener('change', reset);
document.querySelector('form').addEventListener('submit', run);
}
function test1(count) {
var start = Date.now();
var sum = 0;
for (var i = 0; i < count; i++) {
for (var j = 0; j < 360; j++) {
sum += Math.sin(j * Math.PI / 180);
}
}
var end = Date.now();
var result1 = "sum=" + sum + "; time=" + (end - start);
result1Element.textContent = result1;
}
function test2(count) {
var start = Date.now();
var sum = 0;
for (var i = 0; i < count; i++) {
for (var j = 0; j < 360; j++) {
sum += floatArray[j];
}
}
var end = Date.now();
var result2 = "sum=" + sum + "; time=" + (end - start);
result2Element.textContent = result2;
}
function test3(count) {
var start = Date.now();
var sum = 0;
for (var i = 0; i < count; i++) {
for (var j = 0; j < 360; j++) {
sum += typedArray[j];
}
}
var end = Date.now();
var result3 = "sum=" + sum + "; time=" + (end - start);
result3Element.textContent = result3;
}
function reset() {
result1Element.textContent = '';
result2Element.textContent = '';
result3Element.textContent = '';
}
function run(ev) {
ev.preventDefault();
reset();
var count = countElement.valueAsNumber;
setTimeout(test1, 0, count);
setTimeout(test2, 0, count);
setTimeout(test3, 0, count);
}
init();
<form>
<input id="count" type="number" min="1" value="100000">
<input id="run" type="submit" value="Run">
</form>
<dl>
<dt><tt>Math.sin()</tt></dt>
<dd>Result: <span id="result1"></span></dd>
<dt><tt>Array()</tt></dt>
<dd>Result: <span id="result2"></span></dd>
<dt><tt>Float64Array()</tt></dt>
<dd>Result: <span id="result3"></span></dd>
</dl>
In my testing, an array is unquestionably faster than an uncached loop, and a typed array is marginally faster than that. Typed arrays avoid the need for boxing and unboxing the number between the array and the computation. The results I see are:
Math.sin(): 652ms
Array(): 41ms
Float64Array(): 37ms
Note that I am summing and including the results, to prevent the JIT from optimizing out the unused pure function. Also, Date.now() instead of creating seconds+millis yourself.
I agree with that the issue may be down to how you have initialised the pre-computed array
Jsbench shows the precomputed array to be 13% faster than using Math.sin()
Precomputed array: 86% (fastest 1480 ms)
Math.sin(): 100% (1718 ms)
Precomputed Typed Array: 87% (1493 ms)
Hope this helps!

d3 how to turn a set of numbers into a larger set representative of the first set

Say I have array [1,2,5,18,17,8] and I want to turn that into an array of length 40 that follows the same path.
a = [1,2,5,18,17,8];
stepSize = 1 / (40 / a.length);
then i think i could do something like
steps = [];
for( var i = 0; i < 1; i+= stepSize) {
steps.push(d3.interpolate(a[0],a[1])(i));
}
and then repeat that for all the elements. My question is there a better way to do this?
I can only guess what your real problem is but I think you want to plot these values and have a smooth curve. In that case use line.interpolate() https://github.com/mbostock/d3/wiki/SVG-Shapes#line_interpolate
In case you DO know what you need and your solution works for you, take this tip:
Never iterate over stepSize. Calculate it once and multiply it with i in every loop where i goes from 0 to 40. This way you work around precision problems.
Your algorithm cleaned up, tested and working:
var a = [1,5,12,76,1,2];
var steps = 24;
var ss = (a.length-1) / (steps-1);
var result = new Array(steps);
for (var i=0; i<steps; i++) {
var progress = ss * i;
var left = Math.floor(progress);
var right = Math.ceil(progress);
var factor = progress - left;
result[i] = (1 - factor) * a[left] + (factor) * a[right];
// alternative that actually works the same:
//result[i] = d3.interpolateNumber(a[left], a[right], factor);
}
console.log(result);

Logic Pro X Midi FX Javascript - Using GetTimingInfo() causes 100% CPU

I'm using the Scripter MidiFX in MainStage 3 (same as LogicPro X) to create a custom arpeggiator with javascript since I needed more control, so it seemed logical to use GetTimingInfo() to get the current beat inside of the ProcessMIDI() function to trigger the MIDI notes, as I saw in their examples. Unfortunately this pegs the CPU even on my Core i7 MacBook Pro, and I'm using a MacMini with a Core 2 Duo processor at actual shows.
I was able to write my own code to calculate the current beat using new Date() and then only using GetTimingInfo() to get the current tempo when a new note is pressed, but even that wasn't keeping the CPU where I'd like it to be.
When I don't include "NeedsTimingInfo=true" and just hard code the tempo everything works great, but this is a lot of extra code and makes more sense to use the built in functions.
Here's a simple sequencer example that causes this problem... am I doing something wrong? This happen even if I use a counter only run ProcessMIDI() on every 16th call!
NeedsTimingInfo = true;
var startBeat = -1;
var startPitch = 0;
var lastBeat = -1;
var currentStep = 0;
// melody test
var steps = [
0, 0, 0, 0, 0, 0, 0, 2,
0, 0, 0, 0, 0, 0, 2, 5
];
function HandleMIDI(e) {
if (e instanceof NoteOn) {
if (startBeat > 0) return;
currentStep = 0;
startPitch = e.pitch;
var info = GetTimingInfo();
lastBeat = startBeat = info.blockStartBeat;
doNote(e.pitch);
}
else if (e instanceof NoteOff) {
if (e.pitch == startPitch) {
startBeat = -1;
}
}
else {
e.send();
}
}
function doNote(pitch) {
var adjustment = 0;
if (currentStep < steps.length) {
adjustment = steps[currentStep];
}
var p = pitch + adjustment;
var on = new NoteOn;
on.pitch = p;
on.send();
var off = new NoteOff;
off.pitch = p;
off.sendAfterBeats(0.9);
}
function ProcessMIDI() {
var info = GetTimingInfo();
if (!info.playing) return;
if (startBeat < 0) return;
var beat = info.blockStartBeat;
if (beat - lastBeat >= 1) {
currentStep++;
doNote(startPitch);
lastBeat = beat;
}
}
What is your I/O Buffer Size set to in Preferences>Audio>Advanced Settings ? The smaller the buffer size, the more CPU is required. I assume that since you are using MainStage for live use, you have a very low setting to minimize your latency.
I tried running your code with a buffer size of 16, and MS stuttered and maxed out the CPU. 64 handled it better (the CPU meter spiked, but played without any hiccups). Tested on a 2009 MacBook Pro 3.06 Core 2 Duo.
You may have to live with a little more latency in order for Scripter to run smoothly. Your code itself, is solid.
The issue went away with MainStage 3.0.3, which I was able to find using TimeMachine.
I did create a custom Javascript implementation of their timing for 3.0.4, which did help quite a bit, but is an extra 100 lines or so of code (below). If anyone else runs into this problem, I would suggest the downgrade instead.
/**---[lib/TimingInfo.js]---*/
/**
* Constructor accepts the tempo for beat syncing and starts the clock
* to the current time.
*
* #param tempo the tempo of the song (default: 120bpm)
*/
function TimingInfo(tempo) {
this.schedule = [];
this.setTempo(tempo);
this.reset();
}
/**
* Sets the tempo and computes all times associated, assuming a 4/4
* beat structure.
*
* #param tempo the current tempo in beats per minute.
*/
TimingInfo.prototype.setTempo = function(tempo) {
this.tempo = tempo || 120;
this.msecPerBeat = (60 / this.tempo) * 1000;
};
/**
* Resets the beatsync to be relative to the current time.
*/
TimingInfo.prototype.reset = function() {
this.startTime = new Date().getTime();
this.update();
// trigger all scheduled messages immediately. TODO: note off only?
this._sendScheduled(null);
};
/**
* Uses the current time to update what the current beat is and all
* related properties. Any scheduled actions are performed if their
* time has passed.
*/
TimingInfo.prototype.update = function() {
var now = new Date().getTime();
this.elapsedMsec = now - this.startTime;
this.beat = this.elapsedMsec / this.msecPerBeat;
this._sendScheduled(this.beat);
};
/**
* Schedules a midi message to be sent at a specific beat.
* #param e MIDI event to schedule
* #param beat the beat number to send it on
*/
TimingInfo.prototype.sendAtBeat = function(e, beat) {
if (e == null) return;
// insert in-order into schedule
var insertAt = 0;
for (var i = 0; i < this.schedule.length; i++) {
if (this.schedule[i].beat > beat) {
insertAt = i;
break;
}
}
this.schedule.splice(insertAt, 0, {e:e, beat:beat});
};
/**
* Schedules a midi message relative to current beat.
*/
TimingInfo.prototype.sendAfterBeats = function(e, deltaBeats) {
this.sendAtBeat(e, this.beat + deltaBeats);
};
/**
* Sends all messages scheduled on or before a given beat. If not
* supplied all scheduled items are sent.
*
* #param atBeat beat to compare all scheduled events against (default: all)
*/
TimingInfo.prototype._sendScheduled = function(atBeat) {
// send all items on or before the given beat
var sent = 0;
for (var i = 0; i < this.schedule.length; i++) {
if (!atBeat || this.schedule[i].beat <= atBeat) {
this.schedule[i].e.send();
sent++;
}
else {
break;
}
}
// remove sent items
this.schedule.splice(0, sent);
};
var _timing = null;
/**
* Replacement for GetTimingInfo() that calls update() to handling
* any scheduled actions.
*/
function GetNewTimingInfo() {
if (_timing == null) {
_timing = new TimingInfo();
}
_timing.update();
return _timing;
}

Categories

Resources