Midi Keyboard Recording

# Midipiano.rb
# 9 Dec 2018
# Use a midi keyboard to play a piano tune and record it
# Use midi key :C2 to end recording and play the tune from recorded arrays

# reference code used to build this program
# https://github.com/samaaron/sonic-pi/blob/master/etc/doc/tutorial/11.1-MIDI-In.md

# This Gist by Robin Newman  shows how to add computer keyboard control
# via a Ruby script and
# TCP socket I hope to add this technique to this program and
# use an HTML page instead of the computer keyboard.
# https://www.youtube.com/watch?v=uM4hEw4kju4&feature=youtube
# https://gist.github.com/rbnpi/7e01964ab8110e6df1e6d823bd9c4dcb


def midi2note(n)
  nn=note(n)
  if nn==nil
    #    puts "nil seen",nn
    return nn
  else
    nn= note_info(nn)
    #    puts nn
    nnn=nn.to_s.split(":")
    #  puts nnn
    mmm= nnn[3].chop
    return mmm
  end
end # midi2note

def midichord2note(m) # chords in midi aren't handled well
  puts m
  i=0
  sss=''
  while i<m.length
    sss=sss+midi2note(m[i])+','
    i+=1
  end
  return sss
end
sst=[]
ssv=[]
svt=[]

live_loop :midi_piano do
  use_real_time
  #puts tick,vt
  note, velocity = sync "/midi/q49/0/1/note_on"
  #Use :C2 (37) to end recording and start playback
  if (note<37)
    puts "saveit"
    svt.push(vt)
    # quantize?
    i=0
    while i<svt.length-1
      svt[i]=svt[i+1]-svt[i]
      puts 'svt ',i,svt[i]
      i+=1
    end
    i=0
    while i<sst.length
      use_synth :piano
      play sst[i],amp:ssv[i]/127.0
     # sleep 0.25
      sleep svt[i]
      i+=1
    end
  end
  sst.push(note)
  ssv.push(velocity)
  svt.push(vt)
  puts  midichord2note(sst)
  #synth :piano, note: note
     synth :piano, note: note, amp: velocity / 127.0
      
    end
    

Hi @JoeMac,

that’s very interesting a works surprisingly good! Thanks!

I have been thinking (and did some first attempts) to do that. The interesting issue is hidden in your comment: #quantize. Sooner or later I would like to not only record live sound but also (quantized) Midi input.

So I’ll try to build on your work and go on with these ideas.

Cheers
Martin

Seeing the reference to my previous code written in 2016 spurred me on to update it, as you can see here

Midi Editor

This lets you playback from tracks and record on another one.
The editor has a quantize feature.
Save as a Midi file
You can open the midi file in Musescore and see, edit, play and export the sheet music.
Use the 2.0 version for now 3.0 has just been released and has some problems.

A plug-in (with MS2) that will output a text file of duration and pitch/rest data allows you to pull that info into Sonic Pi. Or you can take the notes and durations in Sonic Pi and build the text file that Musescore with the plugin can read. Look at the .rb programs

writetune