<?xml version="1.0" encoding="utf-8"?>
<page xmlns="http://projectmallard.org/1.0/" type="topic" id="guitar-tuner.py" xml:lang="gl">

  <info>
    <link type="guide" xref="index#py"/>
  
    <desc>Usar GTK+ y GStreamer para construír un sinxelo afinador de guitarra para GNOME. Mostra como usar o deseñador de interfaces.</desc>
    
    <revision pkgversion="0.1" version="0.1" date="2010-12-02" status="stub"/>
    <credit type="author">
      <name>Proxecto de documentación de GNOME</name>
      <email>gnome-doc-list@gnome.org</email>
    </credit>
    <credit type="author">
      <name>Johannes Schmid</name>
      <email>jhs@gnome.org</email>
    </credit>
  </info>

<title>Afinador de guitarra</title>

<synopsis>
  <p>Neste titorial faremos un programa que reproduce tonos que pode usar para afinar unha guitarra. Aprenderá como:</p>
  <list>
    <item><p>Configurar un proxecto básico en Anjuta</p></item>
    <item><p>Crear unha GUI sinxela co deseñador de UI de Anjuta</p></item>
    <item><p>Usar GStreamer para reproducir sons.</p></item>
  </list>
  <p>You'll need the following to be able to follow this tutorial:</p>
  <list>
    <item><p>An installed copy of the <link xref="getting-ready">Anjuta IDE</link></p></item>
    <item><p>Coñecemento básico da linguaxe de programación Python</p></item>
  </list>
</synopsis>

<media type="image" mime="image/png" src="media/guitar-tuner.png"/>

<section id="anjuta">
  <title>Cree un proxecto de Anjuta</title>
  <p>Antes de comezar a programar, deberá configurar un proxecto novo en Anjuta. Isto creará todos os ficheiros que precise para construír e executar o código máis adiante. Tamén é útil para manter todo ordenado.</p>
  <steps>
    <item>
    <p>Inicie Anjuta e prema <guiseq><gui>Ficheiro</gui><gui>Novo</gui><gui>Proxecto</gui></guiseq> para abrir o asistente de proxectos.</p>
    </item>
    <item>
    <p>Choose <gui>PyGTK (automake)</gui> from the <gui>Python</gui> tab, click <gui>Forward</gui>, and fill out your details on the next few pages. Use <file>guitar-tuner</file> as project name and directory.</p>
   	</item>
    <item>
    <p>Prema <gui>Aplicar</gui> e crearase o proxecto. Abra <file>src/guitar_tuner.py</file> desde as lapelas <gui>Proxecto</gui> ou <gui>Ficheiro</gui>. Debería ver algo de código que comece coas liñas:</p>
    <code mime="test/x-python"><![CDATA[
from gi.repository import Gtk, GdkPixbuf, Gdk
import os, sys]]></code>
    </item>
  </steps>
</section>

<section id="run">
  <title>Executar o código por primeira vez</title>
  <p>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:</p>
  
  <list>
  <item>
    <p>The <code>import</code> lines at the top include the tell Python to load the user interface and system
libraries needed.</p>
   </item>
   <item>
    <p>A class is declared that will be the main class for our application. In the <code>__init__</code> method
	the main window is loaded from the GtkBuilder file (<file>src/guitar-tuner.ui</file>) and the
	signals are connected.</p>
    <p>Connecting signals is how you define what happens when you push a button, or when some other event happens. Here, the <code>destroy</code> method is called (and quits the app) when you close the window.</p>
   </item>
   <item>
    <p>The <code>main</code> 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.</p>
   </item>
  </list>

  <p>Este código está listo para o seu uso, polo que pode executalo premendo <guiseq><gui>Executar</gui><gui>Executar</gui></guiseq>.</p>
</section>

<section id="ui">
  <title>Crear a interface de usuario</title>
  <p>A description of the user interface (UI) is contained in the GtkBuilder file. To edit the user interface, open <file>src/guitar_tuner.ui</file>. This will switch to the interface designer. The design window is in the center; widgets and widgets' properties are on the left, and the palette of available widgets is on the right.
  </p>
  <p>The layout of every UI in GTK+ is organized using boxes and tables. Let's use a vertical <gui>GtkButtonBox</gui> here to assign six <gui>GtkButtons</gui>, one for each of the six guitar strings.</p>

