Determining the tempo of a rhythm

The mathematics of defining the tempo of a rhythm is simple. We get the value associated with the beats_per_minute attribute and divide it by 60 to get the beats per second. Then, the time to play each beat (or group of beats simultaneously for a given column) is the reciprocal of beats_per_second.

The code is as follows (see code 3.06.py):

def time_to_play_each_column(self):
beats_per_second = self.beats_per_minute/60
time_to_play_each_column = 1/beats_per_second
return time_to_play_each_column

While we are handling the tempo for the pattern, let's also complete coding of the command callback attached to our beats per minute Spinbox widget (see code 3.06.py):

def on_beats_per_minute_changed(self):
self.beats_per_minute = int(self.beats_per_minute_widget.get())

Now let's code the functionality related to the loop Checkbox. We have already factored in the looping issue in our play_pattern method using the self.loop variable. We simply need to set the value of the self.loop attribute by reading the value of the Spinbox widget (see code 3.06.py):

def on_loop_button_toggled(self):
self.loop = self.loopbuttonvar.get()

With that out of the way, let's code the command callback attached to our Play button and the Stop button (see code 3.06.py):

def on_play_button_clicked(self):
self.start_play()

def start_play(self):
self.init_pygame()
self.play_pattern()

def on_stop_button_clicked(self):
self.stop_play()

def stop_play(self):
self.now_playing = False

Our drum machine is now operational (see code 3.06.py). You can load drum samples and define beat patterns, and when you click on the Play button, the drum machine plays that beat pattern!

However, there is a small problem. The play_sound method blocks the main loop of our Tkinter program. It does not relinquish control back to the main loop until it is done playing the sound sample.

Since our self.loop variable is set to True, this means that pygame never returns back control to Tkinter's main loop and our play button and program is stuck! This can be seen in the following screenshot:

This means that if you now want to click on the Stop button or change some other widget, or even close the window, you will have to wait for the play loop to complete, which never happens in our case.

This is clearly a glitch. We need some method to confer back the control to the Tkinter main loop while the play is still in progress.

That brings us to the next iteration, where we discuss and implement multithreading in our application.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.80.45