Código de Python - Reproductor de música.

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

Reproductor de música.gráfica de visualizaciones


Python

Publicado el 20 de Abril del 2021 por Antonio (51 códigos)
319 visualizaciones desde el 20 de Abril 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 generará al ejecutarse por primera vez.
PARA CUALQUIER DUDA U OBSERVACIÓN USEN LA SECCIÓN DE COMENTARIOS.
mp

Requerimientos

Lenguaje: Python
Librerías y recursos: tkinter, wave, pyaudio, threading, json, os

2.0

Publicado el 20 de Abril del 2021gráfica de visualizaciones de la versión: 2.0
319 visualizaciones desde el 20 de Abril del 2021
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from tkinter import *
from tkinter import filedialog, messagebox
import wave
import pyaudio
import threading
import json
import os
 
if not "data.json" in os.listdir():
    d = {}
    with open("data.json", "w") as f:
        json.dump(d, f)
        print("created data.json")
 
class Player:
    def __init__(self):
        self.root = Tk()
        self.root.title("Music Player")
        self.root.configure(bg="gray78")
        self.root.geometry("923x306")
        self.CHUNK = 1024
 
        with open("data.json") as f:
            self.audio_list = json.load(f)
 
        self.filename = StringVar()
        self.currentDir = StringVar()
        self.currentDir.set(os.getcwd())
        self.file_path = None
        self.playing = False
        self.my_list = []
        self.any_selected = False
 
        entryDir = Entry(self.root,textvariable=self.currentDir,width=153)
        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=355,y=28)
        Button(self.root,text="SEARCH",width=78,bg="blue",fg="white",command=self.open_file).place(x=356,y=75)
        Button(self.root,text="PLAY",width=15,bg="goldenrod1",command=self.init_task).place(x=356,y=108)
        Button(self.root,text="STOP",width=15,bg="goldenrod1",command=self.stop_music).place(x=474,y=108)
        Button(self.root,text="ADD TO PLAYLIST",width=44,bg="goldenrod1",command=self.add).place(x=594,y=108)
        self.items = Label(self.root,text=('{} ITEMS'.format(len(self.audio_list))),font=("arial",10),width=39,height=2,bg="black",fg="red")
        self.items.place(x=594,y=147)
        #Button(self.root,text="PLAY ON LIST",width=27,command=self.list_selection).place(x=594,y=200)#181
        Button(self.root,text="REMOVE PLAYLIST",width=44,height=2,command=self.remove_playlist).place(x=594,y=200)#215
        Button(self.root,text="REMOVE FROM PLAYLIST",width=44,height=2,command=self.remove_from_list).place(x=594,y=254)#249
        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=93,height=9,bg="gray96")
        self.fav_list.pack()
        self.fav_list.config(yscrollcommand = self.scrollbar.set)
        self.scrollbar.config(command = self.fav_list.yview)
 
        self.show_list()
 
        self.root.mainloop()
 
    #INICIA PROCESO EN PARALELO.
    def init_task(self):
        self.any_selected = self.is_any_selected()
        if self.any_selected:
            print("OK")
            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 and self.playing == False:
            if os.path.exists(self.file_path):
                self.clear_counter()
                t = threading.Thread(target=self.music)
                t.start()
            else:
                messagebox.showwarning("FILE NOT FOUND",'''Path not found, file may have
been deleted or moved.''')
 
    def remove_playlist(self):
        message = messagebox.askquestion("REMOVE PLAYLIST",'Do you want to remove all the playlist?')
        if message == "yes":
            self.my_list = []
            self.fav_list.delete(0,END)
            self.audio_list = {}
            d = {}
            with open("data.json", "w") as f:
                json.dump(d, f)
            self.items.configure(text='0 ITEMS')
 
    #AÑADE ELEMENTO AL LISTBOX.
    def add(self):
        if self.entryFile.get() != "":
            self.fav_list.delete(0,END)
            self.audio_list[self.filename.get()]=self.file_path
            with open("data.json", "w") as f:
                json.dump(self.audio_list, f)
            self.show_list()
            self.items.configure(text='{} ITEMS'.format(len(self.audio_list)))
 
    def remove_from_list(self):
        try:
            message = messagebox.askquestion("REMOVE ITEM",'Delete selected item from playlist?')
            if message == "yes":
                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]
                with open("data.json", "w") as f:
                    json.dump(self.audio_list, f)
                self.fav_list.delete(0,END)
                self.show_list()
                self.items.configure(text='{} ITEMS'.format(len(self.audio_list)))
        except Exception as e:
            if str(e) == "tuple index out of range":
                messagebox.showwarning("ERROR","No item selected.")
 
    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 is_any_selected(self):
        cn = 0
        sel = False
        for i in range(0,self.fav_list.size()):
            if self.fav_list.selection_includes(cn):
                sel = True
                break
            cn+=1
        return sel
 
    def open_file(self):
        #if self.playing == False:
        self.stop_music()
        self.any_selected = self.is_any_selected()
        if self.any_selected:
            self.fav_list.selection_clear(self.fav_list.curselection()[0])
        fpath = filedialog.askopenfilename(initialdir = "/",title = "Select File",
                        filetypes = (("wav files","*.wav"),("all files","*.*")))
        if fpath:
            if fpath.endswith(".wav"):
                self.file_path = fpath
                self.filename.set(self.file_path.split("/")[-1])
            else:
                messagebox.showwarning("ERROR","Bad file format.")
 
    #FINALIZA AUDIO
    def stop_music(self):
        if self.playing == True:
            self.playing = False
            print("STOPPED")
 
    def clear_counter(self):
        self.sec_counter = 0
        self.min_counter = 0
        self.hour_counter = 0
 
    def counter_format(self,c):
        if c<10:
            c="0"+str(c)
        return c
 
    def timer_count(self):
        if self.playing == True:
            self.timer['text'] = str(self.hour_counter)+":"+str(self.counter_format(self.min_counter)
                                                    )+":"+str(self.counter_format(self.sec_counter))
            self.sec_counter+=1
            if self.sec_counter==60:
                self.sec_counter=0
                self.min_counter+=1
            if self.min_counter==60:
                self.min_counter=0
                self.hour_counter+=1
            self.process=self.timer.after(1000,self.timer_count)
        else:
            self.timer.after_cancel(self.process)
 
    #REPRODUCE AUDIO.
    def music(self):
        try:
            self.playing = True
            self.p = pyaudio.PyAudio()
            wf = wave.open(self.file_path, 'rb')
            self.stream = self.p.open(format=self.p.get_format_from_width(wf.getsampwidth()),
                        channels=wf.getnchannels(),rate=wf.getframerate(),output=True)
            data = wf.readframes(self.CHUNK)
            self.timer_count()
            while data and self.playing == True:
                self.stream.write(data)
                data = wf.readframes(self.CHUNK)
            self.stream.stop_stream()
            self.stream.close()
            self.p.terminate()
            print("ENDED")
 
        except Exception as e:
            messagebox.showwarning("UNEXPECTED ERROR",str(e))
        self.playing = False
 
    def get_key(self,val):
        for key, value in self.audio_list.items():
            if val == value:
                return key
 
if __name__=="__main__":
    Player()



Comentarios sobre la versión: 2.0 (0)


No hay comentarios
 

Comentar la versión: 2.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/s7017