Guest User

Untitled

a guest
May 28th, 2024
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.21 KB | Source Code | 0 0
  1. import os
  2. import random
  3. import threading
  4. import time
  5. import pygame
  6.  
  7. class MusicPlayer:
  8.     def __init__(self, music_directory, shuffle=False):
  9.         self.music_directory = music_directory
  10.         self.shuffle = shuffle
  11.         self.playlist = self.load_playlist()
  12.         self.current_index = 0
  13.         self.is_playing = False
  14.         self.is_paused = False
  15.         self.thread = None
  16.         pygame.mixer.init()
  17.  
  18.     def load_playlist(self):
  19.         return [os.path.join(self.music_directory, f) for f in os.listdir(self.music_directory) if f.endswith(('.mp3', '.wav'))]
  20.  
  21.     def play_music(self):
  22.         if not self.playlist:
  23.             print("No music files found in the directory.")
  24.             return
  25.  
  26.         if self.shuffle:
  27.             random.shuffle(self.playlist)
  28.  
  29.         self.is_playing = True
  30.         self.is_paused = False
  31.         pygame.mixer.music.load(self.playlist[self.current_index])
  32.         pygame.mixer.music.play()
  33.  
  34.         while self.is_playing:
  35.             if not pygame.mixer.music.get_busy():
  36.                 self.play_next()
  37.             time.sleep(1)
  38.  
  39.     def play_music_thread(self):
  40.         if self.thread is None or not self.thread.is_alive():
  41.             self.thread = threading.Thread(target=self.play_music)
  42.             self.thread.start()
  43.  
  44.     def play_next(self):
  45.         self.current_index = (self.current_index + 1) % len(self.playlist)
  46.         pygame.mixer.music.load(self.playlist[self.current_index])
  47.         pygame.mixer.music.play()
  48.  
  49.     def pause_music(self):
  50.         if self.is_playing and not self.is_paused:
  51.             pygame.mixer.music.pause()
  52.             self.is_paused = True
  53.  
  54.     def unpause_music(self):
  55.         if self.is_playing and self.is_paused:
  56.             pygame.mixer.music.unpause()
  57.             self.is_paused = False
  58.  
  59.     def stop_music(self):
  60.         self.is_playing = False
  61.         pygame.mixer.music.stop()
  62.         if self.thread is not None:
  63.             self.thread.join()
  64.  
  65.     def set_volume(self, volume):
  66.         pygame.mixer.music.set_volume(volume / 100.0)
  67.  
  68.     def seek_forward(self, seconds):
  69.         if self.is_playing:
  70.             pygame.mixer.music.set_pos(pygame.mixer.music.get_pos() / 1000.0 + seconds)
  71.  
Advertisement
Add Comment
Please, Sign In to add comment