Open cosine0 opened 3 years ago
https://stackoverflow.com/questions/66978714/how-can-i-stop-the-infinite-loop-with-a-trigger I found another solution it's gonna be like that;
import time
from pynput import keyboard
import pathlib
from pydub import AudioSegment
from pydub.playback import play
from gtts import gTTS
english=["school", "book", "theater", "stranger" ,"season"]
print("Press Enter ==> Start\n"
"Press p ==> Exit")
check = ''
def Start(key):
if key == keyboard.Key.enter:
print("Started")
return False
def Stop(key):
global check
if key == keyboard.KeyCode(char='p'):
check = 'stop'
return False
with keyboard.Listener(on_release=Start) as listener:
listener.join()
listener = keyboard.Listener(on_release=Stop)
listener.start()
while True:
if check == 'stop':
print("\nLoop Stopped...!")
break
for pick in english:
if check != 'stop':
index = english.index(pick)
eng = pick
tra = turkish[index]
print(index, "-> ", eng, "-", tra)
text_eng = eng
my_eng_obj = gTTS(text=eng, lang="en", slow=False)
text_eng = text_eng.replace(" ", "_")
try:
file_en = pathlib.Path(text_eng + ".mp3")
if file_en.exists():
song_s = AudioSegment.from_mp3(file_en)
play(song_s)
pass
else:
my_eng_obj.save(text_eng + ".mp3")
song_s = AudioSegment.from_mp3(file_en)
play(song_s)
except:
pass
time.sleep(0.2)
Currently, play() function catches and suppresses the
KeyboardInterrupt
exception. Programmers can assume that audio will of course stop as it currently does, but, theKeyboardInterrupt
is catchable in their code. It would be nice if the exception is reraised to the outside of the function so that the programmer has more control over whether to keep executing or to handle the exception.Steps to reproduce
Press Ctrl-C while the audio is playing.
Expected behavior
The audio stops and KeyboardInterrupt is raised to the outside of the library
Actual behavior
The audio stops then no exception is raised.
Your System configuration