Outils pour utilisateurs

Outils du site


issue124:python

Last month, I gave you some basic information about the GPIOZERO library in preparation for the music box program that uses the RPi, the MCP3008 from last month, three potentiometers and a number of switches to make a simple music player. The core of the project is the Fluidsynth program. Michael Horne was kind enough to let me talk about his project. The original project can be found at http://www.recantha.co.uk/blog/?p=14818 and his code is at https://github.com/recantha/musicbox. Michael’s project includes a case, amplifier and speaker, but I’m not going to deal with those, since this is a discussion on using the RPi. I’ll leave those items to you to figure out. I’m using the HDMI audio out and it works just fine, with the exception of being tethered to the monitor by the HDMI cable.

Le mois dernier, je vous ai donné des informations de base sur la bibliothèque GPIOZERO en préparation du programme de boîte à musique qui utilise le RPi, le MCP3008 du mois dernier, trois potentiomètres et un certain nombre d'interrupteurs pour faire un instrument de musique simple. Le cœur du projet est le programme Fluidsynth. Michaël Horne a eu la grande amabilité de me laisser parler de son projet. Le projet original peut être trouvé à http://www.recantha.co.uk/blog/?p=14818 et son code est sur https://github.com/recantha/musicbox.

Le projet de Michaël comprend un boîtier, un amplificateur et un haut-parleur, mais je ne m'en suis pas préoccupé, car il s'agit ici de l'utilisation du RPi. Je vous laisserai ces sujets-là. J'utilise la sortie audio HDMI et tout marche bien, sauf qu'elle est attachée à l'écran par le câble HDMI.

The first thing you need to do is install Fluidsynth from the Add/Remove program on the RPi. Next, you need to add the pyfluidsynth python library. You can do this using pip in a terminal. pip install pyfluidsynth I’m going to assume that you installed the GPIOZERO library that we used last month. Hopefully, you still have the MCP3008 Analogue to Digital converter wired up from last month’s potentiometer project. If not, all is not lost. You can use the Fritzing diagram below.

La première chose à faire est d'installer Fluidsynth à partir du programme Ajouter/Supprimer du RPi. Ensuite, vous devez ajouter la bibliothèque Python pyfluidsynth. Vous pouvez le faire en utilisant pip dans un terminal.

pip install pyfluidsynth

Je pars du principe que vous avez installé la bibliothèque GPIOZERO le mois dernier.

J'espère que vous avez toujours le convertisseur analogique/numérique MCP3008 câblé comme pour le projet de potentiomètre du mois précédent. Sinon, tout n'est pas perdu. Vous pouvez utiliser le schéma Fritzing ci-contre.

Parts List For this project you will need: • Raspberry Pi • Breadboard • Jumpers • MCP3008 • 1 LED • 1 220 Ohm Resistor • 3 10K potentiometers • 9 momentary pushbuttons The potentiometers all have one lead that connects to ground, one that connects to 3.3vDC and the wiper connects to the MCP3008 pins 1, 2 and 3. The switches all have one lead connecting to ground and the others connect to GPIO pins 5, 23, 13, 6, 12, 16, 19, 20 and 21 (physical pins 29, 16, 33, 31, 32, 36, 35, 38 and 40) . The LED cathode connects to ground and the anode connects to one side of the 220 ohm resistor while the other side of the resistor connects to GPIO pin 24 (physical pin 18)

Liste de pièces

Pour ce projet, vous avez besoin :

• du Raspberry Pi, • d'une plaque d'essai, • de cavaliers, • du MCP3008, • d'une LED, • d'une résistance de 220 Ω, • de 3 potentiomètres de 10 kΩ, • de 9 boutons-poussoirs.

Les potentiomètres ont tous une patte reliée à la masse, une au 3,3 vDC et le curseur connecté aux bornes 1, 2, 3 du MCP3008. Les poussoirs ont tous une sortie branchée à la masse, et les autres connectées aux picots 5, 23, 13, 6, 12, 16, 19, 20 et 21 du GPIO (bornes physiques 29, 16, 33, 31, 32, 36, 35, 38 et 40). La cathode de la LED est connectée à la masse et l'anode à une des extrémités de la résistance de 220 Ω, tandis que l'autre bout de la résistance est relié à la borne 24 du GPIO (picot physique 18).

