如何检查混音器系统是否在Pygame中初始化?

时间:2017-05-27 19:02:22

标签: python python-3.x audio pygame text-to-speech

我有一些代码需要知道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()

1 个答案:

答案 0 :(得分:1)

要检查pygame.mixer是否已初始化,您需要做的只是pygame.mixer.get_init(),它将返回当前播放的音频数据,除非它未初始化,在这种情况下它将返回None

来源:https://www.pygame.org/docs/ref/mixer.html#pygame.mixer.get_init