Advertisement
Najeebsk

MP3DATA.pyw

Oct 30th, 2024 (edited)
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.45 KB | None | 0 0
  1. import os
  2. import sqlite3
  3. import tempfile
  4. from tkinter import *
  5. from tkinter import filedialog, messagebox
  6. import vlc  # Import the VLC module
  7. from PIL import Image, ImageTk, ImageSequence
  8.  
  9. class Mp3PlayerApp:
  10.     def __init__(self, root):
  11.         self.root = root
  12.         self.root.title("Najeeb Advanced MP3 Player")
  13.         self.root.geometry("800x550")
  14.         self.root.config(bg="lightblue")
  15.        
  16.         # VLC Media Player initialization
  17.         self.vlc_instance = vlc.Instance()
  18.         self.media_player = self.vlc_instance.media_player_new()
  19.  
  20.         # Database Setup
  21.         self.db_connection = sqlite3.connect("DataMp3.db")
  22.         self.cursor = self.db_connection.cursor()
  23.         self.cursor.execute('''CREATE TABLE IF NOT EXISTS mp3_files
  24.                               (id INTEGER PRIMARY KEY, filename TEXT, filedata BLOB)''')
  25.         self.db_connection.commit()
  26.  
  27.         # Frames for organization
  28.         self.setup_frames()
  29.  
  30.         # Animated GIF Label
  31.         self.load_gif(os.path.join(os.path.dirname(__file__), "MP3.gif"))
  32.  
  33.         # Player Controls
  34.         self.setup_player_controls()
  35.  
  36.         # Volume Control
  37.         self.setup_volume_control()
  38.  
  39.         # Audio Position Slider
  40.         self.setup_position_slider()
  41.  
  42.         # Load MP3s from Database on Start
  43.         self.load_mp3s_from_database()
  44.  
  45.         # Temporary files list
  46.         self.temp_files = []
  47.  
  48.     def setup_frames(self):
  49.         # Browse and Listbox Frame with Scrollbar
  50.         browse_frame = Frame(self.root, bg="lightblue")
  51.         browse_frame.pack(side=LEFT, fill=Y, padx=10, pady=10)
  52.  
  53.         # Listbox with Scrollbar
  54.         self.listbox = Listbox(browse_frame, width=35, height=18)
  55.         self.listbox.pack(side=TOP, pady=10)
  56.         self.listbox.bind("<<ListboxSelect>>", self.play_selected_song)
  57.  
  58.         scrollbar = Scrollbar(browse_frame)
  59.         scrollbar.pack(side=RIGHT, fill=Y)
  60.         self.listbox.config(yscrollcommand=scrollbar.set)
  61.         scrollbar.config(command=self.listbox.yview)
  62.  
  63.         # Buttons below Listbox
  64.         button_frame = Frame(browse_frame, bg="lightblue")
  65.         button_frame.pack(pady=10)
  66.  
  67.         browse_button = Button(button_frame, text="Browse Folder", command=self.browse_folder)
  68.         browse_button.pack(fill=X, pady=2)
  69.  
  70.         add_button = Button(button_frame, text="Add MP3", command=self.add_mp3_file)
  71.         add_button.pack(fill=X, pady=2)
  72.  
  73.         delete_button = Button(button_frame, text="Delete MP3", command=self.delete_mp3_file)
  74.         delete_button.pack(fill=X, pady=2)
  75.  
  76.         save_button = Button(button_frame, text="Save MP3", command=self.save_mp3_to_database)
  77.         save_button.pack(fill=X, pady=2)
  78.  
  79.         delete_temp_button = Button(button_frame, text="Delete Temporary Files", command=self.delete_temp_files)
  80.         delete_temp_button.pack(fill=X, pady=2)
  81.  
  82.     def setup_player_controls(self):
  83.         control_frame = Frame(self.root, bg="lightblue")
  84.         control_frame.pack(pady=20)
  85.  
  86.         self.play_button = Button(control_frame, text="Play", command=self.play_selected_song)
  87.         self.play_button.grid(row=0, column=0, padx=5)
  88.  
  89.         self.stop_button = Button(control_frame, text="Stop", command=self.stop_song)
  90.         self.stop_button.grid(row=0, column=1, padx=5)
  91.  
  92.         prev_button = Button(control_frame, text="Previous", command=self.play_previous)
  93.         prev_button.grid(row=0, column=2, padx=5)
  94.  
  95.         next_button = Button(control_frame, text="Next", command=self.play_next)
  96.         next_button.grid(row=0, column=3, padx=5)
  97.  
  98.     def setup_volume_control(self):
  99.         volume_frame = Frame(self.root, bg="lightblue")
  100.         volume_frame.pack(pady=10)
  101.  
  102.         volume_label = Label(volume_frame, text="Volume", bg="lightblue")
  103.         volume_label.pack(side=LEFT)
  104.  
  105.         self.volume_slider = Scale(volume_frame, from_=0, to=100, orient=HORIZONTAL, command=self.set_volume)
  106.         self.volume_slider.set(50)  # Set initial volume to 50%
  107.         self.volume_slider.pack(side=LEFT)
  108.  
  109.     def setup_position_slider(self):
  110.         self.position_slider = Scale(self.root, from_=0, to=100, orient=HORIZONTAL, command=self.seek_position)
  111.         self.position_slider.pack(fill=X, padx=10, pady=10)
  112.  
  113.     def browse_folder(self):
  114.         folder_path = filedialog.askdirectory()
  115.         if not folder_path:
  116.             return
  117.         self.listbox.delete(0, END)
  118.         self.cursor.execute("DELETE FROM mp3_files")  # Clear previous entries
  119.         self.db_connection.commit()
  120.  
  121.         for filename in os.listdir(folder_path):
  122.             if filename.endswith(".mp3"):
  123.                 file_path = os.path.join(folder_path, filename)
  124.                 with open(file_path, 'rb') as file:
  125.                     file_data = file.read()
  126.                     self.cursor.execute("INSERT INTO mp3_files (filename, filedata) VALUES (?, ?)",
  127.                                         (filename, file_data))
  128.                 self.listbox.insert(END, filename)
  129.  
  130.         self.db_connection.commit()
  131.         messagebox.showinfo("Success", "MP3 files loaded from folder and saved to database!")
  132.  
  133.     def load_mp3s_from_database(self):
  134.         self.listbox.delete(0, END)
  135.         self.cursor.execute("SELECT filename FROM mp3_files")
  136.         for row in self.cursor.fetchall():
  137.             self.listbox.insert(END, row[0])
  138.  
  139.     def add_mp3_file(self):
  140.         file_path = filedialog.askopenfilename(filetypes=[("MP3 files", "*.mp3")])
  141.         if not file_path:
  142.             return
  143.         filename = os.path.basename(file_path)
  144.         with open(file_path, 'rb') as file:
  145.             file_data = file.read()
  146.             self.cursor.execute("INSERT INTO mp3_files (filename, filedata) VALUES (?, ?)",
  147.                                 (filename, file_data))
  148.         self.db_connection.commit()
  149.         self.listbox.insert(END, filename)
  150.         messagebox.showinfo("Success", "MP3 file added to database!")
  151.  
  152.     def delete_mp3_file(self):
  153.         selected_index = self.listbox.curselection()
  154.         if not selected_index:
  155.             return
  156.         song_name = self.listbox.get(selected_index)
  157.         self.cursor.execute("DELETE FROM mp3_files WHERE filename = ?", (song_name,))
  158.         self.db_connection.commit()
  159.         self.listbox.delete(selected_index)
  160.         messagebox.showinfo("Deleted", "MP3 file deleted from database.")
  161.  
  162.     def save_mp3_to_database(self):
  163.         selected_index = self.listbox.curselection()
  164.         if not selected_index:
  165.             messagebox.showwarning("Warning", "Please select an MP3 file to save.")
  166.             return
  167.         song_name = self.listbox.get(selected_index)
  168.  
  169.         folder_path = filedialog.askdirectory()
  170.         if not folder_path:
  171.             return
  172.  
  173.         self.cursor.execute("SELECT filedata FROM mp3_files WHERE filename = ?", (song_name,))
  174.         file_data = self.cursor.fetchone()
  175.        
  176.         if file_data:
  177.             file_path = os.path.join(folder_path, song_name)
  178.             with open(file_path, 'wb') as file:
  179.                 file.write(file_data[0])
  180.             messagebox.showinfo("Success", f"MP3 file '{song_name}' saved to selected folder.")
  181.         else:
  182.             messagebox.showerror("Error", "File data not found in database.")
  183.  
  184.     def play_selected_song(self, event=None):
  185.         selected_index = self.listbox.curselection()
  186.         if not selected_index:
  187.             return
  188.         song_name = self.listbox.get(selected_index)
  189.        
  190.         self.cursor.execute("SELECT filedata FROM mp3_files WHERE filename = ?", (song_name,))
  191.         song_data = self.cursor.fetchone()[0]
  192.  
  193.         with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as temp_file:
  194.             temp_file.write(song_data)
  195.             temp_file_path = temp_file.name
  196.             self.temp_files.append(temp_file_path)
  197.        
  198.         self.media_player.set_media(self.vlc_instance.media_new(temp_file_path))
  199.         self.media_player.play()
  200.         self.update_position_slider()
  201.  
  202.     def stop_song(self):
  203.         self.media_player.stop()
  204.         self.position_slider.set(0)
  205.  
  206.     def play_next(self):
  207.         current_index = self.listbox.curselection()[0]
  208.         next_index = (current_index + 1) % self.listbox.size()
  209.         self.listbox.select_clear(current_index)
  210.         self.listbox.select_set(next_index)
  211.         self.play_selected_song()
  212.  
  213.     def play_previous(self):
  214.         current_index = self.listbox.curselection()[0]
  215.         prev_index = (current_index - 1) % self.listbox.size()
  216.         self.listbox.select_clear(current_index)
  217.         self.listbox.select_set(prev_index)
  218.         self.play_selected_song()
  219.  
  220.     def set_volume(self, volume):
  221.         self.media_player.audio_set_volume(int(volume))
  222.  
  223.     def update_position_slider(self):
  224.         if self.media_player.is_playing():
  225.             current_pos = self.media_player.get_time() // 1000
  226.             self.position_slider.set(current_pos)
  227.             self.root.after(1000, self.update_position_slider)
  228.  
  229.     def seek_position(self, position):
  230.         self.media_player.set_time(int(position) * 1000)
  231.  
  232.     def delete_temp_files(self):
  233.         # First, stop the media player to release any file handles
  234.         self.media_player.stop()
  235.  
  236.         deleted_files = []
  237.         for temp_file in self.temp_files:
  238.             try:
  239.                 if os.path.exists(temp_file):
  240.                    os.remove(temp_file)
  241.                    deleted_files.append(temp_file)
  242.             except Exception as e:
  243.                  messagebox.showerror("Error", f"Failed to delete {temp_file}: {e}")
  244.    
  245.         self.temp_files.clear()  # Clear the list after deletion
  246.         if deleted_files:
  247.             messagebox.showinfo("Success", f"Temporary files deleted: {', '.join(deleted_files)}")
  248.         else:
  249.             messagebox.showinfo("Success", "No temporary files to delete.")
  250.  
  251.  
  252.     def load_gif(self, gif_path):
  253.         self.gif_label = Label(self.root)
  254.         self.gif_label.pack()
  255.         self.gif = Image.open(gif_path)
  256.         self.frames = [ImageTk.PhotoImage(frame.copy()) for frame in ImageSequence.Iterator(self.gif)]
  257.         self.gif_label.configure(image=self.frames[0])
  258.         self.gif_index = 0
  259.         self.update_gif()
  260.  
  261.     def update_gif(self):
  262.         self.gif_index = (self.gif_index + 1) % len(self.frames)
  263.         self.gif_label.configure(image=self.frames[self.gif_index])
  264.         self.root.after(100, self.update_gif)
  265.  
  266. if __name__ == "__main__":
  267.     root = Tk()
  268.     app = Mp3PlayerApp(root)
  269.     root.mainloop()
  270.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement