Loading an audio file using file dialog and playing it with pygame - python-3.x

I'm trying to load a file using the tkinter GUI file dialog and then pass this to another function that will play it using pygame (though I'm open to using another package if it's easier), how would I go about doing this? Below is what a code sample that is representative of what I have so far:
import tkinter, pygame
from tkinter import *
from pygame import *
from tkinter import filedialog
root = Tk()
def open_masker():
global fileName
fileName = filedialog.askopenfilename(filetypes=(("Audio Files", ".wav .ogg"), ("All Files", "*.*")))
masker_track = fileName
if fileName =="":
fileName = None
else:
fh = open(fileName, "r")
fh.close()
def masker_screen():
global m_screen
m_screen = Toplevel(root)
m_screen.geometry('600x600')
m_screen.transient(root)
m_label = Label(m_screen, text = "Playing New Masker Noise")
m_label.pack(anchor = CENTER)
noise = pygame.mixer.Sound(file = fileName)
noise.play(0, 5000)
noise.stop()
b1 = Button(root, text = 'open file',command = open_masker).pack(anchor=CENTER)
b2 = Button(root, text = 'continue', command = masker_screen).pack(anchor = E)
root.mainloop()
Which just returns the error that pygame couldn't load the file. Is this because it's being loaded in as a string into the fileName variable? If so, how do I change that and access the actual file?
Thanks!

Ok, I have fixed some problems you had, and this is my complete working solution (see the comments in the code for explanations):
import pygame
from tkinter import * # not advisable to import everything with *
from tkinter import filedialog
pygame.mixer.init() # initializing the mixer
root = Tk()
audio_file_name = ''
def open_masker():
global audio_file_name
audio_file_name = filedialog.askopenfilename(filetypes=(("Audio Files", ".wav .ogg"), ("All Files", "*.*")))
def masker_screen():
# we will also use the audio_file_name global variable
global m_screen, audio_file_name
m_screen = Toplevel(root)
m_screen.geometry('600x600')
m_screen.transient(root)
m_label = Label(m_screen, text = "Playing New Masker Noise")
m_label.pack(anchor = CENTER)
if audio_file_name: # play sound if just not an empty string
noise = pygame.mixer.Sound(audio_file_name)
noise.play(0, 5000)
b1 = Button(root, text = 'open file',command = open_masker)
# does not make sense to call pack directly
# and stored the result in a variable, which would be None
b1.pack(anchor=CENTER)
Button(root, text = 'continue', command = masker_screen).pack(anchor = E)
root.mainloop()
See documentation for more information on how to use correctly the mixer module.

Related

how to add image in tkinter?

