【发布时间】:2017-05-27 19:02:21
【问题描述】:
我有一些代码需要知道 Pygame 中的混音器系统是否已初始化,以便知道何时退出它,因为目前 Pygame 似乎没有正确退出。我有一个 Python 文本到语音的程序,我目前正试图在每个操作系统上工作,就像它之前依赖于 Windows Media Player 一样。我正在尝试使用 Pygame 来实现此目的,但是在第二次使用 Pygame 后它并没有正确关闭它。当它第一次加载 .mp3 文件时,它将成功退出 Pygame 并允许程序删除该文件,但如果用户选择重试并制作另一个文本转语音,它将重新初始化 Pygame,写入文件,打开然后播放文件。文件播放完毕后,它会尝试退出 Pygame,但是 Pygame 无法正常关闭,程序无法删除当前正在使用的 .mp3 文件。
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", "no", "nah", "nay", "course not"] 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", "yes", "yeah", "course", "ye", "yea", "yh"] or "yes " in answer or "yeah " in answer or "course " in answer or "ye " in answer or "yea " in answer or "yh " 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()
【问题讨论】:
标签: python python-3.x audio pygame text-to-speech