Top.Mail.Ru
Ответы

Помогите оптимизировать код Python

код выдает полный ужас делает то чего я не программировал я новичок поэтому не знаю как оптимизировать свой код прошу помощи

код

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
import pygame, time, os, random, keyboard

pygame.mixer.init()

run = True
run_1 = True

def main():
	os.system("cls")

	while run:
		run_1 = True
		massive = os.listdir("C:/Users/user/Desktop/муз") # создание массива с путем к песням
		try:
			random_choice_massive = random.choice(massive) 
			sound = pygame.mixer.Sound(f"C:/Users/user/desktop/муз/{random_choice_massive}")
			long_song = sound.get_length()
			long_song = round(long_song)
			long_song = long_song+1
			second = 0
			sound.play()
			while run_1:
				print(random_choice_massive, "...", second, long_song)
				round(second, 1)
				time.sleep(0.1)
				os.system("cls")
				if long_song == second:
					sound.stop()
					run_1 = False
				# проверка нажатий клавиш	
				if keyboard.is_pressed('shift'):
					sound.stop()
					run_1 = False
				if keyboard.is_pressed('esc'):
					sound.stop()
					run_1 = False


		# отдел обработки ошибок
		except FileNotFoundError:
			print("Файла нет")
			time.sleep(3)
			main()
		except pygame.error as Error:
			print(f"Ошибка воспроизведения: {Error}")
			time.sleep(3)
			main()

if __name__ == '__main__':
	main()
По дате
По рейтингу
Аватар пользователя
Гуру
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
import pygame
import time
import random
from pathlib import Path
import keyboard  # Note: keyboard requires admin privileges on some OS

# Initialize pygame mixer
pygame.mixer.init()

# Path to music directory
MUSIC_DIR = Path("C:/Users/user/Desktop/муз")

def clear_console():
    os.system('cls' if os.name == 'nt' else 'clear')

def play_random_song():
    # Get list of music files
    music_files = list(MUSIC_DIR.glob("*"))
    if not music_files:
        print("No music files found in the directory.")
        return False

    # Choose a random music file
    song_path = random.choice(music_files)
    try:
        # Load and play music using pygame.mixer.music
        pygame.mixer.music.load(str(song_path))
        pygame.mixer.music.play()

        # Get length of the song
        # pygame.mixer.music does not provide length directly,
        # so we use pygame.mixer.Sound for length only
        sound = pygame.mixer.Sound(str(song_path))
        song_length = sound.get_length()

        start_time = time.time()

        while pygame.mixer.music.get_busy():
            elapsed = time.time() - start_time
            clear_console()
            print(f"Playing: {song_path.name}")
            print(f"Time: {int(elapsed)} / {int(song_length)} seconds")
            print("Press SHIFT to skip, ESC to exit.")

            # Check for key presses
            if keyboard.is_pressed('shift'):
                pygame.mixer.music.stop()
                break
            if keyboard.is_pressed('esc'):
                pygame.mixer.music.stop()
                return False

            time.sleep(0.2)

        return True

    except pygame.error as e:
        print(f"Playback error: {e}")
        time.sleep(3)
        return True

def main():
    clear_console()
    print("Starting music player...")

    while True:
        continue_playing = play_random_song()
        if not continue_playing:
            print("Exiting player.")
            break

if __name__ == "__main__":
    main()