PermissionError: [Errno 13] Permission denied: 'file.mp3' - python

The program runs only twice. Later, the error occurs. I don't know why it works twice and then stops.
import tkinter, sys, pygame
from tkinter import messagebox
from gtts import gTTS
soundfile="file.mp3"
def ex():
sys.exit()
The main problem is there:
def read():
t = e.get()
tts = gTTS(text=t, lang="en")
tts.save(soundfile)
pygame.mixer.init(frequency=16000, size=-16, channels=2, buffer=4096)
pygame.mixer.music.load(soundfile)
pygame.mixer.music.set_volume(1.0)
pygame.mixer.music.play(0,0.0)
while pygame.mixer.music.get_busy()==True:
continue
pygame.quit()
Next is the code for the buttons.
def clear():
e.delete(0, 'end')
main = tkinter.Tk()
e = tkinter.Entry(main, justify = "center")
l = tkinter.Label(main, text = "Write text")
b1 = tkinter.Button(main, text = "Read", command = read)
b2 = tkinter.Button(main, text = "Clear", command = clear)
b3 = tkinter.Button(main, text = "Exit", command = ex)
So, I don't have any idea to fix it.

from gtts import gTTS
import playsound
import os
x = ['sunny', 'sagar', 'akhil']
tts = 'tts'
for i in range(0,3):
tts = gTTS(text= x[i], lang = 'en')
file1 = str("hello" + str(i) + ".mp3")
tts.save(file1)
playsound.playsound(file1,True)
os.remove(file1)
rename the file for every new save, that worked for me.

Related

Timer stops updating when an audio is played

I have used after() method to update the time remaining for quiz and converted text of question to audio using gtts module and played that using playsound module. But when the audio is played timer stops updating. How can I fix it?
import playsound
import tkinter
import gtts
import os
def speak_que():
global audio_no
sound = gtts.gTTS(question_label["text"], lang = "en")
file_name = "Audio_" + str(audio_no) + ".mp3"
sound.save(file_name)
playsound.playsound(file_name)
os.remove(file_name)
audio_no += 1
def change_time():
pre_time = int(time_label["text"])
if pre_time != 1:
time_label.config(text = pre_time-1)
time_label.after(1000, change_time)
else:
window.destroy()
window = tkinter.Tk()
audio_no = 0
time_label = tkinter.Label(window, text = "15")
time_label.after(1000, change_time)
question_label = tkinter.Label(window, text = "What is the sum of 4 and 2")
answer = tkinter.Entry(window)
speak = tkinter.Button(window, text = "Speak", command = speak_que)
time_label.pack()
question_label.pack()
answer.pack()
speak.pack()
window.mainloop()
First, make sure your speak_que() routine is completing, if not, you can install the older version of playsound 1.2.2 as the newest version tends to have issues.
pip uninstall playsound
pip install playsound==1.2.2
Next, if you want the timer to continue during speak_que() (or any two operations in parallel); you'll have to use threading, see below.
import playsound
import tkinter
import gtts
import os
from threading import *
def speak_que():
global audio_no
sound = gtts.gTTS(question_label["text"], lang = "en")
file_name = "Audio_" + str(audio_no) + ".mp3"
sound.save(file_name)
playsound.playsound(file_name)
os.remove(file_name)
audio_no += 1
def threadedSound():
t1=Thread(target=speak_que)
t1.start()
def change_time():
pre_time = int(time_label["text"])
if pre_time != 1:
time_label.config(text = pre_time-1)
time_label.after(1000, change_time)
else:
window.destroy()
window = tkinter.Tk()
audio_no = 0
time_label = tkinter.Label(window, text = "15")
time_label.after(1000, change_time)
question_label = tkinter.Label(window, text = "What is the sum of 4 and 2")
answer = tkinter.Entry(window)
speak = tkinter.Button(window, text = "Speak", command = threadedSound)
time_label.pack()
question_label.pack()
answer.pack()
speak.pack()
window.mainloop()

Why my code without errors isn't running?

I need some help! This is my code. When i press run it isn't do anything.
I've tried to install again all the modules, but no luck.
from tkinter import *
from tkinter import filedialog
import pyttsx3
from PyPDF2 import PdfFileReader
#Intializing Window
window = Tk('500x350')
window.geometry()
window.config(bg='#6C969D')
window.title("Pdf to Audio Speecch |Nick S")
#Labels
startingpagenumber = Entry(window)
startingpagenumber.place(relx=0.6,rely=0.1)
page1 = Label(window,text="Enter starting page number")
page1.place(relx=0.2,rely=0.1)
label = Label(window, text="Select a book.")
label.place(relx=0.3, rely=0.2)
def file():
path = filedialog.askopenfilename()
book = open(path, 'rb')
pdfreader = PdfFileReader(book)
pages = pdfreader.numPages
speaker = pyttsx3.init()
for i in range(int(startingpagenumber.get()), pages):
page = pdfreader.getPage(i)
txt = page.extractText()
speaker.say(txt)
speaker.runAndWait()
B = Button(window, text="Choose the Book", command=file)
B.place(relx=0.4,rely=0.3)
This is what I get in console
C:\Users\nicks\Desktop\Coding Projects\Python\Pdf to Audio>C:/Users/nicks/AppData/Local/Microsoft/WindowsApps/python3.9.exe "c:/Users/nicks/Desktop/Coding Projects/Python/Pdf to Audio/main.py"
Thanks everyone!
The problem was that I didn't include mainloop() in the end!

