Outils pour utilisateurs

Outils du site


issue190:python

I have an embarrassing confession to make. Between issues with the weather here in central Texas, deadlines on book chapters, support and testing issues, I didn’t start thinking about this issue of FCM until February the first. I didn’t even get around to starting researching or writing the demo programs until the second. However, once I get this all written down, I truly believe I can hold my head up high and be proud of this issue’s article. Speaking of which, let’s get started. You might notice the title of this article. Yes, it DOES have to do with Python and missing beeps. For years, my computer has not had a built-in speaker, so the beep that I would normally rely on to get the user’s attention didn’t function the way I was used to. For a while, I tried in vain to get the blasted BEEP to respond, then something would come up and I’d have to abandon it for a while. Each time, the “a while” became longer and longer, and it eventually got lost in the shuffle. Until today.

J'ai une confession embarrassante à faire. Entre les problèmes de météo dans le centre du Texas, les échéances des chapitres du livre, les problèmes de support et de tests, je n'ai pas commencé à penser à ce numéro du FCM avant le 1er février. Je n'ai même pas commencé à faire des recherches ou à écrire les programmes de démonstration avant le 2 février. Cependant, une fois que j'aurai tout écrit, je crois vraiment que je pourrai garder la tête haute et être fier de l'article de ce numéro.

Sur ce, commençons. Vous avez peut-être remarqué le titre de cet article. Oui, il a bien un rapport avec Python et les « bips » manquants. Pendant des années, mon ordinateur n'a pas eu de haut-parleur intégré, donc le bip sur lequel je comptais normalement pour attirer l'attention de l'utilisateur ne fonctionnait pas comme j'en avais l'habitude. Pendant un certain temps, j'ai essayé en vain d'obtenir une réponse de ce maudit BIP, puis quelque chose se produisait et je devais l'abandonner pour un moment. À chaque fois, le « un moment » devenait de plus en plus long, et il finissait par se perdre dans la masse. Jusqu'à aujourd'hui.

I tried to go back – to find a way to get the bleep working – and still no luck. So I decided to give up on attempting to force a bleep tone out of my speakers, and started looking for an alternative method, one that would not force any of my users to have to install a ton of libraries before they could use a program of mine. I found a library named (of all things) Beepy. It is a pretty simple, lightweight library, and it has only one dependency. So I gave it a try. The instructions said to install it via pip; I’m lucky that my Python installs don’t require using a “3” at the end of my Python and Pip commands, so I forget that many of you aren’t quite that lucky. So if you can use just a “pip”, convert it mentally when you see “pip3”. pip3 install beepy I pulled up my ptpython REPL… The instructions say… import beepy beep(sound=1) That’s easy enough even for me to follow. Unfortunately, when I did that, nothing happened – other than an error message. Traceback (most recent call last): File “<stdin>”, line 1, in <module> NameError: name 'beep' is not defined name 'beep' is not defined »>

