Pygame doesn't close properly so I can't delete the file it's using

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
18 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Pygame doesn't close properly so I can't delete the file it's using

Gameskiller01
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 Pygame properly after using it the second time. When it loads the .mp3 file for the first time it will successfully exit Pygame and allow the program to delete the file, but if the user opts to try again and make another text-to-speech, it will re-initialize Pygame, write the file, open and then play the file. After the file has finished playing it will try to exit Pygame, however Pygame does not close properly and the program is unable to delete the .mp3 file.

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()
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Pygame doesn't close properly so I can't delete the file it's using

Daniel Foerster
Try making a call to pygame.quit() when your program exits.


On 05/27/2017 02:05 PM, Gameskiller01 wrote:

> 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
> Pygame properly after using it the second time. When it loads the .mp3 file
> for the first time it will successfully exit Pygame and allow the program to
> delete the file, but if the user opts to try again and make another
> text-to-speech, it will re-initialize Pygame, write the file, open and then
> play the file. After the file has finished playing it will try to exit
> Pygame, however Pygame does not close properly and the program is unable to
> delete the .mp3 file.
>
>
>
>
>
>
> --
> View this message in context: http://pygame-users.25799.x6.nabble.com/Pygame-doesn-t-close-properly-so-I-can-t-delete-the-file-it-s-using-tp3044.html
> Sent from the pygame-users mailing list archive at Nabble.com.

Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Pygame doesn't close properly so I can't delete the file it's using

Gameskiller01
It already does.
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Pygame doesn't close properly so I can't delete the file it's using

Noel Garwick
Could you post the source somewhere?

I think another reason those files are staying locked could be if you aren't calling filename.close()

On May 28, 2017 4:19 AM, "Gameskiller01" <[hidden email]> wrote:
It already does.



--
View this message in context: http://pygame-users.25799.x6.nabble.com/Pygame-doesn-t-close-properly-so-I-can-t-delete-the-file-it-s-using-tp3044p3046.html
Sent from the pygame-users mailing list archive at Nabble.com.
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Pygame doesn't close properly so I can't delete the file it's using

Luke Paireepinart
Do you have an outer python program with some control loop and inside that loop you are initializing pygame, generating the mp3, quitting pygame and then deleting the file in the same program? If so, I don't think that's how pygame is meant to be used. Why don't you initialize it once and not quit until the program is terminated? You might need to also purge the event queue of pygame too. I agree though, need to see code.

On May 28, 2017 8:55 AM, "Noel Garwick" <[hidden email]> wrote:
Could you post the source somewhere?

I think another reason those files are staying locked could be if you aren't calling filename.close()

On May 28, 2017 4:19 AM, "Gameskiller01" <[hidden email]> wrote:
It already does.



--
View this message in context: http://pygame-users.25799.x6.nabble.com/Pygame-doesn-t-close-properly-so-I-can-t-delete-the-file-it-s-using-tp3044p3046.html
Sent from the pygame-users mailing list archive at Nabble.com.
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Pygame doesn't close properly so I can't delete the file it's using

Gameskiller01
The code should be in the original message (I can see it in there). Just in case, here it is again:

import os
import time
import sys
import getpass
import pip
import imp
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():

    active = pygame.mixer.get_init()
    if active != None:
        pygame.mixer.music.stop()
        pygame.mixer.quit()
        pygame.quit()
    if os.path.isfile(my_file):
        os.remove(my_file)


def wait_for_it(audio_length, greater_than, less_than, time_to_wait):

    if (audio_length) >= (greater_than) and (audio_length) < (less_than):
        time.sleep((audio_length) + (time_to_wait))


def exiting():

    check_and_remove_file()
    print("\nGoodbye!")
    sys.exit()


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
        try:
            pygame.mixer.init()
        except pygame.error:
            print("\nSorry, no audio device was detected. The code cannot complete.")
            exiting()
        bp = pyglet.resource.media(my_file)
        bp.play()
        wait_for_it(audio_length, 0, 15, 1)
        wait_for_it(audio_length, 15, 30, 2)
        wait_for_it(audio_length, 30, 45, 3)
        wait_for_it(audio_length, 45, 60, 4)
        wait_for_it(audio_length, 60, 75, 5)
        wait_for_it(audio_length, 75, 90, 6)
        wait_for_it(audio_length, 90, 105, 7)
        wait_for_it(audio_length, 105, 120, 8)
        wait_for_it(audio_length, 120, 135, 9)
        wait_for_it(audio_length, 135, 150, 10)
        wait_for_it(audio_length, 150, 165, 11)
        wait_for_it(audio_length, 165, 180, 12)
        if audio_length >= 180:
            time.sleep((audio_length) + 15)
        try:
            check_and_remove_file()
        except PermissionError:
            imp.reload(pygame)
            check_and_remove_file()

    except KeyboardInterrupt:

        exiting()


with suppress_output():

    pkgs = ['mutagen', 'gTTS', 'pygame', 'pyglet']
    for package in pkgs:
        if package not in pip.get_installed_distributions():
            pip.main(['install', package])


import pyglet
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? ").strip().lower()
        if answer in ["n", "no", "nah", "nay", "course not", "don't", "dont", "not"] or "no" in answer or "nah" in answer or "nay" in answer or "course not" in answer or "don't" in answer or "dont" in answer or "not" in answer:
            exiting()
        elif answer in ["y", "yes", "yeah", "course", "ye", "yea", "yh", "do"] or "yes" in answer or "yeah" in answer or "course" in answer or "ye" in answer or "yea" in answer or "yh" in answer or "do" 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 yes or no.")

    except KeyboardInterrupt:

        exiting()
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Pygame doesn't close properly so I can't delete the file it's using

Gameskiller01
In reply to this post by Noel Garwick
When I do my_file.close() I get:

   my_file.close()
AttributeError: 'str' object has no attribute 'close'
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Pygame doesn't close properly so I can't delete the file it's using

Jake b
That's because my_file is a string, not a file handle.

my_file = "Text To Speech.mp3"


When using with open, the file is closed when the context handler ends


Note: In the email, your code did not get posted. I think it has something to do with nabble. When I clicked on that, then, I do see a couple different versions.

Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Pygame doesn't close properly so I can't delete the file it's using

Gameskiller01
Well I tried:

my_file = "Text To Speech.mp3"
opened = open(my_file)

opened.close()

But it still gave the PermissionError when trying to delete the file.
In the handling of that error, it tries to reload Pygame. In doing so, it gives an AttributeError, explained in detail here. Does this have anything to do with it?
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Pygame doesn't close properly so I can't delete the file it's using

Martin Kühne
Please regard distinct issues as distinct.

Yes, opened.close() is the right thing to do as far as opening and
closing files goes.

I think the del pygame.imageext exception is an accident, since
actually, pygame should catch AtrributeError there.

As for the PermissionError; are you sure you didn't have the file open
in another program?
Focus on that part, since the rest is happening accidentally.

cheers!
mar77i
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Pygame doesn't close properly so I can't delete the file it's using

Gameskiller01
It may be an accident, but it's a consistent one. The file is open in no other programs, and I still get the PermissionError after a restart if I open up the file as soon as I boot my PC. It also successfully deletes the file the first time it tries, but not the second. The AttributeError happens every time I try to reload pygame.
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Pygame doesn't close properly so I can't delete the file it's using

DR0ID
In reply to this post by Gameskiller01
On 28.05.2017 17:57, Gameskiller01 wrote:

