Skip to content
Advertisement

How to call a method while another method is still running- Python

I’m working on a python program that extracts the sound from a given YouTube video url and plays it. I created a play_vid method to play the sound and a pause_vid method to pause the sound. The issue is that while the sound is still playing inside the play_vid method and I try to call the pause_vid method, the call gets ignored and the play_vid method keeps running. Example:

JavaScript

How do I terminate the play_vid method when the pause_vid method is called? I’ve been researching for a while and wasn’t able to find a solution to this problem. Full program:

JavaScript

A big thanks to Mark M for letting me know that I forgot to add self.player.set_pause(1) in the pause_vid method. He also advised me to remove the while loop, so I used time.sleep in my main program in order to decide how long the video will play for instead of the while loop. Updated code:

JavaScript

I’ve also found a way to play the whole sound in the main program:

JavaScript

I’m basically just delaying the program by the length of the video.

Advertisement

Answer

The problem is two-fold:

  1. You’re not actually pausing the audio playback, so the MediaPlayer will just continue to play the rest of it. According to the MediaPlayer docs it has a function pause() or even stop(). Call this from your pause_vid method.
  2. You’ll need to invoke the vid.pause_vid() method from another thread because the play_vid() method will just run till completion. You can create a background thread to play the video from. Some good examples here https://pymotw.com/3/threading/ On second thought, I think the MediaPlayer.play() method already runs in the background due to the wording in the documentation:

Play. @return: 0 if playback started (and was already started), or -1 on error.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement