eliavfox
eliavfox

Reputation: 21

pygame music player i couldnt manage to display the currently playing song correctly?

import random
import pygame as pg
import os

white = (255,255,255)
green = (0,255,0)
blue = (0,0,255)
os.chdir(r'C:\Users\Eliav\Desktop\project workspace\gui code\easyMusic')

song_finished = pg.USEREVENT +1
pg.mixer.pre_init(44100,-16,2,2048)
pg.init()
def random_song():
    songs = os.listdir()
    rnd_song = random.choice(songs)
    return rnd_song

def screen():
    clk = pg.time.Clock()
    screen = pg.display.set_mode((640,480))
    font = pg.font.Font('freesansbold.ttf', 32)
    text = font.render(random_song(), True, green, blue)
    textRect = text.get_rect()
    screen.fill(white)
    screen.blit(text, textRect)
    pg.display.flip()
    pg.display.update()
    clk.tick(30)


def main():
    rnd = random_song()
    done = False
    pg.mixer.music.load(rnd)
    pg.mixer.music.play(0)
    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == song_finished:
                print('Song finished. Playing random song.')
                pg.mixer.music.load(rnd)
                pg.mixer.music.play(0)
        screen()
main()

Upvotes: 2

Views: 83

Answers (1)

Rabbid76
Rabbid76

Reputation: 211278

See How to play random Mp3 files in Pygame. You have to display rnd, instead of another random_song(). However, get a new random song when the current song ends. e.g.:

def draw_text(surf, message, font, x, y):
    text = font.render(message, True, green, blue)
    textRect = text.get_rect(topleft = (x, y))
    surf.blit(text, textRect)
def main():
    screen = pg.display.set_mode((640,480))
    clk = pg.time.Clock()
    font = pg.font.Font('freesansbold.ttf', 32)

    song_finished = pygame.USEREVENT+1
    pg.mixer.music.set_endevent(song_finished)

    rnd = random_song()
    pg.mixer.music.load(rnd)
    pg.mixer.music.play(0)

    done = False
    while not done:
        clk.tick(30)
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == song_finished:
                print('Song finished. Playing random song.')
                rnd = random_song()
                pg.mixer.music.load(rnd)
                pg.mixer.music.play(0)

        screen.fill(white)
        draw_text(screen, rnd, font, 10, 10)
        pg.display.flip()

Upvotes: 3

Related Questions