J'ai essayé de revenir en arrière - pour trouver un moyen de faire fonctionner le bip - et toujours pas de chance. J'ai donc décidé d'abandonner l'idée d'obliger un bip à sortir de mes haut-parleurs, et j'ai commencé à chercher une méthode alternative, qui n'obligerait pas mes utilisateurs à installer une tonne de bibliothèques avant de pouvoir utiliser un de mes programmes. J'ai trouvé une bibliothèque nommée (qui l'eut cru ?!) Beepy. C'est une bibliothèque assez simple, légère, et elle n'a qu'une seule dépendance. Je l'ai donc essayée. Les instructions disaient de l'installer via pip ; par chance, mes installations de Python ne nécessitent pas l'utilisation d'un « 3 » à la fin de mes commandes Python et Pip, mais j'oublie que beaucoup d'entre vous n'ont pas cette chance. Donc si vous pouvez seulement utiliser « pip », convertissez-le mentalement quand vous voyez « pip3 ».

pip3 install beepy

J'ai lancé mon REPL ptpython… Les instructions disent :

import beepy beep(sound=1)

C'est assez facile à suivre, même pour moi. Malheureusement, quand j'ai fait ça, rien ne s'est passé, à part un message d'erreur.

Traceback (appel le plus récent en dernier) :

File "<stdin>", line 1, in <module>

NameError: name 'beep' is not defined

name 'beep' is not defined

I double checked the documentation (what little there is), and the instructions still read the same. So I thought maybe there was a change in the program and the documentation didn’t get updated, so I scratched multiple body parts and decided I’d take a look at the output of the dir() function. »> dir(beepy) ['builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'path', 'spec', 'beep', 'make_sound'] There was the command beep, so I knew that there were simply two ways to make it work. I could try from beepy import beep beep(sound=1) And there it was! The sound of life! That is simple enough for me to include and code – if I wanted to get the user’s attention. But what about the other option? import beepy beepy.beep(sound=1) So, there it was, a teachable moment for us all. I read down the rest of the instructions and found the rest of the commands. sound argument takes either integers (1-7) or string (from the list below) as argument. Following are the mappings for the numbers: 1 : 'coin', 2 : 'robot_error', 3 : 'error', 4 : 'ping', 5 : 'ready', 6 : 'success', 7 : 'wilhelm' Hmmm. Only 7 options. I tried all 7 sounds and, while they worked, I wasn’t really impressed. Given the fact that the last release was in 2019, I thought there might be a better solution.

J'ai revérifié la documentation (le peu qu'il y a), et les instructions sont toujours les mêmes. J'ai donc pensé qu'il y avait peut-être eu un changement dans le programme et que la documentation n'avait pas été mise à jour ; alors je me suis gratté plusieurs parties du corps et j'ai décidé de jeter un coup d'œil à la sortie de la fonction dir() :

dir(beepy)

['builtins', 'cached', 'doc', 'file', 'loader', 'name', 'package', 'path', 'spec', 'beep', 'make_sound']

Il y avait la commande beep, donc je savais qu'il y avait simplement deux façons de la faire fonctionner. Je pouvais essayer :

from beepy import beep beep(sound=1)

Et voilà ! On a tous pu apprendre quelque chose ! C'est assez simple à inclure et à coder pour moi, si je voulais attirer l'attention de l'utilisateur. Mais qu'en est-il de l'autre option ?

import beepy beepy.beep(sound=1)

Et voilà, c'était un moment d'apprentissage pour nous tous. J'ai lu le reste des instructions et j'ai trouvé le reste des commandes.

L'argument sound prend comme argument soit des entiers (1-7), soit des chaînes (de la liste ci-dessous).

Voici les correspondances pour les nombres : 1 : 'coin', 2 : 'robot_error', 3 : 'error', 4 : 'ping', 5 : 'ready', 6 : 'success', 7 : 'wilhelm'.

Hmmm. Seulement 7 options. J'ai essayé les 7 sons et, bien qu'ils aient fonctionné, je n'ai pas été vraiment impressionné. Compte tenu du fait que la dernière version date de 2019, je me suis dit qu'il y avait peut-être une meilleure solution.

Since beepy had only one dependency, I thought I’d try looking at that for something easier and with a bit more options. That dependency is a library called simpleaudio. I ran a search on the Internet and got their github address. https://github.com/hamiltron/py-simple-audio. I was excited again. At least until I read the last release date. 2019. ARRGH! However, at least there was some documentation. There was still light at the end of the tunnel, and I prayed that it wasn’t a freight train. I called up the documentation url (https://simpleaudio.readthedocs.io/en/latest/) and started digging in. The first thing they show is a quick function check. Ok. I can do that. import simpleaudio.functionchecks as fc fc.LeftRightCheck.run() I thought I’d hear something like “Right speaker” coming out of the speakers, but I was happy to hear a piano note coming out of one of the speakers and, a moment later, the same note but an octave higher out of the other. I started to see some possibilities. I kept reading on. I moved through the documentation, seeing that, yes, there is a way to make simple beeps, but not so simply… But, I found what I knew had to be there. A way to play audio files, .wav files specifically. While I’m not a huge fan of .wav files, it would do the trick and, if I absolutely had to, there are plenty of websites that have free .wav files just for the purpose of embedding into someone’s program. So I tried it (I still had ptpython running). Code is shown top right.

Puisque beepy n'avait qu'une seule dépendance, j'ai pensé que je pourrais essayer d'y chercher quelque chose de plus simple et avec un peu plus d'options. Cette dépendance est une bibliothèque appelée simpleaudio. J'ai fait une recherche sur Internet et j'ai trouvé leur adresse github. https://github.com/hamiltron/py-simple-audio. J'étais à nouveau enthousiaste. Au moins jusqu'à ce que je lise la dernière date de sortie. 2019. ARRGH ! Cependant, au moins il y avait de la documentation. Il y avait encore de la lumière au bout du tunnel, et je priais pour que ce ne soit pas un train de marchandises. J'ai appelé l'URL de la documentation (https://simpleaudio.readthedocs.io/en/latest/) et j'ai commencé à lire. La première chose qui est montrée est une vérification rapide des fonctions. Ok. Je peux le faire.

import simpleaudio.functionchecks as fc

fc.LeftRightCheck.run()

Je pensais entendre quelque chose comme « Right speaker » (haut-parleur droit) sortant des haut-parleurs, mais j'ai été heureux d'entendre une note de piano sortir d'un des haut-parleurs et, un instant plus tard, la même note mais une octave plus haut sortir de l'autre. Je commençais à entrevoir quelques possibilités. J'ai continué à lire.

J'ai parcouru la documentation, voyant que, oui, il y avait un moyen de faire des bips simples, mais pas si simplement… Mais j'ai trouvé ce que je savais devoir être là. Un moyen de lire des fichiers audio, plus précisément des fichiers .wav. Bien que je ne sois pas un grand fan des fichiers .wav, cela ferait l'affaire et, si je devais absolument le faire, il y a beaucoup de sites Web qui ont des fichiers .wav gratuits juste pour les intégrer dans un programme. Je l'ai donc essayé (j'avais toujours ptpython en cours d'exécution). Le code est affiché en haut à droite.

I had just found one of those “meant to be embedded” files and downloaded it to my desktop. I copied the code block into the REPL and changed the example path to my real path and, low and behold, it worked as advertised. The first time! I dug in a bit deeper and found the other thing I wanted. The ability to create a simple tone or two on demand. However, the sample and this part of documentation was all about using numpy to generate the wave forms. This seemed to be a little bit more than I was willing to commit to, but I gave it a try anyway, since the REPL was still up (middle right). Well, that is very familiar to a guy who spent 6 years in the school band. If there were only two things I learned in High School, it was music and computers. So the three lines simply give the frequencies of a concert A4, a C# and an E. The next part sort-of made sense and I’m not a big numpy user. Basically, after setting the sample rate, and the duration of any note, numpy generates an array of values (bottom right). The next bit of code (below) creates numpy arrays containing the values for the sine waves of the three notes.

Je venais de trouver un de ces fichiers « destinés à être intégrés » et je l'ai téléchargé sur mon bureau. J'ai copié le bloc de code dans le REPL et j'ai remplacé le chemin d'accès de l'exemple par mon chemin d'accès réel et, comme par hasard, cela a fonctionné comme prévu. La première fois !

Je venais de trouver l'un de ces fichiers « à intégrer » et l'ai téléchargé sur mon bureau. J'ai copié le bloc de code dans le REPL et j'ai changé le chemin de l'exemple à mon vrai chemin et, surprise, il fonctionnait comme attendu. La première fois !

J'ai creusé un peu plus profondément et j'ai trouvé l'autre chose que je voulais. La possibilité de créer un ou deux sons simples à la demande. Cependant, l'échantillon et cette partie de la documentation concernaient l'utilisation de numpy pour générer des formes d'onde. Cela semblait être un peu plus que ce que j'étais prêt à faire, mais j'ai quand même essayé, puisque le REPL était toujours en place (au milieu à droite).

Eh bien, c'est très familier pour un gars qui a passé 6 ans dans la fanfare de l'école. S'il n'y a que deux choses que j'ai apprises au lycée, c'est la musique et les ordinateurs. Les trois lignes donnent simplement les fréquences d'un La4, d'un Do# et d'un Mi de concert. La partie suivante est plus ou moins logique et je ne suis pas un grand utilisateur de numpy. En gros, après avoir défini la fréquence d'échantillonnage et la durée de chaque note, numpy génère un tableau de valeurs (en bas à droite).

Le bout de code suivant (ci-dessous) crée des tableaux numpy contenant les valeurs des ondes sinusoïdales des trois notes.

Then, this code (next page, top left) will “bundle up” all the notes and normalize them into a single numpy array. Then we feed the audio data into the playbuffer and wait for it to be done (top right). Knowing that I couldn’t have made any typos, since I copied the code directly from the documentation, I pressed the <enter> key after the last line, waiting to be presented with a three note chord, one note at a time. However, what I got was (below)… That was REALLY frustrating. I looked again at the code and I realized that the only floating point value was the value for T, which is the duration of the note to be played. That had to be in the np.linspace command. T = 0.25 t = np.linspace(0, T, T * sample_rate, False) Ah. The T * sample_rate portion is going to return a floating point value so I tried casting it to an integer. t = np.linspace(0, T, int(T * sample_rate), False)

Puis, ce code (page suivante, en haut à gauche) va « regrouper » toutes les notes et les normaliser en un seul tableau numpy.

Ensuite, nous introduisons les données audio dans le tampon d'exécution (playbuffer) et attendons qu'il soit terminé (en haut à droite).

Sachant que je ne pouvais pas faire de fautes de frappe, puisque j'ai copié le code directement à partir de la documentation, j'ai appuyé sur la touche <entrée> après la dernière ligne, m'attendant à ce qu'on me présente un accord de trois notes, une note à la fois. Cependant, ce que j'ai obtenu est (ci-dessous).

C'était VRAIMENT frustrant. J'ai regardé le code à nouveau et j'ai réalisé que la seule valeur à virgule flottante était la valeur de T, qui est la durée de la note à jouer. Cela devait être dans la commande np.linspace.

T = 0.25 t = np.linspace(0, T, T * sample_rate, False)

Ah ! La partie T * taux d'échantillonnage va retourner une valeur à virgule flottante ; j'ai donc essayé de la convertir en un nombre entier :

t = np.linspace(0, T, int(T * sample_rate), False)

When I ran the program again, I was presented with the three tones that I was expecting all along. There were other examples from the website that I tried; one of which creates a higher resolution object; and then I tried to add more notes to the whole process. The idea was to create all the notes from A4 to A5. I modified the base file to calculate all thirteen notes. # calculate the frequencies A_freq = 440 Ash_freq = A_freq * 2 ** (1 / 12) B_freq = A_freq * 2 ** (2 / 12) C_freq = A_freq * 2 ** (3 / 12) Csh_freq = A_freq * 2 ** (4 / 12) D_freq = A_freq * 2 ** (5 / 12) Dsh_freq = A_freq * 2 ** (6 / 12) E_freq = A_freq * 2 ** (7 / 12) F_freq = A_freq * 2 ** (8 / 12) Fsh_freq = A_freq * 2 ** (9 / 12) G_freq = A_freq * 2 ** (10 / 12) Gsh_freq = A_freq * 2 ** (11 / 12) A5_freq = 880 If you aren’t a musician, this might not mean much to you; however, I’ll try to give you a point of reference. I grabbed a screenshot of the virtual piano keyboard from an app on my computer, and added some hints. Each of the white keys are called natural keys. In the image, it starts with middle C (which is C4) and goes up an octave (13 notes) to C5. It’s called middle C because it’s the C key in the middle of the keyboard.

Lorsque j'ai relancé le programme, j'ai obtenu les trois tons que j'attendais depuis le début.

J'ai essayé d'autres exemples du site Web, dont l'un crée un objet de plus haute résolution, puis j'ai essayé d'ajouter plus de notes à l'ensemble du processus. L'idée était de créer toutes les notes de La4 à La5. J'ai modifié le fichier de base pour calculer les treize notes : # calculate the frequencies A_freq = 440 Ash_freq = A_freq * 2 ** (1 / 12) B_freq = A_freq * 2 ** (2 / 12) C_freq = A_freq * 2 ** (3 / 12) Csh_freq = A_freq * 2 ** (4 / 12) D_freq = A_freq * 2 ** (5 / 12) Dsh_freq = A_freq * 2 ** (6 / 12) E_freq = A_freq * 2 ** (7 / 12) F_freq = A_freq * 2 ** (8 / 12) Fsh_freq = A_freq * 2 ** (9 / 12) G_freq = A_freq * 2 ** (10 / 12) Gsh_freq = A_freq * 2 ** (11 / 12) A5_freq = 880 Si vous n'êtes pas musicien, cela ne signifie peut-être pas grand-chose pour vous ; cependant, je vais essayer de vous donner un point de référence. J'ai saisi une capture d'écran du clavier virtuel d'un piano à partir d'une application sur mon ordinateur et j'ai ajouté quelques indices.

Chacune des touches blanches est appelée touche naturelle. Dans l'image, on commence par le Do central (qui est Do4) et on monte d'une octave (13 notes) jusqu'au Do5. On l'appelle Do central parce que c'est la touche Do au milieu du clavier.

The black keys are sharps or flats depending on if you are going up the scale or down. So the keys are C, C#, D, D#, E, F, F#, G, G#, A, A#, B and back to C …for a total of thirteen tones. In “modern” music, this is known as an equal-tempered scale. It hasn’t always been this way, but that gets into a whole can of worms, so I won’t go there. Just know that the formulas above to generate the thirteen tones work well. You can find the program to do this as tones4.py in the repository. I was going to close the article here, with a note that I hadn’t tried to save the audio objects created to files, either as a numpy file that can be loaded later or as a .wav file that would negate the need to import numpy in every program you create and use this, just the simpleaudio package. Well after taking a quick break, I figured out how to do it, so I’ll let you in on the secret. The solution to saving the audio object to a file is really rather simple. At the bottom of the file, there are just two lines. In the case of tones4.py, add at the bottom of the file the following lines. # save the audio object to local file for future use with open(“scale1.npy”, “wb”) as f: np.save(f, audio)

Les touches noires sont des dièses ou des bémols, selon que vous montez ou descendez la gamme. Les clés sont donc :

Do, Do#, Ré, Ré#, Mi, Fa, Fa#, Sol, Sol#, La, La#, Si et retour au Do.

…pour un total de treize tonalités. Dans la musique « moderne », on appelle cela la gamme tempérée. Il n'en a pas toujours été ainsi, mais c'est une autre paire de manches, alors je ne m'y attarderai pas.

Sachez simplement que les formules ci-dessus pour générer les treize tons fonctionnent bien.

Vous pouvez trouver le programme pour le faire sous le nom de tones4.py dans le dépôt.

J'allais clore l'article ici, en notant que je n'avais pas essayé de sauvegarder les objets audio créés dans des fichiers, soit comme un fichier numpy qui peut être chargé plus tard, soit comme un fichier .wav qui éviterait le besoin d'importer numpy dans chaque programme que vous créez et utilisez cela, mais juste le paquet simpleaudio. Après avoir fait une petite pause, j'ai trouvé comment le faire, alors je vais vous révéler le secret.

La solution pour sauvegarder l'objet audio dans un fichier est vraiment très simple. Au bas du fichier, il y a juste deux lignes. Dans le cas de tones4.py, ajoutez en bas du fichier les lignes suivantes :

# enregistrer l'objet audio dans un fichier local pour une utilisation future

with open(“scale1.npy”, “wb”) as f :

  np.save(f, audio)
  

That’s it. I’ve saved the program as tones4a.py . The file that was generated can be used again in a different program (top right). This solution, however, still requires having numpy as a dependency in the program. For me, the better solution is not only to have the numpy file (for future use) but to save the audio object to a .wav file. This requires the additional import of the wave package. Add that to the top of the test4 program, and then add the following code at the bottom. obj = wave.open(“scale1.wav”, “w”) obj.setnchannels(1) obj.setsampwidth(2) obj.setframerate(sample_rate) obj.writeframesraw(audio) obj.close() This will create a .wav file (without the need to save the numpy data if you don’t want to). Then to play it back, all you need is this short bit of code. import simpleaudio as sa wave_obj = sa.WaveObject.from_wave_file(“scale1.wav”) play_obj = wave_obj.play() play_obj.wait_done()

C'est tout. J'ai enregistré le programme sous le nom de tones4a.py . Le fichier qui a été généré peut être réutilisé dans un autre programme (en haut à droite).

Cette solution, cependant, nécessite toujours d'avoir numpy comme dépendance dans le programme. Pour moi, la meilleure solution n'est pas seulement d'avoir le fichier numpy (pour une utilisation future) mais de sauvegarder l'objet audio dans un fichier .wav. Cela nécessite l'importation supplémentaire du paquet wave. Ajoutez-le en haut du programme test4, puis ajoutez le code suivant en bas : obj = wave.open(“scale1.wav”, “w”) obj.setnchannels(1) obj.setampwidth(2) obj.setframerate(sample_rate) obj.writeframesraw(audio) obj.close()

Cela créera un fichier .wav (sans qu'il soit nécessaire de sauvegarder les données numpy si vous ne le souhaitez pas). Ensuite, pour le lire, tout ce dont vous avez besoin est ce petit bout de code :

import simpleaudio as sa wave_obj = sa.WaveObject.from_wave_file(“scale1.wav”) play_obj = wave_obj.play() play_obj.wait_done()

So I modified tones4a.py to include not only the write to a numpy file, but the code to create the .wav file and play it back. I’ve also included the playback routine as a simple python file named play_my_wav.py which will play back the “scale1.wav” file. Of course, the numpy files and some sample .wav files are also in the repository. Well, it’s time to wrap this up for this month. Just know that looking for a simple thing like getting your computer to beep on command can easily lead you to a path where you might be like Alice, and “go down the rabbit hole”. I’ve put the .wav file for Beepy as well as the test file for simpleaudio in my github repository. I’ve also included a few other test files I created for simpleaudio testing. You can find the repository at https://github.com/gregwa1953/FCM-190. Until next time, as always; stay safe, healthy, positive and creative!

J'ai donc modifié tones4a.py pour inclure non seulement l'écriture dans un fichier numpy, mais aussi le code pour créer le fichier .wav et le lire.

J'ai également inclus la routine de lecture dans un simple fichier python nommé play_my_wav.py qui lira le fichier « scale1.wav ». Bien sûr, les fichiers numpy et quelques exemples de fichiers .wav sont également dans le dépôt.

Bon, il est temps de conclure pour ce mois-ci. Sachez que la recherche d'une chose aussi simple que de faire sonner votre ordinateur sur commande peut facilement vous conduire sur un chemin où vous pourriez être comme Alice, et « descendre dans le terrier du lapin ».

J'ai mis le fichier .wav pour Beepy ,ainsi que le fichier de test pour simpleaudio, dans mon dépôt github. J'ai également inclus quelques autres fichiers de test que j'ai créés pour tester simpleaudio. Vous pouvez trouver le dépôt à https://github.com/gregwa1953/FCM-190.

Jusqu'à la prochaine fois, comme toujours, restez en sécurité, en bonne santé, positif et créatif !

issue190/python.txt · Dernière modification : 2023/03/01 12:56 de andre_domenech