The Code The code is fairly long, so I won’t include it all here. I will, however, pull out various snippets to discuss some of the less mundane segments. I also will be bouncing around within the code, to point out various things. I do strongly suggest pulling the full code from Michael’s github page. It also includes sound fonts for you to test with. Of course, the very first thing that Michael does is his imports… from future import division from gpiozero import Button, MCP3008, LED import glob import os import re import time import fluidsynth The only library that you might not be familiar with is the ‘glob’ library. This library allows the matching of filenames to a pattern. It’s simple but very powerful.

Le code

Le code est assez long ; aussi, je ne vais pas tout inclure ici. Cependant, j'en montrerai divers extraits pour présenter certains des segments les moins usuels. Je me baladerai aussi dans le code pour mettre en avant certains points. Je suggère fortement que vous récupériez le code de la page github de Michaël. Il comprend aussi des polices sonores pour le tester.

Bien sûr, la première chose que fait Michaël, ce sont les imports :

from future import division

from gpiozero import Button, MCP3008, LED

import glob import os import re import time import fluidsynth

La seule bibliothèque qui pourrait ne pas vous être connue est « glob ». Cette bibliothèque vous permet de faire correspondre les noms de fichiers à un modèle. C'est simple mais très puissant.

Next he loads up FluidSynth. # Start up the Synth and load the sound font fs = fluidsynth.Synth() fs.start(driver='alsa') Now, here is the button definition section. Remember, the pin numbers refer to the GPIO pin, not the physical pin number. # Set-up buttons for reset and shutdown button_reset = Button(5) button_shutdown = Button(23) # Set-up buttons for keyboard input thumb_bottom = Button(13) thumb_top = Button(6) thumb_right = Button(12) index_finger = Button(16) middle_finger = Button(19) ring_finger = Button(20) pinky_finger = Button(21) Now he defines which potentiometer is on which channel of the MCP3008. (I added the comments in this section.)

Ensuite, il charge FluidSynth.

# Démarrage de Synth et chargement de la police sonore

fs = fluidsynth.Synth() fs.start(driver='alsa')

Maintenant, voici la section de définition des poussoirs. Souvenez-vous que les numéros de picot correspondent aux picots du GPIO, et pas aux numéros des picots physiques.

# Paramétrage des poussoirs pour la remise à zéro et l'arrêt

button_reset = Button(5) button_shutdown = Button(23)

# Paramétrage des poussoirs du clavier

thumb_bottom = Button(13) thumb_top = Button(6) thumb_right = Button(12) index_finger = Button(16) middle_finger = Button(19) ring_finger = Button(20) pinky_finger = Button(21)

# Define potentiometers pot0 = MCP3008(channel=2) # Volume Control pot1 = MCP3008(channel=1) # Instrument Select pot2 = MCP3008(channel=0) # Additor The load_soundfonts() routine (top right) will walk through the soundfonts directory, getting the file names of the soundfonts into a usable list. Michael includes 15 sample soundfonts in his source files. This next routine (previous page, bottom right) will set the instrument for the synth based on the value of potentiometer #1 which as we saw above is on channel number 1 of the MCP3008. Here is where Michael sets up the actions for each of the music buttons. Basically, there is a ‘when_pressed’ and a ‘when_released’ action that calls a routine when the action is performed.

# Définition des potentiomètres

pot0 = MCP3008(channel=2) # Contrôle du volume.

pot1 = MCP3008(channel=1) # Sélection de l'instrument.

pot2 = MCP3008(channel=0) # Changement d'octave (« Additor »).

La routine load_soundfonts() (en haut à droite) va parcourir la bibliothèque soundfonts, en récupérant les noms des fichiers de polices sonores dans une liste utilisable. Les fichiers sources de Michaël comprennent 15 échantillons de polices sonores.

La routine suivante (page précédente, en bas à droite) paramétrera l'instrument pour la synthèse sur la base de la valeur du potentiomètre n° 1 qui, comme nous le voyons plus haut, est le canal n° 1 du MCP3008.

