Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # Code for article 23
- import sys
- import os.path
- try:
- from mutagen.mp3 import MP3
- except:
- print "This application requires the mutagen python library."
- try:
- import pygtk
- pygtk.require("2.0")
- except:
- pass
- try:
- import gtk
- import gtk.glade
- except:
- sys.exit(1)
- class PlayListCreator:
- def __init__(self):
- self.gladefile = "playlistmaker.glade"
- self.wTree = gtk.glade.XML(self.gladefile,"MainWindow")
- self.SetEventDictionary()
- self.SetWidgetReferences()
- self.SetupToolTips()
- self.SetupTreeview()
- self.CurrentPath = ""
- self.CurrentRow = 0
- self.RowCount = 0
- def SetEventDictionary(self):
- dict = {"on_MainWindow_destroy": gtk.main_quit,
- "on_tbtnQuit_clicked": gtk.main_quit,
- "on_tbtnAdd_clicked": self.on_tbtnAdd_clicked,
- "on_tbtnDelete_clicked": self.on_tbtnDelete_clicked,
- "on_tbtnClearAll_clicked": self.on_tbtnClearAll_clicked,
- "on_tbtnMoveToTop_clicked": self.on_tbtnMoveToTop_clicked,
- "on_tbtnMoveUp_clicked": self.on_tbtnMoveUp_clicked,
- "on_tbtnMoveDown_clicked": self.on_tbtnMoveDown_clicked,
- "on_tbtnMoveToBottom_clicked": self.on_tbtnMoveToBottom_clicked,
- "on_tbtnAbout_clicked": self.on_tbtnAbout_clicked,
- "on_btnGetFolder_clicked": self.on_btnGetFolder_clicked,
- "on_txtFilename_key_press_event": self.txtFilenameKeyPress,
- "on_btnSavePlaylist_clicked": self.on_btnSavePlaylist_clicked}
- self.wTree.signal_autoconnect(dict)
- def SetWidgetReferences(self):
- self.txtFilename = self.wTree.get_widget("txtFilename")
- self.txtPath = self.wTree.get_widget("txtPath")
- self.tbtnAdd = self.wTree.get_widget("tbtnAdd")
- self.tbtnDelete = self.wTree.get_widget("tbtnDelete")
- self.tbtnClearAll = self.wTree.get_widget("tbtnClearAll")
- self.tbtnQuit = self.wTree.get_widget("tbtnQuit")
- self.tbtnAbout = self.wTree.get_widget("tbtnAbout")
- self.tbtnMoveToTop = self.wTree.get_widget("tbtnMoveToTop")
- self.tbtnMoveUp = self.wTree.get_widget("tbtnMoveUp")
- self.tbtnMoveDown = self.wTree.get_widget("tbtnMoveDown")
- self.tbtnMoveToBottom = self.wTree.get_widget("tbtnMoveToBottom")
- self.btnGetFolder = self.wTree.get_widget("btnGetFolder")
- self.btnSavePlaylist = self.wTree.get_widget("btnSavePlaylist")
- self.sbar = self.wTree.get_widget("statusbar1")
- self.context_id = self.sbar.get_context_id("Statusbar")
- def SetupToolTips(self):
- self.tbtnAdd.set_tooltip_text("Add a file or files to the playlist.")
- self.tbtnAbout.set_tooltip_text("Display the About Information.")
- self.tbtnDelete.set_tooltip_text("Delete selected entry from the list.")
- self.tbtnClearAll.set_tooltip_text("Remove all entries from the list.")
- self.tbtnQuit.set_tooltip_text("Quit this program.")
- self.tbtnMoveToTop.set_tooltip_text("Move the selected entry to the top of the list.")
- self.tbtnMoveUp.set_tooltip_text("Move the selected entry up in the list.")
- self.tbtnMoveDown.set_tooltip_text("Move the selected entry down in the list.")
- self.tbtnMoveToBottom.set_tooltip_text("Move the selected entry to the bottom of the list.")
- self.btnGetFolder.set_tooltip_text("Select the folder that the playlist will be saved to.")
- self.btnSavePlaylist.set_tooltip_text("Save the playlist.")
- self.txtFilename.set_tooltip_text("Enter the filename to be saved here. The extension '.m3u' will be added for you if you don't include it.")
- def SetupTreeview(self):
- self.cFName = 0
- self.cFType = 1
- self.cFPath = 2
- self.sFName = "Filename"
- self.sFType = "Type"
- self.sFPath = "Folder"
- self.treeview = self.wTree.get_widget("treeview1")
- self.AddPlaylistColumn(self.sFName,self.cFName)
- self.AddPlaylistColumn(self.sFType,self.cFType)
- self.AddPlaylistColumn(self.sFPath,self.cFPath)
- self.playList = gtk.ListStore(str,str,str)
- self.treeview.set_model(self.playList)
- self.treeview.set_grid_lines(gtk.TREE_VIEW_GRID_LINES_BOTH)
- def AddPlaylistColumn(self,title,columnId):
- column = gtk.TreeViewColumn(title,gtk.CellRendererText(),text=columnId)
- column.set_resizable(True)
- column.set_sort_column_id(columnId)
- self.treeview.append_column(column)
- def on_tbtnAdd_clicked(self,widget):
- fd = FileDialog()
- selectedfiles,self.CurrentPath = fd.ShowDialog(0,self.CurrentPath)
- self.AddFilesToTreeview(selectedfiles)
- def on_tbtnDelete_clicked(self,widget):
- sel = self.treeview.get_selection()
- (model,rows) = sel.get_selected_rows()
- iters=[]
- for row in rows:
- iters.append(self.playList.get_iter(row))
- for i in iters:
- if i is not None:
- self.playList.remove(i)
- self.RowCount -= 1
- self.sbar.push(self.context_id,"%d files in list." % (self.RowCount))
- def on_tbtnClearAll_clicked(self,widget):
- self.playList.clear()
- def on_tbtnMoveToTop_clicked(self,widget):
- sel = self.treeview.get_selection()
- (model,rows) = sel.get_selected_rows()
- for path1 in rows:
- path2 = 0
- iter1=model.get_iter(path1)
- iter2 = model.get_iter(path2)
- model.move_before(iter1,iter2)
- def on_tbtnMoveUp_clicked(self,widget):
- sel = self.treeview.get_selection()
- (model,rows) = sel.get_selected_rows()
- for path1 in rows:
- path2 = (path1[0]-1,)
- if path2[0] >= 0:
- iter1=model.get_iter(path1)
- iter2 = model.get_iter(path2)
- model.swap(iter1,iter2)
- def on_tbtnMoveDown_clicked(self,widget):
- sel = self.treeview.get_selection()
- (model,rows) = sel.get_selected_rows()
- for path1 in rows:
- path2 = (path1[0]+1,)
- iter1=model.get_iter(path1)
- if path2[0] <= self.RowCount-1:
- iter2 = model.get_iter(path2)
- model.swap(iter1,iter2)
- def on_tbtnMoveToBottom_clicked(self,widget):
- sel = self.treeview.get_selection()
- (model,rows) = sel.get_selected_rows()
- for path1 in rows:
- path2 = self.RowCount-1
- iter1=model.get_iter(path1)
- iter2 = model.get_iter(path2)
- model.move_after(iter1,iter2)
- def on_tbtnAbout_clicked(self,widget):
- self.ShowAbout()
- def on_btnGetFolder_clicked(self,widget):
- fd = FileDialog()
- filepath,self.CurrentPath = fd.ShowDialog(1,self.CurrentPath)
- self.txtPath.set_text(filepath[0])
- def on_btnSavePlaylist_clicked(self,widget):
- self.SavePlaylist()
- def txtFilenameKeyPress(self,widget,data):
- if data.keyval == 65293: # The value of the return key
- self.SavePlaylist()
- def AddFilesToTreeview(self,FileList):
- counter = 0
- for f in FileList:
- extStart = f.rfind(".")
- fnameStart = f.rfind("/")
- extension = f[extStart+1:]
- fname = f[fnameStart+1:extStart]
- fpath = f[:fnameStart]
- data = [fname,extension,fpath]
- self.playList.append(data)
- counter += 1
- self.RowCount += counter
- self.sbar.push(self.context_id,"%s files added for a total of %d" % (counter,self.RowCount))
- def SavePlaylist(self):
- fp = self.txtPath.get_text() # Get the file path from the text box
- fn = self.txtFilename.get_text() # Get the filename from the text box
- if fp == "": # IF filepath is blank...
- self.MessageBox("error","Please provide a filepath for the playlist.")
- elif fn == "": # IF filename is blank...
- self.MessageBox("error","Please provide a filename for the playlist file.")
- else: # Otherwise
- extStart = fn.rfind(".") # Find the extension start position
- print extStart
- if extStart == -1:
- fn += '.m3u' #append the extension if there isn't one.
- print "Added extension. fn = %s" % fn
- self.txtFilename.set_text(fn) #replace the filename in the text box
- if os.path.exists(fp + "/" + fn):
- self.MessageBox("error","The file already exists. Please select another.")
- else:
- plfile = open(fp + "/" + fn,"w") # Open the file
- plfile.writelines('#EXTM3U\n') #Print the M3U header
- for row in self.playList:
- fname = "%s/%s.%s" % (row[2],row[0],row[1])
- artist,title,songlength = self.GetMP3Info(fname)
- if songlength > 0 and (artist != '' and title != ''):
- plfile.writelines("#EXTINF:%d,%s - %s\n" % (songlength,artist,title))
- #plfile.writelines("%s/%s.%s\n" % (row[2],row[0],row[1]))
- plfile.writelines("%s\n" % fname)
- plfile.close # Finally Close the file
- self.MessageBox("info","Playlist file saved!")
- def MessageBox(self,level,text):
- if level == "info":
- dlg = gtk.MessageDialog(None,0,gtk.MESSAGE_INFO,gtk.BUTTONS_OK,text)
- elif level == "warning":
- dlg = gtk.MessageDialog(None,0,gtk.MESSAGE_WARNING,gtk.BUTTONS_OK,text)
- elif level == "error":
- dlg = gtk.MessageDialog(None,0,gtk.MESSAGE_ERROR,gtk.BUTTONS_OK,text)
- elif level == "question":
- dlg = gtk.MessageDialog(None,0,gtk.MESSAGE_QUESTION,gtk.BUTTONS_YES_NO,text)
- if level == "question":
- resp = dlg.run()
- dlg.destroy()
- return resp
- else:
- resp = dlg.run()
- dlg.destroy()
- def ShowAbout(self):
- about = gtk.AboutDialog()
- about.set_program_name("Playlist Maker")
- about.set_version("1.0")
- about.set_copyright("(c) 2011 by Greg Walters")
- comments = "Written for Full Circle Magazine\n"
- comments += "This program will create a M3U format play list\n"
- comments += "for use with any media player that supports the .m3u playlist format"
- #about.set_comments("Written for Full Circle Magazine")
- about.set_comments(comments)
- about.set_logo(gtk.gdk.pixbuf_new_from_file("logo.png"))
- about.set_website("http://thedesignatedgeek.com")
- about.run()
- about.destroy()
- def GetMP3Info(self,filename):
- artist = ''
- title = ''
- songlength = 0
- audio = MP3(filename)
- keys = audio.keys()
- for key in keys:
- try:
- if key == "TPE1": # Artist
- artist = audio.get(key)
- except:
- artist = ''
- try:
- if key == "TIT2": # Song Title
- title = audio.get(key)
- except:
- title = ''
- songlength = audio.info.length # Audio Length
- return (artist,title,songlength)
- class FileDialog:
- def ShowDialog(self,which,CurrentPath):
- if which == 0: # file chooser
- dialog = gtk.FileChooserDialog("Select files to add...",None,
- gtk.FILE_CHOOSER_ACTION_OPEN,
- (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
- gtk.STOCK_OPEN, gtk.RESPONSE_OK))
- filter = gtk.FileFilter()
- filter.set_name("Music Files")
- filter.add_pattern("*.mp3")
- filter.add_pattern("*.ogg")
- filter.add_pattern("*.wav")
- dialog.add_filter(filter)
- filter = gtk.FileFilter()
- filter.set_name("All files")
- filter.add_pattern("*")
- dialog.add_filter(filter)
- else: # folder chooser
- dialog = gtk.FileChooserDialog("Select Save Folder..",None,
- gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
- (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
- gtk.STOCK_OPEN, gtk.RESPONSE_OK))
- dialog.set_default_response(gtk.RESPONSE_OK)
- dialog.set_select_multiple(True)
- if CurrentPath != "":
- dialog.set_current_folder(CurrentPath)
- response = dialog.run()
- if response == gtk.RESPONSE_OK:
- fileselection = dialog.get_filenames()
- CurrentPath = dialog.get_current_folder()
- dialog.destroy()
- return (fileselection,CurrentPath)
- elif response == gtk.RESPONSE_CANCEL:
- print 'Closed, no files selected'
- dialog.destroy()
- return ([],"")
- if __name__ == "__main__":
- plc = PlayListCreator()
- gtk.main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement