FLOSS Manuals

 English |  Español |  Français |  Italiano |  Português |  Русский |  Shqip

CSOUND Español

READING MIDI FILES LECTURA DE ARCHIVOS MIDI

Instead of using either the standard Csound score or live midi events as input for a orchestra Csound can read a midi file and use the data contained within it as if it were a live midi input.

En lugar de usar la puntuación de Csound estándar o vivir los eventos midi como entrada para una orquesta Csound puede leer un archivo midi y utilizar los datos contenidos en ella como si se tratara de una entrada midi en directo.

The command line flag to instigate reading from a midi file is '-F' followed by the name of the file or the complete path to the file if it is not in the same directory as the .csd file. Midi channels will be mapped to instrument according to the rules and options discussed in Triggering Instrument Instances and all controllers can be interpretted as desired using the techniques discussed in Working with Controllers. One thing we need to be concerned with is that without any events in our standard Csound score our performance will terminate immedately. To circumvent this problem we need some sort of dummy event in our score to fool Csound into keeping going until our midi file has completed. Something like the following, placed in the score, is often used.

El indicador de línea de comandos para instigar la lectura de un archivo midi es -F seguido por el nombre del archivo o la ruta completa al archivo si no está en el mismo directorio que el archivo .csd. Los canales Midi se asignarán al instrumento de acuerdo con las reglas y opciones discutidas en Disparando Instancias de Instrumento y todos los controladores pueden ser interpretados como se desee usando las técnicas discutidas en Trabajando con Controladores. Una cosa que debemos preocuparnos es que sin ningún evento en nuestra puntuación Csound estándar nuestro desempeño terminará inmediatamente. Para eludir este problema necesitamos algún tipo de evento ficticio en nuestra partitura para engañar a Csound para que continúe hasta que nuestro archivo midi se haya completado. Algo como el siguiente, colocado en la partitura, se utiliza a menudo.

 

f 0 3600

This dummy 'f' event will force Csound to wait for 3600 second (1 hour) before terminating performance. It doesn't really matter what number of seconds we put in here, as long as it is more than the number of seconds duration of the midi file. Alternatively a conventional 'i' score event can also keep performance going; sometimes we will have, for example, a reverb effect running throughout the performance which can also prevent Csound from terminating. Performance can be interrupted at any time by typing ctrl+c in the terminal window.

Este evento ficticio forzará a Csound a esperar 3600 segundos (1 hora) antes de terminar el rendimiento. Realmente no importa qué número de segundos ponemos aquí, siempre y cuando sea más que el número de segundos de duración del archivo midi. Alternativamente, un evento de puntuación i convencional también puede mantener el rendimiento en marcha; A veces tendremos, por ejemplo, un efecto de reverberación a lo largo del rendimiento que también puede evitar que Csound termine. El rendimiento se puede interrumpir en cualquier momento escribiendo ctrl c en la ventana del terminal.

The following example plays back a midi file using Csound's 'fluidsynth' family of opcodes to facilitate playing soundfonts (sample libraries). For more information on these opcodes please consult the Csound Reference Manual. In order to run the example you will need to download a midi file and two (ideally contrasting) soundfonts. Adjust the references to these files in the example accordingly. Free midi files and soundfonts are readily available on the internet. I am suggesting that you use contrasting soundfonts, such as a marimba and a trumpet, so that you can easily hear the parsing of midi channels in the midi file to different Csound instruments. In the example channels 1,3,5,7,9,11,13 and 15 play back using soundfont 1 and channels 2,4,6,8,10,12,14 and 16 play back using soundfont 2. When using fluidsynth in Csound we normally use an 'always on' instrument to gather all the audio from the various soundfonts (in this example instrument 99) which also conveniently keeps performance going while our midi file plays back.

El siguiente ejemplo reproduce un archivo MIDI utilizando la familia de opcodes Csounds fluidsynth para facilitar la reproducción de soundfonts (bibliotecas de ejemplo). Para obtener más información sobre estos opcodes, consulte el Manual de Referencia de Csound. Para ejecutar el ejemplo tendrás que descargar un archivo midi y dos fuentes de sonido (idealmente contrastantes). Ajuste las referencias a estos archivos en el ejemplo en consecuencia. Los archivos midi gratis y soundfonts están fácilmente disponibles en Internet. Estoy sugiriendo que utilice soundfonts contrastantes, como una marimba y una trompeta, para que pueda escuchar fácilmente el análisis de canales midi en el archivo midi a diferentes instrumentos Csound. En los canales de ejemplo 1,3,5,7,9,11,13 y 15 reproducir utilizando soundfont 1 y canales 2,4,6,8,10,12,14 y 16 reproducir utilizando soundfont 2. Cuando se utiliza fluidsynth En Csound utilizamos normalmente un instrumento siempre para recopilar todo el audio de las distintas fuentes de sonido (en este instrumento de ejemplo 99) que también mantiene conveniente el rendimiento mientras nuestro archivo midi se reproduce.

  EXAMPLE 07D01_ReadMidiFile.csd 

<CsoundSynthesizer>

<CsOptions>
;'-F' flag reads in a midi file
-F AnyMIDIfile.mid
</CsOptions>

<CsInstruments>
;Example by Iain McCurdy

sr = 44100
ksmps = 32
nchnls = 1
0dbfs = 1

sr = 44100
ksmps = 32
nchnls = 2

giEngine     fluidEngine; start fluidsynth engine
; load a soundfont
iSfNum1      fluidLoad          "ASoundfont.sf2", giEngine, 1
; load a different soundfont
iSfNum2      fluidLoad          "ADifferentSoundfont.sf2", giEngine, 1
; direct each midi channels to a particular soundfonts
             fluidProgramSelect giEngine, 1, iSfNum1, 0, 0
             fluidProgramSelect giEngine, 3, iSfNum1, 0, 0
             fluidProgramSelect giEngine, 5, iSfNum1, 0, 0
             fluidProgramSelect giEngine, 7, iSfNum1, 0, 0
             fluidProgramSelect giEngine, 9, iSfNum1, 0, 0
             fluidProgramSelect giEngine, 11, iSfNum1, 0, 0
             fluidProgramSelect giEngine, 13, iSfNum1, 0, 0
             fluidProgramSelect giEngine, 15, iSfNum1, 0, 0
             fluidProgramSelect giEngine, 2, iSfNum2, 0, 0
             fluidProgramSelect giEngine, 4, iSfNum2, 0, 0
             fluidProgramSelect giEngine, 6, iSfNum2, 0, 0
             fluidProgramSelect giEngine, 8, iSfNum2, 0, 0
             fluidProgramSelect giEngine, 10, iSfNum2, 0, 0
             fluidProgramSelect giEngine, 12, iSfNum2, 0, 0
             fluidProgramSelect giEngine, 14, iSfNum2, 0, 0
             fluidProgramSelect giEngine, 16, iSfNum2, 0, 0

  instr 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 ; fluid synths for channels 1-16
iKey         notnum                 ; read in midi note number
iVel         ampmidi            127 ; read in key velocity
; create a note played by the soundfont for this instrument
             fluidNote          giEngine, p1, iKey, iVel
  endin

  instr 99 ; gathering of fluidsynth audio and audio output
aSigL, aSigR fluidOut           giEngine      ; read all audio from soundfont
             outs               aSigL, aSigR  ; send audio to outputs
  endin
</CsInstruments>

<CsScore>
i 99 0 3600 ; audio output instrument also keeps performance going
e
</CsScore>

<CsoundSynthesizer>

Midi file input can be combined with other Csound inputs from the score or from live midi and also bear in mind that a midi file doesn't need to contain midi note events, it could instead contain, for example, a sequence of controller data used to automate parameters of effects during a live performance.

La entrada de archivos Midi se puede combinar con otras entradas de Csound de la partitura o de midi en directo y también tener en cuenta que un archivo midi no necesita contener eventos de notas MIDI, podría contener, por ejemplo, una secuencia de datos de controlador utilizada para automatizar Parámetros de efectos durante una actuación en vivo.

Rather than to directly play back a midi file using Csound instruments it might be useful to import midi note events as a standard Csound score. This way events could be edited within the Csound editor or several scores could be combined. The following example takes a midi file as input and outputs standard Csound .sco files of the events contained therein. For convenience each midi channel is output to a separate .sco file, therefore up to 16 .sco files will be created. Multiple .sco files can be later recombined by using #include... statements or simply by using copy and paste.

En lugar de reproducir directamente un archivo MIDI utilizando instrumentos Csound, puede ser útil importar eventos de notas MIDI como una puntuación Csound estándar. De esta manera los eventos podrían ser editados dentro del editor Csound o se podrían combinar varias puntuaciones. El siguiente ejemplo toma un archivo MIDI como entrada y genera archivos .sco estándar de Csound de los eventos contenidos en él. Para mayor comodidad, cada canal midi se envía a un archivo .sco separado, por lo que se crearán hasta 16 archivos .sco. Múltiples archivos .sco se pueden recombinar más tarde usando la sentencia #include... or simplemente mediante copiado y pegado.

The only tricky aspect of this example is that note-ons followed by note-offs need to be sensed and calculated as p3 duration values. This is implemented by sensing the note-off by using the release opcode and at that moment triggering a note in another instrument with the required score data. It is this second instrument that is responsible for writing this data to a score file. Midi channels are rendered as p1 values, midi note numbers as p4 and velocity values as p5.

El único aspecto difícil de este ejemplo es que note-ons seguido por nota-offs necesitan ser detectados y calculados como valores de duración p3. Esto se lleva a cabo detectando la nota apagada usando el código de liberación y en ese momento activando una nota en otro instrumento con los datos de puntuación requeridos. Es este segundo instrumento el que se encarga de escribir estos datos en un archivo de puntuación. Los canales MIDI se representan como valores p1, números de nota midi como p4 y valores de velocidad como p5.

  EXAMPLE 07D02_MidiToScore.csd

<CsoundSynthesizer>

<CsOptions>
; enter name of input midi file
-F InputMidiFile.mid
</CsOptions>

<CsInstruments>
; Example by Iain McCurdy

;ksmps needs to be 10 to ensure accurate rendering of timings
ksmps = 10

massign 0,1

  instr 1
iChan       midichn
iCps        cpsmidi            ; read pitch in frequency from midi notes
iVel        veloc	0, 127 ; read in velocity from midi notes
kDur        timeinsts          ; running total of duration of this note
kRelease    release            ; sense when note is ending
 if kRelease=1 then            ; if note is about to end
;           p1  p2  p3    p4     p5    p6
event "i",  2,  0, kDur, iChan, iCps, iVel ; send full note data to instr 2
 endif
  endin

  instr 2
iDur        =        p3
iChan       =        p4
iCps        =        p5
iVel        =        p6
iStartTime  times        ; read current time since the start of performance
; form file name for this channel (1-16) as a string variable
SFileName   sprintf  "Channel%d.sco",iChan
; write a line to the score for this channel's .sco file
            fprints  SFileName, "i%d\\t%f\\t%f\\t%f\\t%d\\n",\
	                         iChan,iStartTime-iDur,iDur,iCps,iVel
  endin

</CsInstruments>

<CsScore>
f 0 480 ; ensure this duration is as long or longer that duration of midi file
e
</CsScore>

</CsoundSynthesizer>

The example above ignores continuous controller data, pitch bend and aftertouch. The second example on the page in the Csound Manual for the opcode fprintks renders all midi data to a score file.

El ejemplo anterior ignora los datos continuos del controlador, pitch bend y aftertouch. El segundo ejemplo en la página en el Manual Csound para el opcode fprintks procesa todos los datos MIDI en un archivo de puntuación.

 

There has been error in communication with Booktype server. Not sure right now where is the problem.

You should refresh this page.