• Playing Piano Midi Notes on an Espruino Original Board

    Using the Espruino examples found here:

    Espruino Waveforms

    A recording of Middle C played on a piano was found here:

    Piano C4 Sample

    As per the example Audacity found here:
    Audacity

    was used to create an audio sample at 8 kHz rate in unsigned 8 bit format.

    The function get_freq(note) was constructed so that the playback rate of the sound sample can be adjusted to change the pitch of the note. The note is specified as a Midi note number.
    Middle C is Midi note number 60 (aka C4), C above middle C (aka C5) is midi note number 72.

    function get_freq(note){ //note is midi note
    note=note-60;
    var octave=Math.log(2);
    var halftone=octave/12;
    //console.log(note);
    var tone=Math.exp(note*halftone);
    var freq=8000*tone; //C4 Middle C Midi note 60
    return freq;
    }// end get_freq
    

    The sample was converted to a string and coded into the program

    // 8 bit unsigned Piano C4 sampled at 8 kHz
    Piano=
    "\x7f\x80\x80\x7f\x80\x7f\x80\x80\x80\x7f\x80\x7f\x80\x80\x80\x80\x80\x7f\x80\x7f\x80\x7f\x80\x80\x80\x80\x80\x80\x7f\x80\x7f\x80\x7f\x80\x7
    ...
    \x80\x80\x81\x80\x80\x81\x81\x81\x81\x80\x81\x82\x82\x82\x82\x82\x81\x80\x7f~}|||}}~~\x7f"
    ;
    

    The chromatic scale is played by this code:

    k=0;
    var ww = new Waveform(Piano.length);//,{bits:16});
    ww.buffer.set(Piano);
    
    note=60;
    analogWrite(A4, 0.5);
    ww.startOutput(A4,get_freq(note));
    
    // this event doesn't fire unless repeat is true
    ww.on('buffer',function(data) { 
      console.log("B");
      k++;
      if (k>3) ww.stop();
     });
    
    
    ww.on('finish',function(data) { console.log("F");//+data);
    note++;
    k=0;
    if (note>72) note=60;//{
    ww.startOutput(Aout, get_freq(note));//,{repeat:true});
    //}
     });
    

    Discussion

    Other instrument samples are widely available on the Web. (Orchestras)
    The tempo of the notes increases with pitch. How to solve this?
    With only 2 DACs, polyphony is limited. Using PWM can produce synthesized sounds.

    attached files

    Piano1 .js


    1 Attachment

About