0
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'
2
  • Not a urllib issue (btw, you may want to use requests instead), unless urllib didn't close() it. Your program couldn't open the file for writing. Do you have it open somewhere else? Commented Jun 21, 2017 at 8:47
  • 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.
    – BoboDarph
    Commented Jun 21, 2017 at 8:53

1 Answer 1

2

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.

1
  • as you said pygame still holding the mp3 mixer.music.stop() worked!
    – FKLC
    Commented May 31, 2018 at 13:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.