Código de Python - Reproductor de música (nueva versión).

Imágen de perfil
Val: 712
Bronce
Ha aumentado 1 puesto en Python (en relación al último mes)
Gráfica de Python

Reproductor de música (nueva versión).gráfica de visualizaciones


Python

Actualizado el 9 de Enero del 2024 por Antonio (75 códigos) (Publicado el 31 de Mayo del 2021)
8.685 visualizaciones desde el 31 de Mayo del 2021
Programa para reproducir archivos de audio que incorpora la posibilidad de crear una lista de favoritos.
El programa necesita de un archivo "json" que se generará al ejecutarse por primera vez.
Esta versión incorpora la posibilidad de reproducir secuencialmente la lista de favoritos, para ello se usará el botón "PLAY ALL" (dicha reproducción se podrá finalizar igualmente con el botón "STOP").
PARA CUALQUIER DUDA U OBSERVACIÓN USEN LA SECCIÓN DE COMENTARIOS.
mpr

Requerimientos

Lenguaje: Python
Librerías y recursos: tkinter, pygame (v 2.0.1), threading, json, os

2.1

Publicado el 31 de Mayo del 2021gráfica de visualizaciones de la versión: 2.1
617 visualizaciones desde el 31 de Mayo del 2021

2.1.1

Actualizado el 11 de Septiembre del 2021 (Publicado el 11 de Junio del 2021)gráfica de visualizaciones de la versión: 2.1.1
465 visualizaciones desde el 11 de Junio del 2021

2.1.2

Actualizado el 11 de Septiembre del 2021 (Publicado el 21 de Junio del 2021)gráfica de visualizaciones de la versión: 2.1.2
360 visualizaciones desde el 21 de Junio del 2021

2.1.3

Actualizado el 14 de Septiembre del 2021 (Publicado el 22 de Junio del 2021)gráfica de visualizaciones de la versión: 2.1.3
2.607 visualizaciones desde el 22 de Junio del 2021

2.2

Actualizado el 20 de Enero del 2022 (Publicado el 24 de Septiembre del 2021)gráfica de visualizaciones de la versión: 2.2
965 visualizaciones desde el 24 de Septiembre del 2021

3.0

Actualizado el 9 de Enero del 2024 (Publicado el 1 de Febrero del 2022)gráfica de visualizaciones de la versión: 3.0
3.672 visualizaciones desde el 1 de Febrero del 2022
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

El reproductor cuenta con la posibilidad de reproducir en bucle los audios previamente guardados en la playlist. El orden de dicha reproducción será aleatorio en el caso en que el botón junto a "PLAY ALL" esté en "RANDOM (ON)" y secuencial en el caso en que esté en "RANDOM (OFF)". Esta versión también incorpora un botón "PAUSE" para pausar la reproducción del audio.
PARA CUALQUIER DUDA U OBSERVACIÓN, USEN LA SECCIÓN DE COMENTARIOS.

mp32
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from tkinter import *
from tkinter import filedialog, messagebox
import random
from pygame import mixer, display
import threading
import json
import os
 
if not "music_favs.json" in os.listdir():
    d = {}
    with open("music_favs.json", "w") as f:
        json.dump(d, f)
        print("created music_favs.json")
 
class Player:
    def __init__(self):
        self.root = Tk()
        self.root.title("Music Player")
        self.root.configure(bg="gray78")
        self.root.geometry("928x306")
        self.root.resizable(height=FALSE, width=FALSE)
        self.CHUNK = 1024
 
        self.currentDir = StringVar()
        self.currentDir.set(os.getcwd())
        self.filename = StringVar()
        self.playing = False
        self.file_path = ""
        mixer.init()
        display.init()
        self.paused = False
        self.stopped = False
        self.random_mode = False
        self.running = False
        self.c = 0
        self.text_x = 0
        self.text_direction = 1
        self.sleeep = False
 
        with open("music_favs.json") as f:
            self.audio_list = json.load(f)
 
        entryDir = Entry(self.root, textvariable=self.currentDir, width=154)
        entryDir.place(x=0, y=0)
        self.timer = Label(self.root, text="0:00:00", bg="black", fg="green", font=("arial", "34"), width=13, height=2)
        self.timer.place(x=9, y=28)
        self.entryFile = Entry(self.root, textvariable=self.filename, width=37, font=("arial", 20))
        self.entryFile.place(x=358, y=28)
        Button(self.root, text="SEARCH", width=79, bg="blue", fg="white", command=self.open_file).place(x=356, y=75)
        Button(self.root, text="PLAY", width=10, bg="goldenrod1", command=self.init_task).place(x=356, y=108)
        self.btnPause = Button(self.root, text="PAUSE", width=10, bg="goldenrod1", command=self.pause)
        self.btnPause.place(x=437, y=108)
        Button(self.root, text="STOP", width=10, bg="goldenrod1", command=self.stop).place(x=518, y=108)
        Button(self.root, text="ADD TO PLAYLIST", width=44, bg="goldenrod1", command=self.add).place(x=601, y=108)
        self.items = Label(self.root, text=('{} ITEMS ON PLAYLIST'.format(len(self.audio_list))), font=("arial", 10),
                           width=39, height=2, bg="black", fg="red")
        self.items.place(x=601, y=147)
        Button(self.root, text="REMOVE PLAYLIST", width=44, command=self.remove_playlist).place(x=601, y=220)
        Button(self.root, text="REMOVE FROM PLAYLIST", width=44, command=self.remove_from_list).place(x=601, y=190)
        self.btnPlayall = Button(self.root, text="PLAY ALL", width=21, height=2, command=self.init_task2)
        self.btnPlayall.place(x=601, y=254)
        self.btnRandom = Button(self.root, text="RANDOM (OFF)", width=21, height=2, command=self.random_mod)
        self.btnRandom.place(x=762, y=254)
        self.canvas = Canvas(self.root)
        self.canvas.place(x=9, y=147)
        self.scrollbar = Scrollbar(self.canvas, orient=VERTICAL)
        self.scrollbar.pack(side=RIGHT, fill=Y)
        self.fav_list = Listbox(self.canvas, width=94, height=9, bg="gray96")
        self.fav_list.pack()
        self.fav_list.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.fav_list.yview)
 
        # Crear un Canvas para la animación del texto dentro de entryFile
        self.canvas_text = Canvas(self.root, width=559, height=36, bg="white", highlightthickness=0)#width=559,
        self.canvas_text.place(x=358, y=28)
 
        # Iniciar la función para mover el texto dentro de entryFile:
        self.move_text()
 
        self.show_list()
        self.root.mainloop()
 
    def open_file(self):
        try:
            fpath = filedialog.askopenfilename(initialdir="/", title="Select File",
                                               filetypes=(("mp3 files", "*.mp3"), ("wav files", "*.wav"),
                                                          ("ogg files", ".ogg")))  # ,("all files","*.*")))
            if fpath:
                self.any_selected = self.is_any_selected()
                if self.any_selected:
                    self.fav_list.selection_clear(self.fav_list.curselection()[0])
                    self.stop()
                if self.playing == True:
                    self.stop()
                self.file_path = fpath
                self.filename.set(self.file_path.split("/")[-1])
 
        except Exception as e:
            messagebox.showwarning("UNEXPECTED ERROR", str(e))
 
    def add(self):
        self.any_selected = self.is_any_selected()
        if self.entryFile.get() != "" and self.running == False and self.any_selected == False:
            if not self.file_path in self.audio_list.values():
                self.fav_list.delete(0, END)
                self.audio_list[self.filename.get()] = self.file_path
                with open("music_favs.json", "w") as f:
                    json.dump(self.audio_list, f)
                self.show_list()
                self.items.configure(text='{} ITEMS ON PLAYLIST'.format(len(self.audio_list)))
            else:
                messagebox.showwarning("ALREADY SAVED",
                                       "Selected item is already saved on playlist.")
 
    def random_mod(self):
        if self.random_mode == False:
            self.random_mode = True
            self.listado = self.create_list(self.my_list, self.c)
            self.playlist = self.my_list
            self.btnRandom.configure(text="RANDOM (ON)")
 
        else:
            self.random_mode = False
            self.c = 0
            self.playlist = self.my_list[::-1]
            self.btnRandom.configure(text="RANDOM (OFF)")
 
    def update_timer(self):
        pos_time = mixer.music.get_pos()
        s = pos_time // 1000
        m, s = divmod(s, 60)
        h, m = divmod(m, 60)
        h, m, s = int(h), int(m), int(s)
        self.timer['text'] = f"{h:01}:{m:02}:{s:02}"
 
        self.process = self.root.after(500, self.update_timer)
        if h == -1:
            self.timer['text'] = "0:00:00"
            self.root.after_cancel(self.process)
            self.btnPause.configure(text="PAUSE", command=self.pause)
            self.playing = False
 
    def show_list(self):
        if len(self.audio_list) > 0:
            self.my_list = []
            c = 1
            for i in (self.audio_list):
                self.fav_list.insert(END, (str(c) + "- " + i))
                self.my_list.append(self.audio_list[i])
                c += 1
 
    def remove_playlist(self):
        if self.fav_list.size() > 0:
            message = messagebox.askquestion("REMOVE PLAYLIST", 'Do you want to remove all the playlist?')
            if message == "yes":
                self.playing = False
                self.running = False
                self.btnPlayall.configure(state='normal')
                self.my_list = []
                self.fav_list.delete(0, END)
                self.audio_list = {}
                d = {}
                with open("music_favs.json", "w") as f:
                    json.dump(d, f)
                self.items.configure(text='0 ITEMS ON PLAYLIST')
 
    def remove_from_list(self):
        if self.fav_list.size() > 0:
            self.any_selected = self.is_any_selected()
            if self.any_selected:
                message = messagebox.askquestion("REMOVE ITEM", 'Delete selected item from playlist?')
                if message == "yes":
                    if self.running == False:
                        mixer.music.stop()
                    else:
                        self.running = False
                        self.btnPlayall.configure(state='normal')
 
                    self.file_path = self.my_list[self.fav_list.curselection()[0]]
                    self.key = self.get_key(self.file_path)
                    del self.audio_list[self.key]
                    self.fav_list.delete(0, END)
                    with open("music_favs.json", "w") as f:
                        json.dump(self.audio_list, f)
                    self.show_list()
                    self.items.configure(text='{} ITEMS ON PLAYLIST'.format(len(self.audio_list)))
            else:
                messagebox.showwarning("NO ITEM SELECTED", "Select the item you want to delete.")
 
    def is_any_selected(self):
        self.num_selected = 0
        for i in range(0, self.fav_list.size()):
            if self.fav_list.selection_includes(i):
                self.num_selected += 1
                sel = True
                break
        else:
            sel = False
        return sel
 
    def create_list(self, p, c):
        lista = []
        for i in range(len(p)):
            lista.append(i)
        random.shuffle(lista)
        if c == lista[0]:
            lista.append(lista.pop(lista.index(c)))
        return lista
 
    def play_loop(self):
        self.playing = True
        self.stopped = False
        self.paused = False
 
        self.c = 0
        if self.random_mode == False:
            self.playlist = self.my_list[::-1]
        else:
            self.listado = self.create_list(self.my_list, self.c)
            self.playlist = self.my_list
        self.running = True
 
        while self.running:
            print("-->" + str(self.c))
            if len(self.playlist) > 0 and self.stopped == False:
                if mixer.music.get_busy() == 0 and self.paused == False:
                    if self.random_mode == False:
                        current = self.playlist.pop()
                    else:
                        current = self.playlist[self.listado[self.c]]
 
                    try:
                        mixer.music.load(current)
                        self.filename.set(self.get_key(current))
                        any_selected = self.is_any_selected()
                        if any_selected:
                            self.fav_list.selection_clear(self.fav_list.curselection()[0])
 
                        if self.random_mode == False:
                            self.fav_list.selection_set(self.c)
                            self.fav_list.see(self.c)
                            self.c += 1
                        else:
                            self.fav_list.selection_set(self.listado[self.c])
                            self.fav_list.see(self.listado[self.c])
                            if self.c < len(self.listado) - 1:
                                self.c += 1
                            else:
                                self.listado = self.create_list(self.my_list, self.listado[self.c])
                                self.c = 0
                        self.playing = True
                        mixer.music.play()
                        self.update_timer()
                    except:
                        if self.random_mode == False:
                            self.c += 1
                        else:
                            if self.c < len(self.listado) - 1:
                                self.c += 1
                            else:
                                self.listado = self.create_list(self.my_list, self.listado[self.c])
                                self.c = 0
            else:
                if self.c != 0:
                    self.c = 0
                    self.playlist = self.my_list[::-1]
        self.playing = False
 
    def init_task2(self):
        if len(self.audio_list) > 0 and self.playing == False:
            self.btnPlayall.configure(state="disabled")
            t2 = threading.Thread(target=self.play_loop)
            t2.start()
 
    def play(self):
        self.playing = True
        try:
            mixer.music.load(self.file_path)
            mixer.music.play()
            self.update_timer()
        except:
            messagebox.showwarning("ERROR", "Can't open the file '{}'.".format(self.entryFile.get()))
            self.playing = False
 
    def init_task(self):
        if self.playing == False:
            self.any_selected = self.is_any_selected()
            if self.any_selected:
                self.file_path = self.my_list[self.fav_list.curselection()[0]]
                self.key = self.get_key(self.file_path)
                self.filename.set(self.key)
            if self.file_path:
                if os.path.exists(self.file_path):
                    self.timer['text'] = "0:00:00"
                    t = threading.Thread(target=self.play)
                    t.start()
                else:
                    messagebox.showwarning("NO FILE", '''Path not found, file may have
been deleted or moved.''')
 
    def stop(self):
        mixer.music.stop()
        self.stopped = True
        self.running = False
        self.btnPlayall.configure(state="normal")
 
    def pause(self):
        if self.playing == True:
            mixer.music.pause()
            self.paused = True
            self.btnPause.configure(text="CONTINUE", command=self.unpause)
 
    def unpause(self):
        mixer.music.unpause()
        self.stopped = False
        self.paused = False
        self.btnPause.configure(text="PAUSE", command=self.pause)
 
    def get_key(self, val):
        for key, value in self.audio_list.items():
            if val == value:
                return key
 
    def move_text(self):
        text = self.entryFile.get()
        canvas_width = self.canvas_text.winfo_width()
 
        text_bbox = self.canvas_text.bbox(self.canvas_text.create_text(0, 0, text=text, anchor="w", font=("arial", 20)))
        text_width = text_bbox[2] - text_bbox[0]
 
        if text_width > canvas_width:
            self.canvas_text.delete("all")
            self.canvas_text.create_text(self.text_x, 15, text=text, anchor="w", fill="black", font=("arial", 20))
            self.text_x -= 5
 
            if self.text_x <= - text_width:
                self.text_x = canvas_width
        else:
            self.canvas_text.delete("all")
            self.canvas_text.create_text(self.text_x, 15, text=text, anchor="w", fill="black", font=("arial", 20))
            self.text_x = 0
 
        self.root.after(100, self.move_text)
 
 
    def __del__(self):
        mixer.music.stop()
        self.stopped = True
        self.running = False
 
if __name__ == "__main__":
    Player()



Comentarios sobre la versión: 3.0 (0)


No hay comentarios
 

Comentar la versión: 3.0

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

http://lwp-l.com/s7076