C'est ici que Michaël paramètre les actions pour chacun des poussoirs musicaux. De base, il y a les actions « when_pressed » (si appuyé) et « when_released » (si relâché) qui appellent une routine quand l'action est effectuée.

# Assign actions to when_pressed for each button thumb_bottom.when_pressed = thumb_bottom_start thumb_bottom.when_released = thumb_bottom_stop thumb_right.when_pressed = thumb_right_start thumb_right.when_released = thumb_right_stop thumb_top.when_pressed = thumb_top_start thumb_top.when_released = thumb_top_stop index_finger.when_pressed = index_finger_start index_finger.when_released = index_finger_stop middle_finger.when_pressed = middle_finger_start middle_finger.when_released = middle_finger_stop ring_finger.when_pressed = ring_finger_start ring_finger.when_released = ring_finger_stop pinky_finger.when_pressed = pinky_finger_start pinky_finger.when_released = pinky_finger_stop Glancing at index finger button action routine sets we see what's shown top right…

# Assignation des actions quand un des poussoirs est appuyé

thumb_bottom.when_pressed = thumb_bottom_start thumb_bottom.when_released = thumb_bottom_stop thumb_right.when_pressed = thumb_right_start thumb_right.when_released = thumb_right_stop thumb_top.when_pressed = thumb_top_start thumb_top.when_released = thumb_top_stop index_finger.when_pressed = index_finger_start index_finger.when_released = index_finger_stop middle_finger.when_pressed = middle_finger_start middle_finger.when_released = middle_finger_stop ring_finger.when_pressed = ring_finger_start ring_finger.when_released =ring_finger_stop pinky_finger.when_pressed = pinky_finger_start pinky_finger.when_released = pinky_finger_stop

En examinant ce que fait la routine d'action du poussoir de l'index, nous voyons ce qui est montré en haut à droite.

The way things work on a synth is that when a note key is pressed a noteon event is called and when it is released, a noteoff event is then called. (That is why sometimes when playing a midi file on a computer you get notes that seem to be accidentally left on, playing forever. The noteoff event is never read by the soft synth.) By doing this, you could play chords. These are mostly repeated for each of the buttons that control the notes to be played. Also notice that the value of the additor is added to the note itself. This allows you to do various octaves of the seven notes. In the following lines, Michael sets the note definitions for each button.

La façon dont les choses fonctionnent sur un synthétiseur est que, quand on appuie sur une touche, un événement noteon est appelé et quand elle est relâchée, un événement noteoff est appelé. (C'est pourquoi, parfois, quand vous écoutez un fichier midi sur un ordinateur, vous avez des notes qui semblent être accidentellement en appui permanent, les laissant jouer sans fin. L'événement noteoff n'est jamais lu par le synthétiseur logiciel.) En faisant cela, vous pouvez jouer des cordes. Elles sont généralement répétées pour chacun des poussoirs qui contrôlent les notes à jouer. Notez aussi que la valeur de l'« additor » est ajoutée à la note elle-même. Ceci vous permet de disposer des sept notes sur plusieurs octaves.

Dans les lignes suivantes, Michaël définit la note de chaque poussoir.

thumb_bottom_note = 54 thumb_right_note = 56 thumb_top_note = 58 index_finger_note = 60 middle_finger_note = 62 ring_finger_note = 64 pinky_finger_note = 66 I think that this gives you a basic understanding of what the code does, so you can continue on and play with the project. Once again, a huge thanks to Michael for this project. Until next time, have fun.

thumb_bottom_note = 54 thumb_right_note = 56 thumb_top_note = 58 index_finger_note = 60 middle_finger_note = 62 ring_finger_note = 64 pinky_finger_note = 66

Je pense que ceci vous donne une compréhension de base de ce que fait le code ; aussi, vous pouvez poursuivre et jouer avec le projet.

Une fois encore, un grand merci à Michaël pour ce projet.

Jusqu'à la prochaine fois, amusez-vous bien.

issue124/python.txt · Dernière modification : 2017/08/30 11:42 de auntiee