Making Pico Music in a fashion similar to Sonic PI

Posted on
  • There are a number of examples on this site for creating musical sounds. Thank you for the help in creating this post.
    When I bought a Raspberry Pi, I discovered the Sonic PI software that also runs on PC, Mac and Linux.
    Program uses a modified Ruby interpreter.

    Sonic PI

    I wondered if something like Sonic Pi could be implemented using Espruino, at least a small subset.
    Here is a first attempt:

    //music.js
    // 1 Nov 2017
    // Tested on a Pico
    // make music in a fashion similar to Sonic PI
    // http://sonic-pi.net/
    //
    // Hardware
    // Connect an amplified speaker input to ground and the Speaker pin
    // as defined here
    var Speaker=A5; //A9;
    // use this to find a suitable pin
    //analogWrite();
    /*
    Pico pins
    Suitable pins are:
    A0 A1 A2 A3 A5 A6 A7 A8 A9
    A10 A11 A15 B0 B1 B3 B4 B5 B6
    B7 B8 B9 B10 B13 B14 B15
    =undefined
    
    */
    
    var Tempo =1.0; // changes tempo of the music
    
    // define some note lengths
    var Whole=1.0;
    var Half=Whole/2.0;
    var Quart=Half/2.0;
    var Eighth=Quart/2.0;
    
    // Use this table to write the song as a seried of Midi notes,
    // and durations
    // http://www.electronics.dit.ie/staff/tsca­rff/Music_technology/midi/midi_note_numb­ers_for_octaves.htm
    
    // Tune is C4 Major scale C4 is middle C, Midi note 60
    var tune=[[60,Quart],
              [62,Eighth],
              [64,Quart],
              [65,Eighth],
              [null,Half], // a musical rest
              [67,Quart],
              [69,Eighth],
              [71,Quart],
              [72,Eighth]
              ];
    
    
    var octave=Math.log(2);
    var halftone=octave/12;
    
    function freq(f) { 
      if (f===0) digitalWrite(Speaker,0);
      else analogWrite(Speaker, 0.5, { freq: f } );
    }
    function soundoff(){
      digitalWrite(Speaker,0);
    }
    
    function play(note){
      if(note===null)return; // a rest
    note=note-60;
    //console.log(note);
    var tone=Math.exp(note*halftone);
    //console.log(tone);
    freq(261.63*tone); //C4 Middle C Midi note 60
    }//end play
    
    
    
    function wait(a,c){
    var b=getTime();
    if (b>=(a+c)) return b;
    return a;
    }
    
    var a;
    var b;
    var i=0;
    a=getTime();
    //console.log(a);
    setInterval(function () {
       //if(tune[i][0]!==null)
       play(tune[i][0]);
       b=wait(a,tune[i][1]*Tempo);
       if(b!=a){
        a=b;
        soundoff();
        i++;
       }
      if(i>=tune.length) clearInterval();
    }, 10);
    

    1 Attachment

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

Making Pico Music in a fashion similar to Sonic PI

Posted by Avatar for ClearMemory041063 @ClearMemory041063

Actions