- Tkinter GUI Application Development Blueprints(Second Edition)
- Bhaskar Chaudhary
- 353字
- 2021-06-24 18:35:14
Playing complete patterns
Now our program has the ability to play any sound. But we don't just need to play a single sound. We need to play a pattern. Let's define a method called play_pattern, which reads our internal data structure and plays files accordingly (see code 3.06.py):
import time
def play_pattern(self):
self.now_playing = True
while self.now_playing:
play_list = self.get_is_button_clicked_list()
num_columns = len(play_list[0])
for column_index in range(num_columns):
column_to_play = self.get_column_from_matrix(
play_list, column_index)
for i, item in enumerate(column_to_play):
if item:
sound_filename = self.get_drum_file_path(i)
self.play_sound(sound_filename)
time.sleep(self.time_to_play_each_column())
if not self.now_playing: break
if not self.loop: break
self.now_playing = False
We also add an associated method that returns the ith column from a matrix:
def get_column_from_matrix(self, matrix, i):
return [row[i] for row in matrix]
The description of the preceding code is as follows:
We create a class attribute called self.keep_playing to decide whether the pattern is to be played just once or continuously in a loop.
We create another class attribute called self.now_playing to track whether a beat is currently playing. This will help us to make some decisions on how to handle a sudden close of program or change of pattern by the user.
We then fetch the two-dimensional Boolean list from our data structure and scan each column of the list to look for True values. We get the column data from the matrix by defining a separate method called get_column_from_matrix(self, matrix, i).
For every column, if a True value is encountered, we fetch the corresponding drum file path and call the self.play_sound() method to play the file.
The code sleeps for a fixed duration of time before reading the second column. This sleep duration defines the tempo of the drum beat. If the code does not sleep for some time between each column, all the patterns would play almost immediately and would not even sound like a rhythm. We need to import the time module to use the time.sleep() method.
The amount of time the code sleeps between scanning each column is decided by another method called self.time_to_play_each_column(), which we define next.
- Mastering Visual Studio 2017
- JavaFX Essentials
- AngularJS深度剖析與最佳實踐
- 概率成形編碼調制技術理論及應用
- 大學計算機基礎實驗指導
- Java EE核心技術與應用
- Android系統原理及開發要點詳解
- Mastering Data Mining with Python:Find patterns hidden in your data
- 編程菜鳥學Python數據分析
- RealSenseTM互動開發實戰
- 從Excel到Python數據分析:Pandas、xlwings、openpyxl、Matplotlib的交互與應用
- Web前端開發技術:HTML、CSS、JavaScript
- Three.js權威指南:在網頁上創建3D圖形和動畫的方法與實踐(原書第4版)
- Flink入門與實戰
- Lync Server Cookbook