I can't add image (gif image) to tkinter window.
from tkinter import *
from tkinter import filedialog
from PIL import ImageTk, Image
root = Tk()
def open_image():
qr_select = filedialog.askopenfilename(title = "open")
im = PhotoImage(file=qr_select)
w1 = Label(window, image = im)
w1.image = im
w1.config(image=im)
w1.pack(side="right")
def window_function():
global window
window=Tk()
window.geometry("800x550+650+250")
window.title("QR_Scanner")
btn = Button(window,text = "open a gif picture",command = open_image)
btn.pack()
root.iconify()
window.mainloop()
btn = Button(root,text = "open window",command = window_function)
btn.pack()
root.mainloop()
my error is (_tkinter.TclError: image "pyimage1" doesn't exist)
The reason you can't see your gif in the window is that you haven't made a reference to the image so it is collected in Tkinters garbage collector. Read More About This Here. To Add a reference to the image you can do this:
w1.image = im
And add it in your code here:
def open_image():
qr_select = filedialog.askopenfilename(title = "open")
im = PhotoImage(file=qr_select)
w1 = Label(root, image = im)
w1.image = im #Keep A Reference To The Image
w1.config(image=im)
w1.pack(side="right")
The reason you are getting pyimage1 doesn't exist is because you have more than one instance the Tk and there is only meant to be 1. You have to make your window a Toplevel() by replacing: window=Tk() with window=TopLevel()

how can i save the file based on file path?

i create browse button and it's show me what i want
this is my code
from PyPDF2 import PdfFileReader
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
label_list = []
def get_info(path):
with open(path, 'rb') as f:
pdf = PdfFileReader(f)
info = pdf.getDocumentInfo()
label_list[0].config(text=pdf.getNumPages())
label_list[1].config(text=info.author)
label_list[2].config(text=info.creator)
label_list[3].config(text=info.producer)
label_list[4].config(text=info.subject)
label_list[5].config(text=info.title)
def browsefunc():
filename = filedialog.askopenfilename()
pathlabel.config(text=filename)
get_info(filename)
browsebutton = tk.Button(root, text="Browse", command=browsefunc)
browsebutton.pack()
pathlabel = tk.Label(root)
pathlabel.pack()
for i in range(6):
label_list.append(tk.Label(root, text=""))
label_list[i].pack()
root.mainloop()
and how can i save or move to new dir from file path browse button?
I really hope for your help
Sounds like you want to have the browse window open starting in a different directory location than where your python script is (the default behavior)?
If so, give the directory name as the parameter to filedialog.askopenfilename() like so:
# Example Directories
# example_path = os.path.abspath('C:/Users/MyName/Desktop')
# example_path = os.path.abspath('C:/example/cwd/mydir/')
# or
example_path = os.path.abspath('C:/Windows/Temp')
filename = filedialog.askopenfilename(initialdir=example_path)
will open the file browser in that directory.

Trying to make a program that you push a button, choose a file, and the program then prints a certain value from that file

I'm very new to coding and I tried a bunch of different things but none of them are working for me.
Here is my code. With this code everything is working correctly so far, but i'm unsure of how to implement the read function into my code. My main problem is that in everyone's read examples they use the exact filename, whereas I need to use raw input.
Edit: I was able to solve this on my own, by using open(filename, "r") it lets you pick which file to read. Instead of having "6543.txt" which would only open that specific file.
from tkinter import Tk
from tkinter import *
from tkinter.filedialog import askopenfilename
root = Tk()
root.title("Amazon Error Handler")
root.geometry("300x150")
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
def getfile():
filename = askopenfilename()
print(filename)
getfile = open(filename,"r")
print(getfile.read(1))
print(getfile.read())
button = Button(frame, text="Choose File", fg="black", command=getfile)
button.pack( side = BOTTOM)
root.mainloop()
This is the code I used to solve my own problem. This program is just a button that reads a chosen file and prints it's contents.
from tkinter import Tk
from tkinter import *
from tkinter.filedialog import askopenfilename
root = Tk()
root.title("Amazon Error Handler")
root.geometry("300x150")
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
def getfile():
filename = askopenfilename()
print(filename)
getfile = open(filename,"r")
print(getfile.read(1))
print(getfile.read())
button = Button(frame, text="Choose File", fg="black", command=getfile)
button.pack( side = BOTTOM)
root.mainloop()

Changing mp3 songs in a queue Python,Pygame,Mutagen,Tkinter

I am new to python and I'm trying to build a music player which can add all mp3 songs to its list in that folder.
I can see all the songs in a list , But when i click next button it only goes one song next and one song previous. if i click next again it plays the same song again. Is there anyway I can fix my code
I THINK there is something wrong in the methods , nextsong,prevsong. Please help I've tried alot but couldn't find where the error was
import os
import pygame
from tkinter.filedialog import Tk, Button, askdirectory, Label, Listbox, LEFT, RIGHT
from mutagen.id3 import ID3
root = Tk()
listofsongs=[]
formattedlist = []
realnames = []
index =0
def directorychoose():
filename = askdirectory()
os.chdir(filename)
for file in os.listdir(filename):
if file.endswith(".mp3"):
realdir = os.path.realpath(file)
audio = ID3(realdir)
realnames.append(audio['TIT2'].text[0])
listofsongs.append(file)
for file in realnames:
formattedlist.append(file+"\n")
pygame.mixer.init()
pygame.mixer.music.load(listofsongs[0])
pygame.mixer.music.play()
def nextsong(event):
pygame.mixer.music.load(listofsongs[index+1])
pygame.mixer.music.play()
def prevsong(event):
pygame.mixer.music.load(listofsongs[index-1])
pygame.mixer.music.play()
def stopsong(event):
pygame.mixer.music.stop()
directorychoose()
label = Label(root,text='Music player')
label.pack()
listbox = Listbox(root)
listbox.pack()
for item in formattedlist:
listbox.insert(0,item)
button = Button(root,text='Next')
button.pack(side=LEFT)
button2 = Button(root,text='Prev')
button2.pack(side=RIGHT)
stopbutton = Button(root,text='Stop')
stopbutton.pack()
button.bind("<Button-1>",nextsong)
button2.bind("<Button-1>",prevsong)
stopbutton.bind("<Button-1>",stopsong)
root.mainloop()
The problem is that you never assigned the change to index, so it's never changing. In addition this must be placed as a global variable since the variables within the functions are created and destroyed within them.
You are doing this:
x+1
And you should change it to:
x= x+1
Complete code:
import os
import pygame
from tkinter.filedialog import Tk, Button, askdirectory, Label, Listbox, LEFT, RIGHT
from mutagen.id3 import ID3
root = Tk()
listofsongs = []
formattedlist = []
realnames = []
index = 0
def directorychoose():
filename = askdirectory()
os.chdir(filename)
for file in os.listdir(filename):
if file.endswith(".mp3"):
realdir = os.path.realpath(file)
audio = ID3(realdir)
realnames.append(audio['TIT2'].text[0])
listofsongs.append(file)
for file in realnames:
formattedlist.append(file + "\n")
pygame.mixer.init()
pygame.mixer.music.load(listofsongs[0])
pygame.mixer.music.play()
def nextsong(event):
global index
index += 1
pygame.mixer.music.load(listofsongs[index])
pygame.mixer.music.play()
def prevsong(event):
global index
index -= 1
pygame.mixer.music.load(listofsongs[index])
pygame.mixer.music.play()
def stopsong(event):
pygame.mixer.music.stop()
directorychoose()
label = Label(root, text='Music player')
label.pack()
listbox = Listbox(root)
listbox.pack()
for item in formattedlist:
listbox.insert(0, item)
button = Button(root, text='Next')
button.pack(side=LEFT)
button2 = Button(root, text='Prev')
button2.pack(side=RIGHT)
stopbutton = Button(root, text='Stop')
stopbutton.pack()
button.bind("<Button-1>", nextsong)
button2.bind("<Button-1>", prevsong)
stopbutton.bind("<Button-1>", stopsong)
root.mainloop()

Using Tkinter and suprocess.call

I would like to use tkinter to open a window that will allow a user to select two separate files that will be manipulated several times within my script. I am having trouble finding a way to set the file that will be selected using the button in my tkinter window as a variable so that it can be used within subprocess.call. I have found invoke() but it doesn't seem to have any affect. Any ideas on what I might do would be greatly appreciated.
import os
import sys
import gdal
from gdalconst import *
import numpy as np
import math
import subprocess
from subprocess import call
import math
import datetime
import shutil
import tkinter
from tkinter import *
from tkinter import filedialog
newpath = os.path.expanduser('~\\Desktop\\Components\\Float32')
if not os.path.exists(newpath):
os.makedirs(newpath)
newpath_2 = os.path.expanduser('~\\Desktop\\Components\\Zeros')
if not os.path.exists(newpath_2):
os.makedirs(newpath_2)
newpath_3 = os.path.expanduser('~\\Desktop\\Components\\db_Files')
if not os.path.exists(newpath_3):
os.makedirs(newpath_3)
if __name__== '__main__':
# Set all of the necessary constants so that the script can create and save the pertinent files
# on the users desktop
#tk1 = Tk()
#tk2 = Tk()
#callTK = 'src_dataset =' + tk1
#callTK_2 = 'srcVH =' + tk2
gdalTranslate = 'C:\Program Files (x86)\GDAL\gdal_translate.exe'
tk1.fileName = filedialog.askopenfilename(text="Open HV File")
tk2.fileName = filedialog.askopenfilename(text="Open VH File")
dst_dataset = os.path.expanduser('~\\Desktop\\Components\\Float32\\newHV32.img')
dstVH = os.path.expanduser('~\\Desktop\\Components\\Float32\\newVH32.img')
sttime = datetime.datetime.now().strftime('(Time_Run = %Y-%d-%m_%H:%M:%S)')
wheel_install_1 = os.path.expanduser('~\\Desktop\\Components\\Sigma_Test\\wheel_install.py')
wheel_install_2 = os.path.expanduser('~\\Desktop\\Components\\Sigma_Test\\wheel_install2.py')
ridofz = os.path.expanduser('~\\Desktop\\Components\\Sigma_Test\\ridofZsv2.py')
to_dB = os.path.expanduser('~\\Desktop\\Components\\Sigma_Test\\to_dBv2.py')
db_HV = os.path.expanduser('~\\Desktop\\Components\\dB_Files\\newHVdB.img')
db_VH = os.path.expanduser('~\\Desktop\\Components\\dB_Files\\newVHdB.img')
cmd = "-ot float32 -of HFA" # hopefully this works
# Install necessary packages, which are GDAL and Numpy
# try:
#os.system(wheel_install_1)
#print ("GDAL intalled")
#os.system(wheel_install_2)
#print ("Numpy installed")
#except:
#print ("The packages are't installing properly")
#sys.exit()
# Create three new folders which will house the files that will be created
# along each sequential step of the script
#newpath = os.path.expanduser('~\\Desktop\\Components\\Float32')
#if not os.path.exists(newpath):
#os.makedirs(newpath)
#newpath_2 = os.path.expanduser('~\\Desktop\\Components\\Zeros')
#if not os.path.exists(newpath_2):
#os.makedirs(newpath_2)
#newpath_3 = os.path.expanduser('~\\Desktop\\Components\\db_Files')
#if not os.path.exists(newpath_3):
#os.makedirs(newpath_3)
root = Tk()
#root.fileName = filedialog.askopenfilename()
root.title("Utilis Sigma Test")
root.iconbitmap(r"C:\Users\jack.UTILIS\Desktop\images\sigma.ico")
root.configure(background="#179EBB")
topFrame = Frame(root)
topFrame.pack()
photo = PhotoImage(file="C:\\Users\\jack.UTILIS\\Desktop\\images\\Utilis_Branding2015_FINAL_Small.gif")
label = Label(root, image=photo)
label.pack(side=RIGHT)
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)
button1 = Button(root, text="Open HV File", fg="black", command=filedialog.askopenfilename)
button2 = Button(root, text="Open VH FIle", fg="black", command=filedialog.askopenfilename)
button1.pack(side=LEFT)
button2.pack(side=RIGHT)
hvfullCmd = ' '.join([gdalTranslate, cmd, tk1.fileName,dst_dataset])
subprocess.call(hvfullCmd)
vhfullCmd = ' '.join([gdalTranslate,cmd, tk2.fileName,dstVH])
subprocess.call(vhfullCmd)
root.mainloop()
You have to create own function which get filename from askopenfilename and does something with this file. Then you can assign this file to button using command=
import tkinter as tk
from tkinter import filedialog
# --- functions ---
def on_click():
filename = filedialog.askopenfilename()
if filename:
print("Filename:", filename)
else:
print("Filename: not selected")
# --- main ---
root = tk.Tk()
btn = tk.Button(root, text='Click Me', command=on_click)
btn.pack()
root.mainloop()

Resources