0

I am Getting an Error when Writing to an Audio File Basically, I am overwriting the data in the mp3 whenever my function gets called and then playing it. It works the first time through, but then it gives me PermissionError: [Errno 13] Permission denied: 'audio.mp3'.

Here is the Code.

# Importing Essentials
from gtts import gTTS # for converting text to speech
from playsound import playsound # for Playing Converted Audio


# Creating main Function
def speak(text, language):
    # Specifying Speed, Text and Language of the Audio and Generating it.
    audio = gTTS(text=text, lang=language, slow=False, tld="com")

    # Saving the Audio as audio.mp3
    audio.save("audio.mp3")

    # Playing the Converted Audio
    playsound("audio.mp3")


# Running Main Programm
if __name__ == "__main__":
    # Print Welcome Message.
    print("--------------------- Welcome to RoboSpeaker -----------------------")
    print("Press 'q' to quit.")

    while True:
        # Get Text as Input from the User.
        print("Please Enter the Text Which You Want this Programm to Play(Don't Include any Punctuation).")
        text = input(":- ")

        # Selecting Language in Which We want to convert the Audio.
        language = "en"

        # Exit the Programm if input is q
        if text == "q":
            break
        
        # Runnign Speak Function
        speak(text, language)

This is the Error Message.

Please Enter the Text Which You Want this Programm to Play(Don't Include any Punctuation).
:- Hi Praddyumn yadav
Traceback (most recent call last):
  File "C:\Users\RAJU\Documents\RoboSpeaker\main.py", line 40, in <module>
    speak(text, language)
  File "C:\Users\RAJU\Documents\RoboSpeaker\main.py", line 12, in speak
    audio.save("audio.mp3")
  File "C:\Users\RAJU\Documents\RoboSpeaker\venv\Lib\site-packages\gtts\tts.py", line 324, in save
    with open(str(savefile), "wb") as f:
         ^^^^^^^^^^^^^^^^^^^^^^^^^
PermissionError: [Errno 13] Permission denied: 'audio.mp3'

Thank You

  • Does it happen if you run under root? – Vojtěch Chvojka Mar 28 '23 at 07:32
  • 1
    I suspect that playsound doesn't close the file after it's been played. – molbdnilo Mar 28 '23 at 07:32
  • (Tangentially, code you put in `if __name__ == '__main__':` should be trivial; the purpose of this boilerplate is to allow you to `import` the code, which you will not want to do anyway if the logic you need is not available via `import`. See also https://stackoverflow.com/a/69778466/874188) – tripleee Mar 28 '23 at 07:35
  • I second @molbdnilo's guess. Try if adding `logging.getLogger("playsound").setLevel(logging.DEBUG)` gives you anything useful, especially a potential warning à la ["Failed to close the file"](https://github.com/TaylorSMarks/playsound/blob/master/playsound.py#L62). – Jeronimo Mar 28 '23 at 09:32

0 Answers0