Looping over tracks

Let's add the feature that allows users to loop over tracks. We have already defined radio buttons to allow three choices, as shown in the following screenshot:

In essence, the player should provide a choice from the following three options:

  • No Loop: Play a track and end there
  • Loop Current: Play a single track repeatedly
  • Loop All: Looping through the entire playlist, one after another

The decision to follow one of these three options needs to be taken immediately after a particular track ends playing. The best place to judge whether a track has come to its end is from within the periodic updates loop that we created earlier.

Therefore, modify the manage_periodic_updates_during_play() method to add the following two lines of highlighted code (see code 5.08view.py):

def manage_periodic_updates_during_play(self):
self.update_clock()
self.update_seek_bar()
if not self.player.is_playing():
if self.not_to_loop(): return
self.root.after(1000, self.manage_periodic_updates_during_play)

This in effect means that the looping decision is checked only when the currently playing track ends. Then, define the not_to_loop() method, as follows (see code 5.09view.py):

def not_to_loop(self):
selected_loop_choice = self.loop_value.get()
if selected_loop_choice == 1: # no loop
return True
elif selected_loop_choice == 2: # loop current
self.start_play()
return False
elif selected_loop_choice == 3: #loop all
self.play_next_track()
return True

The code first checks the value of the selected radio button and, based on the selected choice, makes the looping choice:

  • If the selected loop value is 1 (No Loop), it does nothing and returns True, breaking out of the continuous update loop.
  • If the selected loop value is 2 (loop over the current song), it again calls the start_play method and returns False. Thus, we do not break out of the update loop.
  • If the loop value is 3 (Loop All), it calls the play_next_track method and returns True. Thus, we break out of the previous update loop.

The audio player can now loop over the playlist based on the looping preference set by the user.

Let's conclude this iteration by overriding the close button so that the audio player properly deletes the player object when the user decides to close the player while it is playing.

To override the destroy method, first add a protocol override command to the View __init__ method, as follows (see code 5.08view.py):

self.root.protocol('WM_DELETE_WINDOW', self.close_player) 

Finally, define the close_player method, as follows:

def close_player(self):
self.player.stop()
self.root.destroy()

This concludes the iteration. We coded the logic required to loop over tracks and then overrode the close button to ensure that a playing track is stopped before we exit the player.

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

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