1<?xml version="1.0" encoding="utf-8"?>
2<page xmlns="http://projectmallard.org/1.0/" xmlns:its="http://www.w3.org/2005/11/its" type="topic" id="guitar-tuner.py" xml:lang="de">
3
4  <info>
5    <title type="text">Gitarrenstimmgerät (Python)</title>
6    <link type="guide" xref="py#examples"/>
7
8    <desc>Use GTK+ and GStreamer to build a simple guitar tuner application for GNOME. Shows off how to use the interface designer.</desc>
9
10    <revision pkgversion="0.1" version="0.1" date="2010-12-02" status="stub"/>
11    <credit type="author">
12      <name>GNOME-Dokumentationsprojekt</name>
13      <email its:translate="no">gnome-doc-list@gnome.org</email>
14    </credit>
15    <credit type="author">
16      <name>Johannes Schmid</name>
17      <email its:translate="no">jhs@gnome.org</email>
18    </credit>
19    <credit type="editor">
20      <name>Marta Maria Casetti</name>
21      <email its:translate="no">mmcasetti@gmail.com</email>
22      <years>2013</years>
23    </credit>
24    <credit type="editor">
25      <name>Marta Maria Casetti</name>
26      <email its:translate="no">mmcasetti@gmail.com</email>
27      <years>2013</years>
28    </credit>
29
30    <mal:credit xmlns:mal="http://projectmallard.org/1.0/" type="translator copyright">
31      <mal:name>Mario Blättermann</mal:name>
32      <mal:email>mario.blaettermann@gmail.com</mal:email>
33      <mal:years>2011, 2013, 2016, 2018, 2021</mal:years>
34    </mal:credit>
35  </info>
36
37<title>Gitarrenstimmgerät</title>
38
39<synopsis>
40  <p>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:</p>
41  <list>
42    <item><p>Einrichten eines einfachen Projekts in Anjuta</p></item>
43    <item><p>Erstellen einer einfachen grafischen Benutzeroberfläche mit dem UI-Designer von Anjuta</p></item>
44    <item><p>GStreamer zum Abspielen von Klängen verwenden</p></item>
45  </list>
46  <p>You'll need the following to be able to follow this tutorial:</p>
47  <list>
48    <item><p>An installed copy of the <link xref="getting-ready">Anjuta IDE</link></p></item>
49    <item><p>Grundlegende Kenntnisse der Programmiersprache Python</p></item>
50  </list>
51</synopsis>
52
53<media type="image" mime="image/png" src="media/guitar-tuner.png"/>
54
55<section id="anjuta">
56  <title>Erstellen eines Projekts in Anjuta</title>
57  <p>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.</p>
58  <steps>
59    <item>
60    <p>Starten Sie Anjuta und wählen Sie <guiseq><gui>Datei</gui><gui>Neu</gui><gui>Projekt</gui></guiseq>, um den Projektassistenten zu öffnen.</p>
61    </item>
62    <item>
63    <p>Choose <gui>PyGTK (automake)</gui> from the <gui>Python</gui> tab, click <gui>Continue</gui>, and fill out your details on the next few pages. Use <file>guitar-tuner</file> as project name and directory.</p>
64   	</item>
65    <item>
66    <p>Click <gui>Apply</gui> and the project will be created for you. Open <file>src/guitar_tuner.py</file> from the <gui>Project</gui> or <gui>File</gui> tabs. You should see some code which starts with the lines:</p>
67    <code mime="test/x-python">
68from gi.repository import Gtk, GdkPixbuf, Gdk
69import os, sys</code>
70    </item>
71  </steps>
72</section>
73
74<section id="run">
75  <title>Erste Ausführung des Codes</title>
76  <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>
77
78  <list>
79  <item>
80    <p>The <code>import</code> lines at the top include the tell Python to load the user interface and system
81libraries needed.</p>
82   </item>
83   <item>
84    <p>A class is declared that will be the main class for our application. In the <code>__init__</code> method
85	the main window is loaded from the GtkBuilder file (<file>src/guitar-tuner.ui</file>) and the
86	signals are connected.</p>
87    <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>
88   </item>
89   <item>
90    <p>The <code>main</code> function is run by default when you start a Python application. It just creates
91	an instance of the main class and starts the main loop to bring up the window.</p>
92   </item>
93  </list>
94
95  <p>This code is ready to be used, so you can run it by clicking <guiseq><gui>Run</gui><gui>Execute</gui></guiseq>.</p>
96</section>
97
98<section id="ui">
99  <title>Erstellen der Benutzeroberfläche</title>
100  <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 right, and the palette of available widgets is on the left.
101  </p>
102  <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>
103
104<media type="image" mime="image/png" src="media/guitar-tuner-glade.png"/>
105
106  <steps>
107   <item>
108   <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
109six strings) and the orientation to vertical.</p>
110   </item>
111   <item>
112    <p>Now, choose a <gui>GtkButton</gui> from the palette and put it into the first part of the box.</p>
113   </item>
114   <item>
115    <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>
116    </item>
117    <item>
118     <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>
119    </item>
120    <item>
121    <p>Repeat the above steps for the other buttons, adding the next 5 strings with the names <em>A</em>, <em>D</em>, <em>G</em>, <em>B</em>, and <em>e</em>.</p>
122    </item>
123    <item>
124    <p>Save the UI design (by clicking <guiseq><gui>File</gui><gui>Save</gui></guiseq>) and keep it open.</p>
125    </item>
126  </steps>
127</section>
128
129<section id="signal">
130  <title>Schreiben des Signalhandlers</title>
131  <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>
132<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
133<gui>clicked</gui> signal and drag it into to the source file inside the class. The following code will be added to your source file:</p>
134<code mime="text/x-csrc">
135def on_button_clicked (self, button):
136</code>
137
138  <p>This signal handler has two arguments: the usual Python class pointer, and the <code>Gtk.Button</code> that called the function.</p>
139  <p>For now, we'll leave the signal handler empty while we work on writing the code to produce sounds.</p>
140</section>
141
142<section id="gstreamer">
143  <title>GStreamer-Weiterleitungen</title>
144  <p>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.</p>
145  <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>
146  <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>
147  <media type="image" mime="image/png" src="media/guitar-tuner-pipeline.png">
148    <p>Eine Beispiel-Weiterleitung in GStreamer.</p>
149  </media>
150</section>
151
152<section id="pipeline">
153  <title>Einrichten der Weiterleitung</title>
154  <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>
155
156  <p>Change the import line in <file>guitar_tuner.py</file>, just at the beginning to :</p>
157  <code mime="test/x-python">from gi.repository import Gtk, Gst, GObject </code>
158  <p>The <code>Gst</code> includes the GStreamer library. You also need to initialise GStreamer properly which
159     is done in the <code>main()</code> method with this call added above the <code>app = GUI()</code>
160     line:</p>
161  <code mime="test/x-python">Gst.init_check(sys.argv)</code>
162  <p>Then, copy the following function into the class in <file>guitar_tuner.py</file> somewhere:</p>
163  <code mime="test/x-python">
164def play_sound(self, frequency):
165	pipeline = Gst.Pipeline(name='note')
166	source = Gst.ElementFactory.make('audiotestsrc', 'src')
167	sink = Gst.ElementFactory.make('autoaudiosink', 'output')
168
169	source.set_property('freq', frequency)
170	pipeline.add(source)
171	pipeline.add(sink)
172	source.link(sink)
173	pipeline.set_state(Gst.State.PLAYING)
174
175	GObject.timeout_add(self.LENGTH, self.pipeline_stop, pipeline)</code>
176  <steps>
177    <item>
178    <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>
179    </item>
180    <item>
181    <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>
182    </item>
183    <item>
184    <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>
185    </item>
186    <item>
187    <p>Next <code>pipeline.set_state</code> is used to start playback, by setting the state of the pipeline to playing (<code>Gst.State.PLAYING</code>).</p>
188    </item>
189  </steps>
190
191</section>
192
193<section id="playback">
194  <title>Die Wiedergabe stoppen</title>
195  <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>
196  <p>Now, we'll write the <code>pipeline_stop</code> function which is called by <code>GObject.timeout_add</code>. Insert the following code <em>above</em> the <code>play_sound</code> function:</p>
197  <code mime="test/x-python">
198def pipeline_stop(self, pipeline):
199	pipeline.set_state(Gst.State.NULL)
200	return False
201</code>
202  <p>You need to define the <code>LENGTH</code> constant inside the class, so add this code at the beginning of the
203main class:</p>
204  <code mime="test/x-python">
205LENGTH = 500
206</code>
207  <p>Der Aufruf von <code>pipeline.set_state</code> stoppt die Wiedergabe der Pipeline.</p>
208</section>
209
210<section id="tones">
211  <title>Definieren der Töne</title>
212  <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
213we can easily map them to the names of the strings:</p>
214  <code mime="test/x-python">
215# Frequencies of the strings
216frequencies = {
217	'E': 329.63,
218	'A': 440,
219	'D': 587.33,
220	'G': 783.99,
221	'B': 987.77,
222	'e': 1318.5
223}
224</code>
225  <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>
226  <code mime="test/x-python">
227def on_button_clicked(self, button):
228	label = button.get_child()
229	text = label.get_label()
230
231	self.play_sound (self.frequencies[text])
232</code>
233  <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>
234  <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>
235</section>
236
237<section id="run2">
238  <title>Anwendung ausführen</title>
239  <p>All of the code should now be ready to go. Click <guiseq><gui>Run</gui><gui>Execute</gui></guiseq> to start the application. Enjoy!</p>
240</section>
241
242<section id="impl">
243 <title>Referenz-Implementierung</title>
244 <p>If you run into problems with the tutorial, compare your code with this <link href="guitar-tuner/guitar-tuner.py">reference code</link>.</p>
245</section>
246
247<section id="next">
248  <title>Nächste Schritte</title>
249  <p>Hier sind einige Ideen, wie Sie diese einfache Demonstration erweitern können:</p>
250  <list>
251   <item>
252   <p>Lassen Sie das Programm automatisch durch die Notizen blättern.</p>
253   </item>
254   <item>
255   <p>Make the program play recordings of real guitar strings being plucked.</p>
256   <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>
257   <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>
258   </item>
259   <item>
260   <p>Automatically analyze notes that the user plays.</p>
261   <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>
262   </item>
263  </list>
264</section>
265
266</page>
267