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

I am trying to create a ChatBot, VA, in Python, for receiving audio output I have the packages gtts(google text to speech), playsound, and have used system os to save the audio file before playing.

The Code is below:

from gtts import gTTS
import speech_recognition as sr
import playsound
import os #to save the file
import time


def speak(text):#this defines the function SPEAK and creates the command for its use
           tts = gTTS(text=text, lang="en")
           filename = "voice.mp3"
           tts.save(filename) #saves the audio file
           playsound.playsound(filename)

       #function ends here

To play the audio I use the function in the following way:

>>>speak("I am speaking this text")

The above ^^^ works perfectly fine, but when I use multiple statements like:

>>>speak("I am saying this")
>>>speak("And also this!")

It gives an error:

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

Which I figured was due to matching names of audio files. But then when I tried to use a loop to change the number every time, it still showed the error after playing the audio for a specified number of times. Can someone please give me a solution to this? Thanks!



Solution 1:[1]

You are not allowed to overwrite the file voice.mp3 from a different call of the function. What you need to do is delete the voice.mp3 file after you play the file. So:

def speak(text):#this defines the function SPEAK and creates the command for its use
       tts = gTTS(text=text, lang="en")
       filename = "voice.mp3"
       tts.save(filename) #saves the audio file
       playsound.playsound(filename)
       os.remove(filename)

Make sure that you are not storing the file in a sensitive location, and your working directory is somewhere in documents or downloads or something.

Solution 2:[2]

Sounds like a file permission issue when the function is running it is overwriting the existing file

I would check that the user/group which is running the code has permission to read/write

How this is done depends if you are using windows, mac or linux

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sanjit Sarda
Solution 2 clcordell