> 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
>          try:
>              pygame.mixer.init()
>          except pygame.error:
>              print("\nSorry, no audio device was detected. The code cannot
> complete.")
>              exiting()
>          bp = pyglet.resource.media(my_file)
>          bp.play()


Hi there

Isn't that code playing the file using pyglet?

         bp = pyglet.resource.media(my_file)
         bp.play()

I wonder, why and what are you using pyglet for?

I don't think that pyglet is using pygame as a audio backend... but I
might be wrong, but pyglet might lock the file (or whatever backend
pyglet is using for audio).

Maybe try to remove pyglet (since its only used to play the file?) and
see how it goes.

Or I may ask the other way around: why and what are you using pygame for?

If the reason you are using pyglet is because it can play mp3 and pygame
can't, then why bother with pygame at all?


Maybe one of my question will help you figure the problem out.


~DR0ID


Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Pygame doesn't close properly so I can't delete the file it's using

Gameskiller01
Sorry, I posted the wrong code. That code is from when i was trying to use Pyglet instead of Pygame to open the file and see if that would work This is the actual code.

import os
import time
import sys
import getpass
import pip
import imp
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():

    active = pygame.mixer.get_init()
    if active != None:
        pygame.mixer.music.stop()
        pygame.mixer.quit()
        pygame.quit()
    if os.path.isfile(my_file):
        os.remove(my_file)


def wait_for_it(audio_length, greater_than, less_than, time_to_wait):

    if (audio_length) >= (greater_than) and (audio_length) < (less_than):
        time.sleep((audio_length) + (time_to_wait))


def exiting():

    check_and_remove_file()
    print("\nGoodbye!")
    sys.exit()


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
        try:
            pygame.mixer.init()
        except pygame.error:
            print("\nSorry, no audio device was detected. The code cannot complete.")
            exiting()
        pygame.mixer.music.load(my_file)
        pygame.mixer.music.play()
        wait_for_it(audio_length, 0, 15, 1)
        wait_for_it(audio_length, 15, 30, 2)
        wait_for_it(audio_length, 30, 45, 3)
        wait_for_it(audio_length, 45, 60, 4)
        wait_for_it(audio_length, 60, 75, 5)
        wait_for_it(audio_length, 75, 90, 6)
        wait_for_it(audio_length, 90, 105, 7)
        wait_for_it(audio_length, 105, 120, 8)
        wait_for_it(audio_length, 120, 135, 9)
        wait_for_it(audio_length, 135, 150, 10)
        wait_for_it(audio_length, 150, 165, 11)
        wait_for_it(audio_length, 165, 180, 12)
        if audio_length >= 180:
            time.sleep((audio_length) + 15)
        try:
            check_and_remove_file()
        except PermissionError:
            imp.reload(pygame)
            check_and_remove_file()

    except KeyboardInterrupt:

        exiting()


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? ").strip().lower()
        if answer in ["n", "no", "nah", "nay", "course not", "don't", "dont", "not"] or "no" in answer or "nah" in answer or "nay" in answer or "course not" in answer or "don't" in answer or "dont" in answer or "not" in answer:
            exiting()
        elif answer in ["y", "yes", "yeah", "course", "ye", "yea", "yh", "do"] or "yes" in answer or "yeah" in answer or "course" in answer or "ye" in answer or "yea" in answer or "yh" in answer or "do" 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 yes or no.")

    except KeyboardInterrupt:

        exiting()
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Pygame doesn't close properly so I can't delete the file it's using

DR0ID
On 28.05.2017 20:21, Gameskiller01 wrote:

> Sorry, I posted the wrong code. That code is from when i was trying to use
> Pyglet instead of Pygame to open the file and see if that would work This is
> the actual code.
>
> import os
> import time
> import sys
> import getpass
> import pip
> import imp
> 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():
>
>      active = pygame.mixer.get_init()
>      if active != None:
>          pygame.mixer.music.stop()
>          pygame.mixer.quit()
>          pygame.quit()
>      if os.path.isfile(my_file):
>          os.remove(my_file)
>
>
> def wait_for_it(audio_length, greater_than, less_than, time_to_wait):
>
>      if (audio_length) >= (greater_than) and (audio_length) < (less_than):
>          time.sleep((audio_length) + (time_to_wait))
>
>
> def exiting():
>
>      check_and_remove_file()
>      print("\nGoodbye!")
>      sys.exit()
>
>
> 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
>          try:
>              pygame.mixer.init()
>          except pygame.error:
>              print("\nSorry, no audio device was detected. The code cannot
> complete.")
>              exiting()
>          pygame.mixer.music.load(my_file)
>          pygame.mixer.music.play()
>          wait_for_it(audio_length, 0, 15, 1)
>          wait_for_it(audio_length, 15, 30, 2)
>          wait_for_it(audio_length, 30, 45, 3)
>          wait_for_it(audio_length, 45, 60, 4)
>          wait_for_it(audio_length, 60, 75, 5)
>          wait_for_it(audio_length, 75, 90, 6)
>          wait_for_it(audio_length, 90, 105, 7)
>          wait_for_it(audio_length, 105, 120, 8)
>          wait_for_it(audio_length, 120, 135, 9)
>          wait_for_it(audio_length, 135, 150, 10)
>          wait_for_it(audio_length, 150, 165, 11)
>          wait_for_it(audio_length, 165, 180, 12)
>          if audio_length >= 180:
>              time.sleep((audio_length) + 15)
>          try:
>              check_and_remove_file()
>          except PermissionError:
>              imp.reload(pygame)
>              check_and_remove_file()
>
>      except KeyboardInterrupt:
>
>          exiting()
>
>
> 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? ").strip().lower()
>          if answer in ["n", "no", "nah", "nay", "course not", "don't",
> "dont", "not"] or "no" in answer or "nah" in answer or "nay" in answer or
> "course not" in answer or "don't" in answer or "dont" in answer or "not" in
> answer:
>              exiting()
>          elif answer in ["y", "yes", "yeah", "course", "ye", "yea", "yh",
> "do"] or "yes" in answer or "yeah" in answer or "course" in answer or "ye"
> in answer or "yea" in answer or "yh" in answer or "do" 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
> yes or no.")
>
>      except KeyboardInterrupt:
>
>          exiting()
>
>
>
> --
> View this message in context: http://pygame-users.25799.x6.nabble.com/Pygame-doesn-t-close-properly-so-I-can-t-delete-the-file-it-s-using-tp3044p3057.html
> Sent from the pygame-users mailing list archive at Nabble.com.
>
Hi again

ok... errors happen.

I wonder one thing: can't it be played as a sound? (actually not sure
how this would help your problem)


The other idea I head is: load the file to memory and close it properly
after reading it and let pygame read the in memory file (probably as a
file like object). I'm not sure how easy it would be to do (not sure
where the limitation are).

