pythonpython-3.xspydergttspython-playsound

Playsound only plays the mp3 file once and then gives the error "Permission Denied"


I am using Playsound and gtts in Spyder IDE which creates an mp3 file and then plays it.

import gtts
from playsound import playsound
#pass text to gTTS object 

# make request to google to get synthesis
english = gtts.gTTS("Hello world") #retrieved the actual audio speech from the API

# save the audio file
english.save("hello.mp3")
# play the audio file
playsound("hello.mp3")

It plays fine the first time but then shows this every time I run it:

  File "C:\Users\ASUS\.spyder-py3\all codes\Text2Speech.py", line 27, in <module>
    english.save("hello.mp3")

  File "C:\Users\ASUS\AppData\Local\Programs\Python\Python39\Lib\site-packages\gtts\tts.py", line 312, in save
    with open(str(savefile), 'wb') as f:

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

It works fine again after I restart Spyder, then again doesn't work after playing only once. My OS is Windows 10, Playsound version 1.2.2


Solution

  • I know this question is a bit old but I'll leave this here just in case anyone else struggles with it.

    I had a similar problem with my code, I was building a voice assistant that uses input from your microphone then speaks back to you using gTTS and playsound. It would only work once then after the mp3 file is created, it can no longer be used again with a second voice command.

    The solution I found was either giving the file a different name every single time you create it (which would create a mess in most cases), or deleting the file after it is used.

    Here is what my "speak" function looks like, it just saves the text to sound translation into an mp3 file then plays it. At the end I added os.remove(file_path) with file_path being the file name itself or the path to it.

    def speak(text):
        tts = gTTS(text=text, lang="en")
        filename = "voice.mp3"
        tts.save(filename)
        playsound.playsound(filename)
        os.remove("voice.mp3")
    

    This solution only works if this specific mp3 file is being used by the program to "speak" back to you, since it rarely ever needs to go back to what it said before, the file is temporary and deleting it doesn't do any harm.