When I converted this .py program to an .exe file, I have problems with speech_recognition

I'm creating a Voice-Assistant in python and tkinter, and I use pyinstaller to convert it to an executable file. The command line is:
pyinstaller -F -w main.py
This is my code:
import pyttsx3
from pyttsx3.drivers import sapi5
import speech_recognition as sr
import time
from tkinter import *
from datetime import datetime
engine = pyttsx3.init()
rate = engine.getProperty("rate")
engine.setProperty("rate", 175)
volume = engine.getProperty("volume")
engine.setProperty("volume", 0.75)
voices = engine.getProperty("voices")
engine.setProperty("voice", voices[2].id)
window = Tk()
var = StringVar()
var1 = StringVar()
class App:
def __init__(self):
window.title("Voice-Assistant")
window.geometry("1280x720")
window.resizable(False, False)
window.iconbitmap(r"C:\Users\itsju\Documents\KarenDef\Projects\Karen10\IconofKaren.ico")
karenW = Frame(window, bg="#3498db")
karenW.place(relwidth=1, relheight=0.5, x=5, y=365)
spokeW = Frame(window, bg="#1a5276")
spokeW.place(relwidth=1, relheight=0.5, x=5)
karenT = Label(karenW, bg="#3498db", fg="white", font=("Consolas", 16), textvariable=var1, wraplength=1230, justify="left")
karenT.place(x=10, y=28)
spokeT = Label(spokeW, bg="#1a5276", fg="white", font=("Consolas", 16), textvariable=var, wraplength=1230, justify="left")
spokeT.place(x=10, y=28)
karenL = Label(karenW, bg="#3498db", fg="white", font=("Calibri 11 bold underline"), text="Karen")
karenL.pack()
spokeL = Label(spokeW, bg="#1a5276", fg="light blue", font=("Calibri 11 bold underline"), text="You")
spokeL.pack()
def talk(self, audio):
var1.set(audio)
window.update()
engine.say(audio)
engine.runAndWait()
def get_command(self):
r = sr.Recognizer()
with sr.Microphone() as source:
var1.set("Listening...")
window.update()
audio = r.listen(source)
spoke = ""
try:
var1.set("Recognizing...")
window.update()
spoke = r.recognize_google(audio, language='nl')
var.set(spoke)
except sr.UnknownValueError:
var1.set("Couldn't get that!")
window.update()
time.sleep(0.25)
var.set("")
except sr.RequestError:
var1.set("Check your internet connection!")
window.update()
time.sleep(0.5)
var.set("")
return spoke.lower()
a = App()
while True:
spoke = get_command()
if 'hello' in spoke:
a.talk("Hello there!")
break
So when this is converted, and I run the program, and it prints 'listening...' into my application. Then if I said something like 'Hello', my program should recognize it and say 'Hello there!' back. Though, it get's into one of the exceptions! If I convert my program with a terminal, command line: pyinstaller -F main.py without -w it works fine! But I don't want a terminal and my tkinter application opened.
Hope someone can help me with this weird problem! Thanks.
I used this code to hide the console with the speech_recognition library:
import ctypes
ctypes.windll.user32.ShowWindow( ctypes.windll.kernel32.GetConsoleWindow(), 0 ) # Hide the console.

How to give the location of "Input" and "Output" for a python code using User Interface and run the code from UI itself?