~DR0ID

Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Pygame doesn't close properly so I can't delete the file it's using

Martin Kühne
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Pygame doesn't close properly so I can't delete the file it's using

Gameskiller01
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Pygame doesn't close properly so I can't delete the file it's using

Gameskiller01
In reply to this post by DR0ID
Thank you very much! Using the code:

with open(my_file) as f:
    m = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)

pygame.mixer.music.load(m)
pygame.mixer.music.play()

m.close()

The code now finally works! I haven't been this happy for a long time!

Full code:

import os
import time
import sys
import getpass
import pip
import mmap
import imp
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():

    active = pygame.mixer.get_init()
    if active != None:
        pygame.mixer.music.stop()
        pygame.mixer.quit()
        pygame.quit()
    if os.path.isfile(my_file):
        os.remove(my_file)


def wait_for_it(audio_length, greater_than, less_than, time_to_wait):

    if (audio_length) >= (greater_than) and (audio_length) < (less_than):
        time.sleep((audio_length) + (time_to_wait))


def exiting():

    check_and_remove_file()
    print("\nGoodbye!")
    sys.exit()


def input_for_tts(message):

    try:

        tts = gTTS(text = input(message))
        tts.save('Text To Speech.mp3')
       
        with open(my_file) as f:
            m = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
        audio = MP3(my_file)
        audio_length = audio.info.length
        try:
            pygame.mixer.init()
        except pygame.error:
            print("\nSorry, no audio device was detected. The code cannot complete.")
            exiting()
        pygame.mixer.music.load(m)
        pygame.mixer.music.play()
        wait_for_it(audio_length, 0, 15, 1)
        wait_for_it(audio_length, 15, 30, 2)
        wait_for_it(audio_length, 30, 45, 3)
        wait_for_it(audio_length, 45, 60, 4)
        wait_for_it(audio_length, 60, 75, 5)
        wait_for_it(audio_length, 75, 90, 6)
        wait_for_it(audio_length, 90, 105, 7)
        wait_for_it(audio_length, 105, 120, 8)
        wait_for_it(audio_length, 120, 135, 9)
        wait_for_it(audio_length, 135, 150, 10)
        wait_for_it(audio_length, 150, 165, 11)
        wait_for_it(audio_length, 165, 180, 12)
        if audio_length >= 180:
            time.sleep((audio_length) + 15)
        try:
            m.close()
            check_and_remove_file()
        except PermissionError:
            imp.reload(pygame)
            check_and_remove_file()

    except KeyboardInterrupt:

        exiting()


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? ").strip().lower()
        if answer in ["n", "no", "nah", "nay", "course not", "don't", "dont", "not"] or "no" in answer or "nah" in answer or "nay" in answer or "course not" in answer or "don't" in answer or "dont" in answer or "not" in answer:
            exiting()
        elif answer in ["y", "yes", "yeah", "course", "ye", "yea", "yh", "do"] or "yes" in answer or "yeah" in answer or "course" in answer or "ye" in answer or "yea" in answer or "yh" in answer or "do" 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 yes or no.")

    except KeyboardInterrupt:

        exiting()
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Pygame doesn't close properly so I can't delete the file it's using