<media type="image" mime="image/png" src="media/guitar-tuner-glade.png"/>

  <steps>
   <item>
   <p>Select a <gui>GtkButtonBox</gui> from the <gui>Container</gui> section of the <gui>Palette</gui> on the right and put it into the window. In the <gui>Properties</gui> pane, set the number of elements to 6 (for the
six strings) and the orientation to vertical.</p>
   </item>
   <item>
    <p>Now, choose a <gui>GtkButton</gui> from the palette and put it into the first part of the box.</p>
   </item>
   <item>
    <p>While the button is still selected, change the <gui>Label</gui> property in the <gui>Widgets</gui> tab to <gui>E</gui>. This will be the low E string.</p>
    </item>
    <item>
     <p>Switch to the <gui>Signals</gui> tab (inside the <gui>Widgets</gui> tab) and look for the <code>clicked</code> 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 <code>on_button_clicked</code> in the <gui>Handler</gui> column and press <key>Return</key>.</p>
    </item>
    <item>
    <p>Repita os pasos anteriores para o resto dos botóns, engadindo as 5 cordas restantes cos nomes <em>A</em>, <em>D</em>, <em>G</em>, <em>B</em> e <em>e</em>.</p>
    </item>
    <item>
    <p>Garde o deseño da IU (premendo <guiseq><gui>Ficheiro</gui><gui>Gardar</gui></guiseq>) e déixeo aberto.</p>
    </item>
  </steps>
</section>

<section id="signal">
  <title>Escribir o manexador de sinais</title>
  <p>In the UI designer, you made it so that all of the buttons will call the same function, <gui>on_button_clicked</gui>, when they are clicked. We need to add that function in the source file.</p>
<p>To do this, open <file>guitar_tuner.py</file> while the user interface file is still open. Switch to the <gui>Signals</gui> tab, which you already used to set the signal name. Now take the row where you set the 
<gui>clicked</gui> signal and drag it into to the source file inside the main class. The following code will be added to your source file:</p>
<code mime="text/x-csrc"><![CDATA[
def on_button_clicked (self, button):
]]></code>

  <p>This signal handler has two arguments: the usual Python class pointer, and the <code>Gtk.Button</code> that called the function.</p>
  <p>For now, we'll leave the signal handler empty while we work on writing the code to produce sounds.</p>
</section>

<section id="gstreamer">
  <title>Tuberías de GStreamer</title>
  <p>GStreamer é un marco de traballo multimedia de GNOME — vostede pode usalo para reproducir, gravar e procesar vídeo, son, fluxos de cámara web e semellantes. Aquí, usarémolo para producir tonos dunha única frecuencia.</p>
  <p>Conceptually, GStreamer works as follows: You create a <em>pipeline</em> containing several processing elements going from the <em>source</em> to the <em>sink</em> (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.</p>
  <p>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.</p>
  <media type="image" mime="image/png" src="media/guitar-tuner-pipeline.png">
    <p>Un exemplo de tubería de GStreamer.</p>
  </media>
</section>

<section id="pipeline">
  <title>Configurar a tubería</title>
  <p>In this simple example we will use a tone generator source called <code>audiotestsrc</code> and send the output to the default system sound device, <code>autoaudiosink</code>. We only need to configure the frequency of the tone generator; this is accessible through the <code>freq</code> property of <code>audiotestsrc</code>.</p>
  
  <p>Change the import line in <file>guitar_tuner.py</file>, just at the beginning to :</p>
  <code mime="test/x-python"><![CDATA[from gi.repository import Gtk, Gst, GObject ]]></code>
  <p>The <code>Gst</code> includes the GStreamer library. You also need to initialise GStreamer properly which
     is done in the <code>main()</code> method with this call added above the <code>app = GUI()</code>
     line:</p>
  <code mime="test/x-python"><![CDATA[Gst.init_check(sys.argv)]]></code>
  <p>Then, copy the following function into the main class in <file>guitar_tuner.py</file> somewhere:</p>
  <code mime="test/x-python"><![CDATA[
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)
	pipeline.set_state(Gst.State.PLAYING)

	GObject.timeout_add(self.LENGTH, self.pipeline_stop, pipeline)]]></code>  
  <steps>
    <item>
    <p>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 <code>audiotestsrc</code> source; and the sink is named "output" and set to the <code>autoaudiosink</code> sink (default sound card output).</p>
    </item>
    <item>
    <p>The call to <code>source.set_property</code> sets the <code>freq</code> property of the source element to <code>frequency</code>, which was passed as an argument to the <code>play_sound</code> function. This is just the frequency of the note in Hertz; some useful frequencies will be defined later on.</p>
    </item>
    <item>
    <p>The next two lines call <code>pipeline.add</code>, 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 <code>add</code> method repeatedly.</p>
    </item>
    <item>
    <p>A seguinte <code>pipeline.set_state</code> úsase para iniciar a reprodución, estabelecendo o estado da tubería a reprodución (<code>Gst.State.PLAYING).</code></p>
    </item>
  </steps>
  
