Anon
Anon

Reputation: 1846

pygame does not close files after play

from urllib.request import URLopener
from urllib.parse   import quote
from pygame import mixer

def speak(text):
    downloader = URLopener()
    downloader.addheader('Referer', 'https://translate.google.com/')
    downloader.addheader('User-agent', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36')
    downloader.retrieve('https://translate.google.com/translate_tts?ie=UTF-8&q={0}&tl=en&client=tw-ob'.format(quote(text)), 'storage/tts.mp3')
    mixer.init()
    mixer.music.load('storage/tts.mp3')
    mixer.music.play()

Here is the mine code when I try to use funtion in second time it gives me error(sorry for bad english)

downloader.retrieve('https://translate.google.com/translate_tts?ie=UTF-8&q={
    0}&tl=en&client=tw-ob'.format(quote(text)), 'storage/tts.mp3')
      File "C:\Users\pc\AppData\Local\Programs\Python\Python36-32\lib\urllib\request
    .py", line 1800, in retrieve
        tfp = open(filename, 'wb')
    PermissionError: [Errno 13] Permission denied: 'storage/tts.mp3'

Upvotes: 0

Views: 433

Answers (1)

BoboDarph
BoboDarph

Reputation: 2891

Seems to be a permission denied on the file caused by the retrieve call, possibly cased by the fact that your mixer is still holding handles on that file. Suggest stopping the play with

mixer.music.stop()

If that doesnt work, try opening the file before you retrieve it

from urllib.request import URLopener
from urllib.parse   import quote
from pygame import mixer

def speak(text):
    downloader = URLopener()
    downloader.addheader('Referer', 'https://translate.google.com/')
    downloader.addheader('User-agent', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36')
    mp3_file = open('storage/tts.mp3')
    downloader.retrieve('https://translate.google.com/translate_tts?ie=UTF-8&q={0}&tl=en&client=tw-ob'.format(quote(text)), mp3_file)
    mixer.init()
    mixer.music.load('storage/tts.mp3')
    mixer.music.play()
    mixer.music.stop()
    mp3_file.close()

More details here https://groups.google.com/forum/#!topic/pygame-mirror-on-google-groups/XjSh9zs8j0U

Also consider removing the file when you're done with it.

Upvotes: 2

Related Questions