Luke Paireepinart
The wait for it calls can all be done in a loop, is there a reason for having them all listed out?

On May 28, 2017 4:01 PM, "Gameskiller01" <[hidden email]> wrote:
Thank you very much! Using the code:

with open(my_file) as f:
    m = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)

pygame.mixer.music.load(m)
pygame.mixer.music.play()

m.close()

The code now finally works! I haven't been this happy for a long time!

Full code:

import os
import time
import sys
import getpass
import pip
import mmap
import imp
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():

    active = pygame.mixer.get_init()
    if active != None:
        pygame.mixer.music.stop()
        pygame.mixer.quit()
        pygame.quit()
    if os.path.isfile(my_file):
        os.remove(my_file)


def wait_for_it(audio_length, greater_than, less_than, time_to_wait):

    if (audio_length) >= (greater_than) and (audio_length) < (less_than):
        time.sleep((audio_length) + (time_to_wait))


def exiting():

    check_and_remove_file()
    print("\nGoodbye!")
    sys.exit()


def input_for_tts(message):

    try:

        tts = gTTS(text = input(message))
        tts.save('Text To Speech.mp3')

        with open(my_file) as f:
            m = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
        audio = MP3(my_file)
        audio_length = audio.info.length
        try:
            pygame.mixer.init()
        except pygame.error:
            print("\nSorry, no audio device was detected. The code cannot
complete.")
            exiting()
        pygame.mixer.music.load(m)
        pygame.mixer.music.play()
        wait_for_it(audio_length, 0, 15, 1)
        wait_for_it(audio_length, 15, 30, 2)
        wait_for_it(audio_length, 30, 45, 3)
        wait_for_it(audio_length, 45, 60, 4)
        wait_for_it(audio_length, 60, 75, 5)
        wait_for_it(audio_length, 75, 90, 6)
        wait_for_it(audio_length, 90, 105, 7)
        wait_for_it(audio_length, 105, 120, 8)
        wait_for_it(audio_length, 120, 135, 9)
        wait_for_it(audio_length, 135, 150, 10)
        wait_for_it(audio_length, 150, 165, 11)
        wait_for_it(audio_length, 165, 180, 12)
        if audio_length >= 180:
            time.sleep((audio_length) + 15)
        try:
            m.close()
            check_and_remove_file()
        except PermissionError:
            imp.reload(pygame)
            check_and_remove_file()

    except KeyboardInterrupt:

        exiting()


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? ").strip().lower()
        if answer in ["n", "no", "nah", "nay", "course not", "don't",
"dont", "not"] or "no" in answer or "nah" in answer or "nay" in answer or
"course not" in answer or "don't" in answer or "dont" in answer or "not" in
answer:
            exiting()
        elif answer in ["y", "yes", "yeah", "course", "ye", "yea", "yh",
"do"] or "yes" in answer or "yeah" in answer or "course" in answer or "ye"
in answer or "yea" in answer or "yh" in answer or "do" 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
yes or no.")

    except KeyboardInterrupt:

        exiting()



--
View this message in context: http://pygame-users.25799.x6.nabble.com/Pygame-doesn-t-close-properly-so-I-can-t-delete-the-file-it-s-using-tp3044p3062.html
Sent from the pygame-users mailing list archive at Nabble.com.

Loading...