如何检查混合系统是否在Pygame中初始化



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

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

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

相关内容

  • 没有找到相关文章

最新更新