Adding the play/stop function

Now that we have a playlist and a Player class that can play audio, playing audio is simply about updating the current track index and calling the play method. 

Accordingly, let's add an attribute, as follows (see code 5.04view.py):

current_track_index = 0 

Furthermore, the Play button should act as a toggle between the play and stop functions. The Python itertools module provides the cycle method, which is a very convenient way to toggle between two or more values.

Accordingly, import the itertools module and define a new attribute, as follows (see code 5.04view.py):

toggle_play_stop = itertools.cycle(["play","stop"]) 

Now, every time we call next(toggle_play_stop), the value returned toggles between the play and stop strings.

Itertools is a very powerful standard library of Python that can emulate many iterables from a functional programming paradigm. An iterable in Python is an interface that implements the next() method. Every subsequent call to next() is lazily evaluated—thereby making them suitable for iterating over large sequences in the most efficient manner. The cycle() tool used here is an example of an iterator that can provide infinite sequences of alternating values without the need to define a large data structure. 

The following is the documentation of the itertools module:
 https://docs.python.org/3/library/itertools.html

Next, modify the on_play_stop_button_clicked() method so that it looks like this (see code 5.04view.py):

def on_play_stop_button_clicked(self):
action = next(self.toggle_play_stop)
if action == 'play':
try:
self.current_track_index = self.list_box.curselection()[0]
except IndexError:
self.current_track_index = 0
self.start_play()
elif action == 'stop':
self.stop_play()

The preceding method simply toggles between calling the start_play() and stop_play() methods, which are defined as follows:

def start_play(self):
try:
audio_file = self.model.get_file_to_play(self.current_track_index)
except IndexError:
return
self.play_stop_button.config(image=self.stop_icon)
self.player.play_media(audio_file)

def stop_play(self):
self.play_stop_button.config(image=self.play_icon)
self.player.stop()

The preceding code calls the play and stop methods defined in the Player class. It also changes the button image from the play icon to the stop icon by using the widget.config(image=new_image_icon) method.

While we are handling the play function, let's modify the command callback so that a user can play a track simply by double-clicking on it. We have already defined a method named on_play_list_double_clicked earlier, which is currently empty.

Simply modify it, as follows:

def on_play_list_double_clicked(self, event=None):
self.current_track_index = int(self.list_box.curselection()[0])
self.start_play()
..................Content has been hidden....................

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