I have a text-to-speech program in Python that I'm currently trying to get to work on every operating system, as before it relied on Windows Media Player. I'm trying to use PyGame to achieve this purpose, however it does not close the .mp3 file properly after using it the second time. When it loads the .mp3 file for the first time it will successfully exit it and allow the program to delete the file, but if the user opts to try again and make another text-to-speech, the .mp3 file does not exit properly and the program is unable to delete it.
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()