# Guitar tuner (Python)

Use o GTK+ e o GStreamer para criar um aplicativo simples de sintonizador de violão para o GNOME. Mostra como usar o designer de interface.
Projeto de Documentação do GNOME
gnome-doc-list@gnome.org
Johannes Schmid
jhs@gnome.org
Marta Maria Casetti
mmcasetti@gmail.com 2013
Marta Maria Casetti
mmcasetti@gmail.com 2013
Rafael Fontenelle
rafaelff@gnome.org 2013, 2018

# Guitar tuner

      In this tutorial, we're going to make a program which plays tones that you can use to tune a guitar. You will learn how to:

        Set up a basic project in Anjuta
        Create a simple GUI with Anjuta's UI designer
        Use GStreamer to play sounds

      You'll need the following to be able to follow this tutorial:

        An installed copy of the Anjuta IDE
        Basic knowledge of the Python programming language

# Create a project in Anjuta

Before you start coding, you'll need to set up a new project in Anjuta. This will create all of the files you need to build and run the code later on. It's also useful for keeping everything together.

Start Anjuta and click File New Project to open the project wizard.

Choose PyGTK (automake) from the Python tab, click Continue, and fill out your details on the next few pages. Use guitar-tuner as project name and directory.

Click Apply and the project will be created for you. Open src/guitar_tuner.py from the Project or File tabs. You should see some code which starts with the lines:

from gi.repository import Gtk, GdkPixbuf, Gdk import os, sys

# Run the code for the first time

Most of the code in the file is template code. It loads an (empty) window from the user interface description file and shows it. More details are given below; skip this list if you understand the basics:

The `import` lines at the top include the tell Python to load the user interface and system libraries needed.

A class is declared that will be the main class for our application. In the `__init__` method the main window is loaded from the GtkBuilder file (src/guitar-tuner.ui) and the signals are connected.

Connecting signals is how you define what happens when you push a button, or when some other event happens. Here, the `destroy` method is called (and quits the app) when you close the window.

The `main` function is run by default when you start a Python application. It just creates an instance of the main class and starts the main loop to bring up the window.

This code is ready to be used, so you can run it by clicking Run Execute.

# Create the user interface

A description of the user interface (UI) is contained in the GtkBuilder file. To edit the user interface, open src/guitar_tuner.ui. This will switch to the interface designer. The design window is in the center; widgets and widgets' properties are on the right, and the palette of available widgets is on the left.

The layout of every UI in GTK+ is organized using boxes and tables. Let's use a vertical GtkButtonBox here to assign six GtkButtons, one for each of the six guitar strings.

Select a GtkButtonBox from the Container section of the Palette on the right and put it into the window. In the Properties pane, set the number of elements to 6 (for the six strings) and the orientation to vertical.

Now, choose a GtkButton from the palette and put it into the first part of the box.

While the button is still selected, change the Label property in the Widgets tab to E. This will be the low E string.

Switch to the Signals tab (inside the Widgets tab) and look for the `clicked` signal of the button. You can use this to connect a signal handler that will be called when the button is clicked by the user. To do this, click on the signal and type `on_button_clicked` in the Handler column and press Return.

Repeat the above steps for the other buttons, adding the next 5 strings with the names A, D, G, B, and e.

Save the UI design (by clicking File Save) and keep it open.

# Write the signal handler

In the UI designer, you made it so that all of the buttons will call the same function, on_button_clicked, when they are clicked. We need to add that function in the source file.

To do this, open guitar_tuner.py while the user interface file is still open. Switch to the Signals tab, which you already used to set the signal name. Now take the row where you set the clicked signal and drag it into to the source file inside the class. The following code will be added to your source file:

def on_button_clicked (self, button):

This signal handler has two arguments: the usual Python class pointer, and the `Gtk.Button` that called the function.

For now, we'll leave the signal handler empty while we work on writing the code to produce sounds.

# GStreamer pipelines

GStreamer is GNOME's multimedia framework — you can use it for playing, recording, and processing video, audio, webcam streams and the like. Here, we'll be using it to produce single-frequency tones.

Conceptually, GStreamer works as follows: You create a pipeline containing several processing elements going from the source to the sink (output). The source can be an image file, a video, or a music file, for example, and the output could be a widget or the soundcard.

Between source and sink, you can apply various filters and converters to handle effects, format conversions and so on. Each element of the pipeline has properties which can be used to change its behaviour.

An example GStreamer pipeline.

# Set up the pipeline

In this simple example we will use a tone generator source called `audiotestsrc` and send the output to the default system sound device, `autoaudiosink`. We only need to configure the frequency of the tone generator; this is accessible through the `freq` property of `audiotestsrc`.

Change the import line in guitar_tuner.py, just at the beginning to :

from gi.repository import Gtk, Gst, GObject

The `Gst` includes the GStreamer library. You also need to initialise GStreamer properly which is done in the `main()` method with this call added above the `app = GUI()` line:

Gst.init_check(sys.argv)

Then, copy the following function into the class in guitar_tuner.py somewhere:

def play_sound(self, frequency): pipeline = Gst.Pipeline(name='note') source = Gst.ElementFactory.make('audiotestsrc', 'src') sink = Gst.ElementFactory.make('autoaudiosink', 'output')

source.set_property('freq', frequency) pipeline.add(source) pipeline.add(sink) source.link(sink) pipeline.set_state(Gst.State.PLAYING)

GObject.timeout_add(self.LENGTH, self.pipeline_stop, pipeline)

The first three lines create source and sink GStreamer elements and a pipeline element (which will be used as a container for the other two elements). The pipeline is given the name "note"; the source is named "source" and is set to the `audiotestsrc` source; and the sink is named "output" and set to the `autoaudiosink` sink (default sound card output).

The call to `source.set_property` sets the `freq` property of the source element to `frequency`, which was passed as an argument to the `play_sound` function. This is just the frequency of the note in Hertz; some useful frequencies will be defined later on.

The next two lines call `pipeline.add`, putting the source and sink into the pipeline. The pipeline can contain multiple other GStreamer elements. In general, you can add as many elements as you like to the pipeline by calling its `add` method repeatedly.

Next `pipeline.set_state` is used to start playback, by setting the state of the pipeline to playing (`Gst.State.PLAYING`).

# Stopping playback

We don't want to play an annoying tone forever, so the last thing `play_sound` does is to call `GObject.timeout_add`. This sets a timeout for stopping the sound; it waits for `LENGTH` milliseconds before calling the function `pipeline_stop`, and will keep calling it until `pipeline_stop` returns `False`.

Now, we'll write the `pipeline_stop` function which is called by `GObject.timeout_add`. Insert the following code above the `play_sound` function:

def pipeline_stop(self, pipeline): pipeline.set_state(Gst.State.NULL) return False

You need to define the `LENGTH` constant inside the class, so add this code at the beginning of the main class:

LENGTH = 500

The call to `pipeline.set_state` stops the playback of the pipeline.

# Define the tones

We want to play the correct sound when the user clicks a button. First of all, we need to know the frequencies for the six guitar strings, which are defined (at the beginning of the main class) inside a dictionary so we can easily map them to the names of the strings:

# Frequencies of the strings frequencies = { 'E': 329.63, 'A': 440, 'D': 587.33, 'G': 783.99, 'B': 987.77, 'e': 1318.5 }

Now to flesh out the signal handler that we defined earlier, `on_button_clicked`. We could have connected every button to a different signal handler, but that would lead to a lot of code duplication. Instead, we can use the label of the button to figure out which button was clicked:

def on_button_clicked(self, button): label = button.get_child() text = label.get_label()

self.play_sound (self.frequencies[text])

The button that was clicked is passed as an argument (`button`) to `on_button_clicked`. We can get the label of that button by using `button.get_child`, and then get the text from that label using `label.get_label`.

The label text is then used as a key for the dictionary and `play_sound` is called with the frequency appropriate for that note. This plays the tone; we have a working guitar tuner!

# Run the application

All of the code should now be ready to go. Click Run Execute to start the application. Enjoy!

# Reference Implementation

If you run into problems with the tutorial, compare your code with this reference code.

# Next steps

Here are some ideas for how you can extend this simple demonstration:

Have the program automatically cycle through the notes.

Make the program play recordings of real guitar strings being plucked.

To do this, you would need to set up a more complicated GStreamer pipeline which allows you to load and play back music files. You'll have to choose decoder and demuxer GStreamer elements based on the file format of your recorded sounds — MP3s use different elements to Ogg Vorbis files, for example.

You might need to connect the elements in more complicated ways too. This could involve using GStreamer concepts that we didn't cover in this tutorial, such as pads. You may also find the gst-inspect command useful.

Automatically analyze notes that the user plays.

You could connect a microphone and record sounds from it using an input source. Perhaps some form of spectrum analysis would allow you to figure out what notes are being played?