I have a python code :
import gdal
import numpy
from skimage.filters import threshold_otsu
ds = gdal.Open('A:\\algo\\f2.tif')
In this code, line 4 gives the location/path of "input file" and line 10 gives the location of "output file".
I want to create a user interface to give this location in the user interface itself and run the code from user interface itself.
I have tried making a user interface using "tkinter" module :
from tkinter import *
from tkinter import filedialog
def input():
file1 = filedialog.askopenfile()
label = Label(text=file1).pack()
def input2():
file2 = filedialog.asksaveasfile(mode="w", defaultextension=".tif")
label = Label(text=file2).pack()
w = Tk()
w.geometry("500x500")
w.title("FLOOD_MAPPER")
h = Label(text = "S1A FLOOD MAPPER", bg = "yellow", fg = "black", height = "3", width = "500")
h.pack()
i1 = Label(text = "Input*")
i1.place(x=10, y=70)
i1b = Button(w, text = "Select File", command =input)
i1b.place(x=250, y=70)
i2 = Label(text = "Intermediate Product*")
i2.place(x=10, y=140)
i2b = Button(w, text = "Save as", command =input2)
i2b.place(x=250, y=140)
button = Button(w, text="Generate Map", bg = "red", fg = "black", height = "2", width="30")
button.place(x=150, y=400)
w.mainloop()
But I didn't understand how to link these two codes.
The moment I click on button "generate map" in the user interface I want the location/path of Input and output given in the user interface box to move to their respective places in the 1st code and then run the same code aumoatically.
Kindly, help me to achieve my requirement.
It can look like this. I removed keep only important elements in tkinter.
I put code in your_code and it can get filenames as paramaters. So this code looks similar as before.
I create function gen_map which get run your_code with filenames which are assigned to global variables input_filename, `output_filename.
I assing gen_map to button Button( command=gen_map) so it will run it when you press button.
Other buttons open dialog to get file names and assign to global variables input_filename, output_filename.
from tkinter import *
from tkinter import filedialog
import gdal
import numpy
from skimage.filters import threshold_otsu
def your_code(input_file, output_file):
#ds = gdal.Open('A:\\algo\\f2.tif')
ds = gdal.Open(input_file)
band = ds.GetRasterBand(1)
arr = band.ReadAsArray()
thresh = threshold_otsu(arr,16)
binary = arr > thresh
driver = gdal.GetDriverByName("GTiff")
#outdata = driver.Create("A:\\algo\\test11.tif", 14823, 9985, 1, gdal.GDT_UInt16)
outdata = driver.Create(output_file, 14823, 9985, 1, gdal.GDT_UInt16)
outdata.SetGeoTransform(ds.GetGeoTransform())
outdata.SetProjection(ds.GetProjection())
outdata.GetRasterBand(1).WriteArray(binary)
outdata.GetRasterBand(1).SetNoDataValue(10000)
outdata.FlushCache() ##saves to disk!!
#outdata = None
#band = None
#ds = None
def get_input_filename():
global input_filename
# `askopenfilename` instead of `askopenfile` to get filename instead of object file
input_filename = filedialog.askopenfilename()
input_label['text'] = input_filename
def get_output_filename():
global output_filename
# `asksaveasfilename` instead of `asksaveasfile` to get filename instead of object file
output_filename = filedialog.asksaveasfilename(defaultextension=".tif")
output_label['text'] = output_filename
def gen_map():
#global input_filename
#global output_filename
print('input:', input_filename)
print('output:', output_filename)
your_code(input_filename, output_filename)
#---------------------------------------------
# global variables with default values at start
input_filename = 'A:\\algo\\f2.tif'
output_filename = "A:\\algo\\test11.tif"
root = Tk()
#input_label = Label(root, text=input_filename)
input_label = Label(root, text="Input*")
input_label.pack()
input_button = Button(root, text="Select File", command=get_input_filename)
input_button.pack()
#output_label = Label(root, text=output_filename)
output_label = Label(root, text="Intermediate Product*")
output_label.pack()
output_button = Button(root, text="Save as", command=get_output_filename)
output_button.pack()
gen_map_button = Button(root, text="Generate Map", command=gen_map)
gen_map_button.pack()
root.mainloop()

Trouble with combining threading and progressbar with a function

I have some code which asks the user to import a file and then it will be encrypted using a translator. When I try this the program hangs a lot with large files or any files in general. I've tried to solve this using threading and a progressbar but I've sort of hit a dead end - I don't know how to update the progressbar which will correspond with the amount of time it will take to encrypt the file. This is what I have so far:
import tkinter
from tkinter import *
from tkinter import ttk
from tkinter.ttk import *
from tkinter.filedialog import askopenfile
from tkinter.filedialog import askopenfilename
from tkinter.scrolledtext import *
import threading
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
encryption_code = 'LFWOAYUISVZMNXPBDCRJTQEGHK'
letters += letters.lower()
encryption_code += encryption_code.lower()
enc = dict(zip(letters,encryption_code))
window = tkinter.Tk()
style = ttk.Style(window)
style.configure("BW.TLabel")
import_frame = tkinter.Frame(window)
def import_txt():
global import_list
file_name = askopenfilename(filetypes=[("Text files","*.txt")])
import_list = []
with open(file_name, 'r') as f:
import_list = f.readlines()
progressbar.pack()
but1.pack()
encrypttxt.pack()
f.close()
def encrypt_txt():
global letters
global encryption_code
global import_list
global translated
progressbar.start()
pre = "".join(import_list)
translated = "".join([i.translate(str.maketrans(letters, encryption_code)) for i in import_list])
display_txt.insert('insert', translated)
precrypt.insert('insert', pre)
display_txt.pack(side=RIGHT)
precrypt.pack(side=LEFT)
def end():
if t.isAlive() == False:
progressbar.stop()
t.join()
toplevel = tkinter.Toplevel(window)
progressbar = ttk.Progressbar(toplevel, orient = HORIZONTAL, mode = "determinate")
t = threading.Thread(target=encrypt_txt)
but1 = ttk.Button(window, text= "Stop", command=end)
display_txt = tkinter.scrolledtext.ScrolledText(import_frame)
encrypttxt = ttk.Button(import_frame, text="Encrypt", command=encrypt_txt)
precrypt = tkinter.scrolledtext.ScrolledText(import_frame)
start = ttk.Button(window, text="Start", command=import_txt)
start.pack()
import_frame.pack()
window.mainloop()

Categories

Resources