MP3 player with Python

Asked

Viewed 5,610 times

2

I know almost nothing about programming and so I have been studying new possibilities, such as POO and the like.
Recently gave me a desire to try to learn GUI and also to create an MP3 player, all in Python (all yesterday).
I started to look for ways to satisfy my desire and decided to unite the two in one project, however I am with a serious problem, I’m not able to move forward or back a song in my player.

I don’t know if I’ve done anything wrong, but I’ve tried everything and I can’t solve this annoying little problem.
I’ll be leaving my source below so you can analyze.

from pygame  import mixer # Load the required library
from tkinter.filedialog import askopenfilename
from tkinter import *

musicas = []

class Reprodutor :
    def __init__ (self):
       pass

    def escolher ():
        selecionar = askopenfilename(initialdir="C:/Users/",
                           filetypes =(("Arquivo de audio", "*.mp3"),("All Files","*.*")),
                           title = "Selecione as musicas"
                           )
        musicas.append(selecionar)
        return musicas

    def reproduzir ():
        """ 
        mixer.init()
        mixer.music.load('C:/Users/Andreza/Music/Jeff The Killer Theme Song Piano Version Sweet Dreams Are Made Of Screams.mp3')
        mixer.music.play()
        """

        mixer.init()

        for item in musicas:
            musica_atual = mixer.music.load(item)
            musica_atual = mixer.music.play()

    def parar ():
        musica_atual = mixer.music.stop()

    def pausar ():
        musica_atual = mixer.music.pause()

    def retomar ():
        musica_atual = mixer.music.unpause() #Continua da local pausado


    def proxima ():
        for item in range(len(musicas)):
            musica_atual = mixer.music.load(musicas[item])
            musica_atual = mixer.music.play()
            item += 1


    def anterior ():
        for item in range(len(musicas)):
            musica_atual = mixer.music.load(musicas[item])
            musica_atual = mixer.music.play()
            item -= 1 



player = Reprodutor

janela =Tk()

janela.title("REPRODUTOR - FÉLIX LICHT") #Titulo

#Esta parte é que está com problemas
bt_escolher = Button(janela, width=20, text="ADICIONAR MUSICAS", command=player.escolher)
bt_proxima  = Button(janela, width=10, text="PROXIMA",            command=player.proxima)
bt_anterior = Button(janela, width=10, text="ANTERIOR",          command=player.anterior)

bt_escolher.place (x=10,  y=50 )
bt_proxima.place  (x=170, y=50)
bt_anterior.place (x=270, y=50)



bt_play    = Button(janela, width=10, text="PLAY",    command=player.reproduzir)
bt_pause   = Button(janela, width=10, text="PAUSAR",  command=player.pausar)
bt_stop    = Button(janela, width=10, text="PARAR",   command=player.parar)
bt_return  = Button(janela, width=10, text="RETOMAR", command=player.retomar)

bt_play.place   (x=10,  y=0)
bt_pause.place  (x=110, y=0)
bt_stop.place   (x=210, y=0)
bt_return.place (x=310, y=0)

janela.geometry("1280x720+450+350")
janela.mainloop()

If anyone can help me, I’d be grateful.

Thank you

Edited:

After the modification, which was performed based on the first response of the post, the program began to play the music and return the music, but it does this procedure only once.

I tried to create a control system, where the for item would be equated to the last element on the list, and if you were the real one it would go back to the 0 value of Ita, but not even this worked.

================================================================================

from pygame  import mixer # Load the required library
from tkinter.filedialog import askopenfilename
from tkinter import *

musicas = []
TAM     = len(musicas)

class Reprodutor :
    def __init__ (self):
       pass

    def escolher ():
        selecionar = askopenfilename(initialdir="C:/Users/",
                           filetypes =(("Arquivo de audio", "*.mp3"),("All Files","*.*")),
                           title = "Selecione as musicas",
                           #multiple = True
                           )
        musicas.append(selecionar)


        for i in musicas:
            print(i, end=" ")
            print()
        print()


        return musicas

    def reproduzir ():
        mixer.init()

        for item in musicas:
            musica_atual = mixer.music.load(item)
            musica_atual = mixer.music.play()

    def parar ():
        musica_atual = mixer.music.stop()

    def pausar ():
        musica_atual = mixer.music.pause()

    def retomar ():
        musica_atual = mixer.music.unpause() #Continua da local pausado

#Próximo e Anterior com Modificações realizadas com base na resposta do Antony Gabriel
    def proxima ():
        for item in range(len(musicas)):

            item += 1
            musica_atual = mixer.music.load(musicas[item])  
            musica_atual = mixer.music.play() 

    def anterior ():
        for item in range(len(musicas)):
            item -= 1 
            musica_atual = mixer.music.load(musicas[item])
            musica_atual = mixer.music.play()


