Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get precise notes with riffwave.js

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.

like image 454
Andrew Grothe Avatar asked Feb 17 '23 05:02

Andrew Grothe


1 Answers

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();
like image 159
fuzic Avatar answered Feb 19 '23 18:02

fuzic