from pydub import AudioSegment
from tkinter import *
import tkinter.filedialog as tf
from tkinter import ttk
import os
#转换函数
def trans_mp3_to_every(filepath,filepath_n,geshi_o,geshi):
name='AudioSegment.from_'+geshi_o #参数名
#print(name)
#eval转换动态字符串为方法
song=eval(name)(filepath)
# print(filepath_n+'.'+geshi)
song.export(filepath_n+'.'+geshi,format=geshi)
def main():
#增加临时系统变量
os.environ['PATH']=os.getcwd()+'\\bin'+os.pathsep+os.environ['PATH']
root=Tk()
root.title('转换音频')
root.geometry('338x200')
group =LabelFrame(root)
group.grid(padx=5,pady=5)
#选择待转换的文件
Label(group,text='原文件:').grid(row=0,padx=5,pady=5,sticky=E)
route_old=Entry(group)
route_old.grid(row=0,column=1,padx=5,pady=5)
def getroute_old():
route_old.insert(0,tf.askopenfilename())
Button(group,text='选择文件',command=getroute_old)\
.grid(row=0,column=2,padx=5,pady=5)
#选择目标保存的文件夹
Label(group,text='目标文件夹:').grid(row=1,padx=5,pady=5,sticky=E)
route_new=Entry(group)
route_new.grid(row=1,column=1,padx=5,pady=5)
def getroute_new():
route_new.insert(0,tf.askdirectory())
Button(group,text='选择文件夹',command=getroute_new)\
.grid(row=1,column=2,padx=5,pady=5)
#目标格式,设置下拉列表选择
Label(group,text='目标格式:').grid(row=2,padx=5,pady=5,sticky='e')
value=StringVar()
value.set('ogg')
values=['mp3','ogg','wav','aiff']
geshi=ttk.Combobox(group,height=14,width=15,state='readonly'\
,cursor='arrow',textvariable=value,values=values)
geshi.grid(row=2,column=1,padx=5,pady=5,sticky='w')
#定义选择列表事件,列表值设置为当前选中值
def choose(event):
value.set(value.get())
#列表绑定选中事件
geshi.bind('<<ComboboxSelected>>',choose)
#转换文件
def transfile():
geshi_o=route_old.get().split('.')[-1]
filename_o=(route_old.get().split('/')[-1]).split('.')[0]
trans_mp3_to_every(route_old.get(),route_new.get()+'/'+filename_o,\
geshi_o,geshi.get())
Button(group,text='开始转换',command=transfile).\
grid(row=3,columnspan=3,pady=20)
mainloop()
if __name__=='__main__':
main()