player = Reprodutor

janela =Tk()

janela.title("REPRODUTOR - FÉLIX LICHT") #Titulo

#Esta parte é que está com problemas
bt_escolher = Button(janela, width=20, text="ADICIONAR MUSICAS",  command=player.escolher)
bt_proxima  = Button(janela, width=10, text="PROXIMA",            command=player.proxima)
bt_anterior = Button(janela, width=10, text="ANTERIOR",           command=player.anterior)

bt_escolher.place (x=10,  y=50 )
bt_proxima.place  (x=170, y=50)
bt_anterior.place (x=270, y=50)



bt_play    = Button(janela, width=10, text="PLAY",    command=player.reproduzir)
bt_pause   = Button(janela, width=10, text="PAUSAR",  command=player.pausar)
bt_stop    = Button(janela, width=10, text="PARAR",   command=player.parar)
bt_return  = Button(janela, width=10, text="RETOMAR", command=player.retomar)

bt_play.place   (x=10,  y=0)
bt_pause.place  (x=110, y=0)
bt_stop.place   (x=210, y=0)
bt_return.place (x=310, y=0)

janela.geometry("410x80+450+350")
janela.mainloop()

2 answers

4

Funny, I just had to move the item += 1 and item -= 1 up, and it worked smoothly. It was just that, you did everything right.

def proxima ():
    for item in range(len(musicas)):
        item += 1
        musica_atual = mixer.music.load(musicas[item])
        musica_atual = mixer.music.play()



def anterior ():
    for item in range(len(musicas)):
        item -= 1 
        musica_atual = mixer.music.load(musicas[item])
        musica_atual = mixer.music.play()

To solve the problem of advancement I switched to that:

The problem was that the variable item was going to -1, which was impossible to find a song, so it didn’t come back. And the other problem is that it(item) was also increasing the value too much, going to a non-existent song, so it did not advance.

I also took the for, preferred for using a variable called item.

I seem to have solved most of the problems. The only problem that I couldn’t solve and that appears sometimes is that it doesn’t read the number 1 song ( That would be the second ), but it’s not always.

I hope I’ve helped.

Follow the code I modified :

def proxima ():
    global item #Usando uma variável de fora
    item += 1
    #print(item) # Utilizei para checar o que havia de errado.
    try:
        musica_atual = mixer.music.load(musicas[item])
        musica_atual = mixer.music.play()
    except IndexError: # Se o Index nao existir, isso vai impedir que o valor de item incremente.
        item -= 1



def anterior ():
    global item
    if item - 1 == -1: # Se for -1 ele volta não decrementa, ficando em 0.
        pass
    else:
        item -= 1
    #print(item)
    musica_atual = mixer.music.load(musicas[item])
    musica_atual = mixer.music.play()

I also changed the function escolher(), I noticed that sometimes there were some '' on the list, which caused the program not to progress/backtrack, and put to start on the desktop, which for me looked better (my songs stay on the desktop), so I did this:

def escolher ():
    selecionar = askopenfilename(initialdir="C:/Users/%user%/desktop",
                       filetypes =(("Arquivo de audio", "*.mp3"),("All Files","*.*")),
                       title = "Selecione as musicas"
                       )
    if selecionar == '': # Se tiver '' ele não faz nada ( pass )
        pass
    else:
        musicas.append(selecionar)
  • I wanted to thank you for your help and also comment that:

  • with the code on top, I can only turn the music back once, and when I try to advance, from the index error

  • but with the skeleton on top, I think I can try to solve

  • Okay, I changed my answer. I think I solved your problem.

  • One more thing, where you referenced the item?

  • I’ll print it, calm down

  • http://prntscr.com/f6b5p3 print using light shot

  • Oh yes, true, I forgot to say. I put under the variable songs, up there. With initial value 0.

  • Man, thank you XD really saved me . I was stuck here and didn’t know what to do, I had even tried to use global, but could not go ahead. Now I will modify the progamma to select several songs at once, save the path in a TXT of each song, and then access directly ^^

  • once again, very excited

  • Disposi :), I thought it was nice your program. Good luck.

Show 6 more comments

-3

You can also use the playsound library!

Just import like that:

 from playsound import playsound

And then play the mp3 file you want like this:

playsound('nome_do_arquivo_mp3', block=false)

It is important to put the block=false pq if not only will play the music and will not run the program!

And if you want to make graphical interfaces, use the library "Pysimplegui"!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.