user11604499
user11604499

Reputation:

No sound is played in pygame

I made a program to play music at random using python-pygame. When I tried to run, the audio did not play ... By the way, I think that the problem is pygame because the volume is MAX and it can be heard normally even when playing .mp3

music.py

import pygame
import sys
import glob
from random import shuffle

x = glob.glob("sound/*.mp3") 
shuffle(x)

print(x[1])

pygame.mixer.init()
pygame.mixer.music.load(x[1])
pygame.mixer.music.play(2) 

while False:
    x = 1

pygame.mixer.music.stop() 
sys.exit()

Upvotes: 0

Views: 584

Answers (1)

Valentino
Valentino

Reputation: 7361

Seems you want to play only one file randomly chosen. You want something like this:

import pygame
import sys
import glob
from random import choice

allmusic = glob.glob("*.mp3") 
played = choice(allmusic) #select randomly one element from the list

print(played) #print the name of the chosen file
pygame.mixer.init()

pygame.mixer.music.load(played)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
    pass

the last while loop checks if the music is played, and do nothing until the music ends. It's purpose is to keep the program alive, otherwise it ends immediately and the music stream is terminated.

Notice that you do not have control on the music, it will play until the end with no way to stop it before. To have some control of this kind, you need a more complex script handling events (from keyboard or a custom GUI interface you create, but this is going too far from your question I think).

Upvotes: 1

Related Questions