0

On Linux, the following example works fine:

import pygame
from gtts import gTTS

pygame.mixer.init()

t = 'temp.mp3'
for i in range(5):
    gTTS(str(i)).save(t)
    pygame.mixer.music.load(t)
    pygame.mixer.munic.play()

This will play the numbers 0-4.

On Windows, the same code will cause the error:

PermissionError: [Errno 13] Permission denied: 'temp3.mp3'

when i==1. That is, it crashes on the second loop. The crash is inside of gTTS.save at:

with open(savefile, 'wb') as f: 
    self.write_to_fp(f)

As a work around, I've also tried:

with tempfile.TemporaryFile() as t:
    gTTS(str(i)).save(t)
    pygame.mixer.music.load(t)
    pygame.mixer.munic.play()

but get the error

error: Couldn't read from RWops     

It's also worth noting that this is a minimal example that fails every time. In my full code, I usually write and play infrequently, which is successful, and I can play from temp.py multiple times in the same script. The issue appears to occur only if I attempt to write and read back-to-back multiple times.

Jessime Kirk
  • 654
  • 1
  • 6
  • 13
  • Try using `NamedTemporaryFile()` and passing `t.name` instead of `t` to the two functions in the `with` clause. – martineau Apr 24 '17 at 03:25
  • Interestingly, this fails in a third way. I get `PermissionError` again, at the tempfile location (in AppData/Local), but it crashes on the first loop inside of `gTTS.save()`: `with open(savefile, 'wb') as f: self.write_to_fp(f)` I tried running as administrator, but the error occurs either way. – Jessime Kirk Apr 24 '17 at 03:41
  • With your linux code, the `PermissionError` on Windows for `i==1` could be due to the fact that the playing of the file from the previous iteration hasn't finished—so the file is still in use. Unsure because you didn't say what line of code causes the exception. – martineau Apr 24 '17 at 03:56
  • The original exception also comes from the `gTTS.save` function. I've edited my answer to reflect this. I think you're right that the file is still in use. But finishing playing doesn't seem to release the file. I've found a work around, which basically involves loading a second `temp2.mp3` file, which never changes, them writing to and reloading the original `temp.mp3`. It's a hack, but it seems to work for my purposes. – Jessime Kirk Apr 24 '17 at 04:08

0 Answers0