jiaaro / pydub

Manipulate audio with a simple and easy high level interface
http://pydub.com
MIT License
8.87k stars 1.04k forks source link

Don't suppress KeyboardInterrupt in play() #571

Open cosine0 opened 3 years ago

cosine0 commented 3 years ago

Currently, play() function catches and suppresses the KeyboardInterrupt exception. Programmers can assume that audio will of course stop as it currently does, but, the KeyboardInterrupt 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

from pydub import AudioSegment
from pydub.playback import play

sound = AudioSegment.from_file(filename, format="mp3")
try:
    play(sound)
except KeyboardInterrupt:
    print('interrupted)

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

bbbirkan commented 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)