associação pythonbrasil[11] django zope/plone planet Início Logado como (Entrar)

Diferenças para "ProcurarMp3eGerarPlaylist"

Diferenças entre as versões de 12 e 13
Revisão 12e 2004-04-15 19:39:00
Tamanho: 4746
Editor: 243
Comentário:
Revisão 13e 2004-07-07 14:24:59
Tamanho: 4790
Comentário:
Deleções são marcadas assim. Adições são marcadas assim.
Linha 16: Linha 16:
Searches all mp3 files with the _all_ specified keywords, generates a playlist
and execute it.
Searches all mp3 files with the _all_ specified keywords, generates
a playlist and execute it.
Linha 19: Linha 19:
It accepts the same options as winamp or xmms, such as -e to enqueue, and
-s for shuffle. Actually the options are simply passed forward to the player
so all the xmms/winamp options are available.
It accepts the same options as winamp or xmms, such as -e to enqueue,
and -s for shuffle. Actually the options are simply passed forward
to the player so all the xmms/winamp options are available.
Linha 23: Linha 23:
If you didn't do it already, don't forget to change the variable root_folder in
this file (use any simple text editor).
If you didn't do it already, don't forget to change the variable
root_folder in this file (use any simple text editor).
Linha 67: Linha 67:
    playlist = open(playlist_filename, "w")    #create the file
    playlist.write("#EXTM3U\n")    #add the standard header
    playlist = open(playlist_filename, "w") #create the file
    playlist.write("#EXTM3U\n") #add the standard header
Linha 70: Linha 70:
        playlist.write(file + "\n")    #add the items         playlist.write(file + "\n") #add the items
Linha 88: Linha 88:
    if len(sys.argv) == 1: # if no keyword was entered, give the user a nice tip...
        print __doc__
    if len(sys.argv) == 1: # if no keyword was entered,
        print __doc__ #
give the user a nice tip...
Linha 93: Linha 93:
        # get any options (starting with '-') the user might have entered
        # these options will simply be passed forward to the player
        # one common option is -e to enqueue the songs instead of creating
        #
a brand new playlist
        # get any options (starting with '-') the user might have
        # entered these options will simply be passed forward to
        # the player one common option is -e to enqueue the songs
        #
instead of creating a brand new playlist
Linha 100: Linha 100:
        # if we don't use string.lower the user will never find anything if it
        #
puts a uppercase letter in any of the keywords.
        # if we don't use string.lower the user will never find
        #
anything if it puts a uppercase letter in any of the
        #
keywords.
Linha 104: Linha 105:
        print "Looking for mp3 files with the keyword(s): ", keylist         print "Looking for mp3 files with the keyword(s): ",
               
keylist
Linha 107: Linha 109:
            print "Finished! Found", len(files), "file(s). So, let's play!"             print "Finished! Found", len(files),
                   
"file(s). So, let's play!"
Linha 113: Linha 116:

Procurar arquivos MP3 e gerar playlist

Esse foi meu primeiro script Python. A idéia é poder digitar toca white stripes na linha de comando do Linux ou MiniCli, e o XMMS abriria com uma playlist com todos arquivos mp3 que tivessem essas palavras-chave. Também é possível usar esse script no Windows, basta mudar as variáveis root_folder e player apropriadamente (algo como "c:\\my documents\\mp3" e "c:\\arquivos de programas\\winamp\\winamp.exe", respectivamente).

Boa sorte, e me contate caso tenha alguma dúvida. Também estou aberto a sugestões pra melhorar esse script. Ainda tem algumas coisas com cara de C e Java no código, mas aos poucos to me acostumando com o "estilo Python" :)

Código

"""
Usage: toca <options> <keywords> ....
Example: toca beatles let it be

Searches all mp3 files with the _all_ specified keywords, generates
a playlist and execute it.

It accepts the same options as winamp or xmms, such as -e to enqueue,
and -s for shuffle. Actually the options are simply passed forward
to the player so all the xmms/winamp options are available.

If you didn't do it already, don't forget to change the variable
root_folder in this file (use any simple text editor).
"""

# ------------ configuration options ------------
root_folder = "/windows/E/mp3"               # change this to your mp3 root folder...
print "WARNING: root_folder not customized." # and remove this line.

player = "xmms" # at windows might be something like c:\\program files\\winamp\\winamp.exe
playlist_filename = "playlist.m3u"


# ------------ module imports ------------
import sys
import string 
import os


# ------------ functions used ------------

def findFiles(directory, keylist):
    """
    Gets a list of files in the directory (and subdirectories)
    with contains all the keywords in 'keylist' at the filename 
    """
    filenames = []
    for (path, dname, fnames) in os.walk(directory):
        for filename in fnames:
            # for each filename, check if it contains all the keywords
            lowercase = string.lower(filename)
            if lowercase.endswith(".mp3"):
                for keyword in keylist:
                    if not keyword in lowercase:
                        break 
                else:
                    # all keywords were found: add to the result list
                    filenames.append(os.path.join(path, filename))
    return filenames
    

def makePlaylist(fileList):
    """
    Generates a playlist file for the filenames at fileList
    """
    playlist = open(playlist_filename, "w") #create the file
    playlist.write("#EXTM3U\n")             #add the standard header
    for file in fileList:   
        playlist.write(file + "\n")         #add the items
    playlist.close()
    

def playIt(opt):
    """
    Execute the playlist.
    """
    opt = " ".join(opt)
    command = " ".join([player, opt, playlist_filename, "&"])
    os.popen(command)
    

def main():
    """
    Program main function.
    """
    print "-" * 60
    if len(sys.argv) == 1: # if no keyword was entered,
        print __doc__      #  give the user a nice tip... 
    else:
        args = sys.argv[1:]

        # get any options (starting with '-') the user might have
        # entered these options will simply be passed forward to
        # the player one common option is -e to enqueue the songs
        # instead of creating a brand new playlist
        opt = [x for x in args if x[0] == "-"]
        
        # get the keywords to search for the mp3s
        # if we don't use string.lower the user will never find
        # anything if it puts a uppercase letter in any of the
        # keywords.
        keylist = [string.lower(x) for x in args if x not in opt]
        
        print "Looking for mp3 files with the keyword(s): ",
                keylist
        files = findFiles(root_folder, keylist)
        if files:
            print "Finished! Found", len(files),
                    "file(s). So, let's play!"
            makePlaylist(files)
            playIt(opt)
        else:
            print "Didn't find anything :-( Did you mispell it?"
    print "-" * 60

if __name__ == '__main__':
    main()

Para usar

Renomeie o arquivo para toca, dê um chmod +x toca e copie para um diretório no seu PATH, por exemplo /usr/local/bin/. Então basta digitar $ toca <palavras-chave>. Pode usar quantas palavras quiser, para tornar a busca mais precisa (por exemplo, toca beatles let it be. Quaisquer opcões iniciadas com um "-" são passadas pro player, por exemplo "-e" para colocar as músicas na fila da playlist atual (enqueue) e "-s" para shuffle.


RodrigoVieira