</section>

<section id="playback">
  <title>Deter a reprodución</title>
  <p>We don't want to play an annoying tone forever, so the last thing <code>play_sound</code> does is to call <code>GObject.timeout_add</code>. This sets a timeout for stopping the sound; it waits for <code>LENGTH</code> milliseconds before calling the function <code>pipeline_stop</code>, and will keep calling it until <code>pipeline_stop</code> returns <code>False</code>.</p>
  <p>Agora, escríbese o código da función <code>pipeline_stop</code>, chamada por <code>GObject.timeout_add</code>. Inserte o código seguinte <em>enriba</em> da función <code>play_sound</code>:</p>
  <code mime="test/x-python"><![CDATA[
def pipeline_stop(self, pipeline):
	pipeline.set_state(Gst.State.PAUSED)
	return False
]]></code>
  <p>You need to define the <code>LENGTH</code> constant inside the class, so add this code at the beginning of the
main class:</p>
  <code mime="test/x-python"><![CDATA[
LENGTH = 500
]]></code>
  <p>The call to <code>pipeline.set_state</code> pauses the playback of the pipeline.</p>
</section>

<section id="tones">
  <title>Definir os tonos</title>
  <p>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:</p>
  <code mime="test/x-python"><![CDATA[
# Frequencies of the strings
frequencies = {
	'E': 369.23,
	'A': 440,
	'D': 587.33,
	'G': 783.99,
	'B': 987.77,
	'e': 1318.5
}
]]></code>
  <p>Now to flesh out the signal handler that we defined earlier, <code>on_button_clicked</code>. 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:</p>
  <code mime="test/x-python"><![CDATA[
def on_button_clicked(self, button):
	label = button.get_child()
	text = label.get_label()

	self.play_sound (self.frequencies[text])
]]></code>
  <p>The button that was clicked is passed as an argument (<code>button</code>) to <code>on_button_clicked</code>. We can get the label of that button by using <code>button.get_child</code>, and then get the text from that label using <code>label.get_label</code>.</p>
  <p>The label text is then used as a key for the dictionary and <code>play_sound</code> is called with the frequency appropriate for that note. This plays the tone; we have a working guitar tuner!</p>
</section>

<section id="run2">
  <title>Executar o aplicativo</title>
  <p>Todo o código debería estar listo. Prema <guiseq><gui>Executar</gui><gui>Executar</gui></guiseq> para iniciar o aplicativo. Góceo!</p>
</section>

<section id="impl">
 <title>Implementación de referencia</title>
 <p>Se ten problemas ao executar este titorial compare o seu código con este <link href="guitar-tuner/guitar-tuner.py">código de referencia</link>.</p>
</section>

<section id="next">
  <title>Seguintes pasos</title>
  <p>Aquí hai algunhas ideas sobre como pode estender esta sinxela demostración:</p>
  <list>
   <item>
   <p>Facer que o programa reproduza de forma cíclica as notas.</p>
   </item>
   <item>
   <p>Facer que o programa reproduza gravacións de cordas de guitarras que se están afinando.</p>
   <p>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 <link href="http://gstreamer.freedesktop.org/documentation/plugins.html">decoder and demuxer</link> GStreamer elements based on the file format of your recorded sounds — MP3s use different elements to Ogg Vorbis files, for example.</p>
   <p>You might need to connect the elements in more complicated ways too. This could involve using <link href="http://gstreamer.freedesktop.org/data/doc/gstreamer/head/manual/html/chapter-intro-basics.html">GStreamer concepts</link> that we didn't cover in this tutorial, such as <link href="http://gstreamer.freedesktop.org/data/doc/gstreamer/head/manual/html/section-intro-basics-pads.html">pads</link>. You may also find the <cmd>gst-inspect</cmd> command useful.</p>
   </item>
   <item>
   <p>Analizar automaticamente as notas que toca o músico.</p>
   <p>You could connect a microphone and record sounds from it using an <link href="http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gst-plugins-good-plugins/html/gst-plugins-good-plugins-autoaudiosrc.html">input source</link>. Perhaps some form of <link href="http://gstreamer.freedesktop.org/data/doc/gstreamer/head/gst-plugins-good-plugins/html/gst-plugins-good-plugins-plugin-spectrum.html">spectrum analysis</link> would allow you to figure out what notes are being played?</p>
   </item>
  </list>
</section>

</page>
