Python PyGame没有';不要在.mp3文件第二次使用时关闭它
我有一个用Python编写的文本到语音程序,我目前正试图在每个操作系统上使用它,就像以前它依赖Windows Media Player一样。我正试图使用PyGame来达到这个目的,但是在第二次使用它之后,它没有正确地关闭.mp3文件。当它第一次加载.mp3文件时,它将成功退出该文件并允许程序删除该文件,但如果用户选择重试并制作另一个文本到语音,则.mp3文件无法正确退出,并且程序无法删除该文件Python PyGame没有';不要在.mp3文件第二次使用时关闭它,python,python-3.x,audio,pygame,text-to-speech,Python,Python 3.x,Audio,Pygame,Text To Speech,我有一个用Python编写的文本到语音程序,我目前正试图在每个操作系统上使用它,就像以前它依赖Windows Media Player一样。我正试图使用PyGame来达到这个目的,但是在第二次使用它之后,它没有正确地关闭.mp3文件。当它第一次加载.mp3文件时,它将成功退出该文件并允许程序删除该文件,但如果用户选择重试并制作另一个文本到语音,则.mp3文件无法正确退出,并且程序无法删除该文件 import os import time import sys import getpass imp
import os
import time
import sys
import getpass
import pip
from contextlib import contextmanager
my_file = "Text To Speech.mp3"
username = getpass.getuser()
@contextmanager
def suppress_output():
with open(os.devnull, "w") as devnull:
old_stdout = sys.stdout
sys.stdout = devnull
try:
yield
finally:
sys.stdout = old_stdout
def check_and_remove_file():
if os.path.isfile(my_file):
os.remove(my_file)
def input_for_tts(message):
try:
tts = gTTS(text = input(message))
tts.save('Text To Speech.mp3')
audio = MP3(my_file)
audio_length = audio.info.length
pygame.mixer.init()
pygame.mixer.music.load(my_file)
pygame.mixer.music.play()
time.sleep((audio_length) + 0.5)
pygame.mixer.music.stop()
pygame.mixer.quit()
pygame.quit()
check_and_remove_file()
except KeyboardInterrupt:
check_and_remove_file()
print("\nGoodbye!")
sys.exit()
with suppress_output():
pkgs = ['mutagen', 'gTTS', 'pygame']
for package in pkgs:
if package not in pip.get_installed_distributions():
pip.main(['install', package])
import pygame
from pygame.locals import *
from gtts import gTTS
from mutagen.mp3 import MP3
check_and_remove_file()
input_for_tts("Hello there " + username + ". This program is\nused to output the user's input as speech.\nPlease input something for the program to say: ")
while True:
try:
answer = input("\nDo you want to repeat? (Y/N) ").strip().lower()
if answer in ["n"] or "no" in answer or "nah" in answer or "nay" in answer or "course not" in answer:
check_and_remove_file()
sys.exit()
elif answer in ["y"] or "yes" in answer or "yeah" in answer or "course" in answer:
input_for_tts("\nPlease input something for the program to say: ")
else:
print("\nSorry, I didn't understand that. Please try again with either Y or N.")
except KeyboardInterrupt:
check_and_remove_file()
print("\nGoodbye!")
sys.exit()
只是一些提高代码可读性的技巧:1。将所有导入放在程序的顶部,以便很容易看到代码的依赖项。2.仅在再现异常的行中使用try except,而不是在整个程序中使用try except(在这种情况下,它将围绕
input
函数)。3.将新行放在三个引号之前(括号之后),以便缩进比最低缩进高一级,这可能会令人困惑/难以阅读(简短演示)@TedKleinBergman模块的导入必须在软件包的pip安装之后进行;如果这是第一次在新的计算机上运行,它将尝试在安装模块之前导入模块,这显然不起作用。三重引号的作用是在输出中创建一个空行,以便在运行程序时更容易将新文本与程序区分开来。但是,我已经将try的位置更改为输入
函数。我不好,那我就明白为什么要将导入放在不同的位置了。尽管如此,为什么不在字符串的开头加一个\n
,而不是在三个引号中加一个实际的新行字符呢?我知道你想要的是问题的答案(不幸的是我没有),而不是提高可读性的建议,但这可能会提高其他人回答问题的机会。@TedKleinBergman谢谢,我不知道\n
。它现在已经被实现到代码中。