MIDI In

In this section we will learn how to connect a MIDI controller to send events into Sonic Pi to control our synths and sounds. Go and grab a MIDI controller such as a keyboard or control surface and let’s get physical!

Connecting a MIDI Controller

Para obtener información de un dispositivo MIDI externo hacia Sonic Pi primero se necesita conectarlo al computador. Usualmente esto será por conexión USB, sin embargo dispositivos más viejos tendrán un conector DIN de 5 pines para los cuales necesitarás hardware adicional del computador para soportar su uso (por ejemplo, algunas tarjetas de sonido usan conectores DIN para MIDI). Una vez conectado el dispositivo, arranca Sonic Pi y observa la sección de IO en el Panel de Preferencias. Deberías ver el dispositivo listado aquí. De lo contrario, intenta con el botón de ‘Reiniciar MIDI’ y mirar si aparece. Si aún no algo, lo siguiente es intentar consultar la configuración de MIDI de tu sistema operativo y ver si allí aparece. Si todo lo anterior falla, tomate la libertad de preguntar en nuestros amigables foros: https://in-thread.sonic-pi.net

Recibiendo Eventos MIDI

Una vez tu dispositivo este conectado, Sonic Pi automaticamente recibirá eventos MIDI. Puedes verlo tú mismo manipulando tu dispositivo MIDI y observando la bitácora cue en la esquina inferior derechade la aplicación, justo abajo del log (si eso no es visible, ve a Preferencias->Editor->Ver & Ocultar y activa caja de ‘Mostrar cue log’). Verás una hilera de eventos como estos:

/midi:nanokey2_keyboard:0:1/note_off  [55, 64]
/midi:nanokey2_keyboard:0:1/note_on   [53, 102]
/midi:nanokey2_keyboard:0:1/note_off  [57, 64]
/midi:nanokey2_keyboard:0:1/note_off  [53, 64]
/midi:nanokey2_keyboard:0:1/note_on   [57, 87]
/midi:nanokey2_keyboard:0:1/note_on   [55, 81]
/midi:nanokey2_keyboard:0:1/note_on   [53, 96]
/midi:nanokey2_keyboard:0:1/note_off  [55, 64]

Once you can see a stream of messages like this, you’ve successfully connected your MIDI device. Congratulations, let’s see what we can do with it!

MIDI Time State

Estos eventos se dividen en dos secciones. En primer lugar está el nombre del evento como /midi:nanokey2_keyboard:0:1/note_on y en segundo lugar están los valores del evento como [18, 62]. Curiosamente, estas son las dos cosas que necesitamos para almacenar la información en Time State. Sonic Pi inserta automáticamente los eventos MIDI entrantes en Time State. Esto significa que puedes get (obtener) el último valor MIDI y también sync para esperar el próximo valor MIDI usando todo lo que aprendimos en la sección 10 de este tutorial.

Controlando efectos (FX)

Now we’ve connected a MIDI device, seen its events in the cue log and discovered that our knowledge of Time State is all we need to work with the events, we can now start having fun. Let’s build a simple MIDI piano:

live_loop :midi_piano do
  note, velocity = sync "/midi:nanokey2_keyboard:0:1/note_on"
  synth :piano, note: note
end

There’s a few things going on in the code above including some issues. Firstly, we have a simple live_loop which will repeat forever running the code between the do/end block. This was introduced in Section 9.2. Secondly, we’re calling sync to wait for the next matching Time State event. We use a string representing the MIDI message we’re looking for (which is the same as was displayed in the cue logger). Notice that this long string is provided to you by Sonic Pi’s autocompletion system, so you don’t have to type it all out by hand. In the log we saw that there were two values for each MIDI note on event, so we assign the result to two separate variables note and velocity. Finally we trigger the :piano synth passing our note.

Now, you try it. Type in the code above, replace the sync key with a string matching your specific MIDI device and hit Run. Hey presto, you have a working piano! However, you’ll probably notice a couple of problems: firstly all the notes are the same volume regardless of how hard you hit the keyboard. This can be easily fixed by using the velocity MIDI value and converting it to an amplitude. Given that MIDI has a range of 0->127, to convert this number to a value between 0->1 we just need to divide it by 127:

live_loop :midi_piano do
  note, velocity = sync "/midi:nanokey2_keyboard:0:1/note_on"
  synth :piano, note: note, amp: velocity / 127.0
end

Update the code and hit Run again. Now the velocity of the keyboard is honoured. Next, let’s get rid of that pesky pause.

Eliminar la latencia

Before we can remove the pause, we need to know why it’s there. In order to keep all the synths and FX well-timed across a variety of differently capable CPUs, Sonic Pi schedules the audio in advance by 0.5s by default. (Note that this added latency can be configured via the fns set_sched_ahead_time! and use_sched_ahead_time). This 0.5s latency is being added to our :piano synth triggers as it is added to all synths triggered by Sonic Pi. Typically we really want this added latency as it means all synths will be well timed. However, this only makes sense for synths triggered by code using play and sleep. In this case, we’re actually triggering the :piano synth with our external MIDI device and therefore don’t want Sonic Pi to control the timing for us. We can turn off this latency with the command use_real_time which disables the latency for the current thread. This means you can use real time mode for live loops that have their timing controlled by syncing with external devices, and keep the default latency for all other live loops. Let’s see:

live_loop :midi_piano do
  use_real_time
  note, velocity = sync "/midi:nanokey2_keyboard:0:1/note_on"
  synth :piano, note: note, amp: velocity / 127.0
end

Update your code to match the code above and hit Run again. Now we have a low latency piano with variable velocity coded in just 5 lines. Wasn’t that easy!

Manos a la Obra

Finally, as our MIDI events are going straight into the Time State, we can also use the get fn to retrieve the last seen value. This doesn’t block the current thread and returns nil if there’s no value to be found (which you can override by passing a default value - see the docs for get). Remember that you can call get in any thread at any time to see the latest matching Time State value. You can even use time_warp to jump back in time and call get to see past events…

Now You are in Control

Lo mejor es que ahora puedes usar las mismas estructuras de código para sync (sincronizar) y get (obtener) información MIDI de cualquier dispositivo MIDI y hacer lo que quieras con los valores. ¡Ahora puedes elegir lo que hará tu dispositivo MIDI!