Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play Music Notes with Javascript

I am developing a little free software project which is basically a music keyboard and score sheet editor.

My first step in this project is to play note and or conceive notes itself. I use timbre, which is a few documented http://mohayonao.github.io/timbre.js . My first function is to transform for example "C4" (do4 en français) in a audio sound from sine function.

But what I can't do for now is to play and stop notes. Play works for begin the sine wave but when I play a second note, the first note doesn't disappear so I got 2 sine and then 3

My script https://gitlab.com/mdahmen/Laterreestron.de/blob/master/pagesandapps/partgenie/js/lecture.js

http://mohayonao.github.io/timbre.js

The test page: http://laterreestron.de/pagesandapps/partgenie/index.php

like image 749
manueldahmen Avatar asked Aug 12 '26 04:08

manueldahmen


1 Answers

I was able to play notes using synth.noteOnWithFreq() and then end them using synth.noteOff() The code is based on the Synthesizer example on the timbre.js project page. Make sure that you include the keyboard.js library as show below.

Run the code snippet, click on the input box, and type some letters

var synth = T("OscGen", {
  wave: "saw",
  mul: 0.25
}).play();

var keydict = T("ndict.key");

var midicps = T("midicps");

T("keyboard").on("keydown", function(e) {
  var midi = keydict.at(e.keyCode);
  if (midi) {
    var freq = midicps.at(midi);
    synth.noteOnWithFreq(freq, 100);
    window.key.innerHTML = midi;
    window.freq.innerHTML = freq.toFixed(2);
  }
}).on("keyup", function(e) {
  var midi = keydict.at(e.keyCode);
  if (midi) {
    synth.noteOff(midi, 100);
  }
}).start();
<script src="http://mohayonao.github.io/timbre.js/timbre.js"></script>
<script src="http://mohayonao.github.io/timbre.js/src/extras/keyboard.js"></script>
<div>KeyCode: <span id="key"></span>, Freq: <span id="freq"></span></div>
<input id="keyboard" placeholder="Type some letters here">
like image 162
Roberto Avatar answered Aug 14 '26 17:08

Roberto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!