游戏后pygame不会关闭文件

时间:2017-06-21 08:08:09

标签: python windows urllib python-3.6

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()

这是我第二次尝试使用功能时的地雷代码,它给了我错误(抱歉英语不好)

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'

1 个答案:

答案 0 :(得分:2)

似乎是由检索调用引起的文件权限被拒绝,可能是由于您的调音台仍然在该文件上持有句柄这一事实。建议用

停止游戏
mixer.music.stop()

如果不起作用,请在检索之前尝试打开文件

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()

此处有更多详情https://groups.google.com/forum/#!topic/pygame-mirror-on-google-groups/XjSh9zs8j0U

另外,请考虑在使用该文件时删除该文件。