0

Some pretext that's maybe useful idk. I use mixer and am trying to do a random music choice but the random.choice always take the last one (song 5). This is my code

if Mamp=='1':
vad=input("[1] Bakground music")
#Mixer shit
mixer.init()
pygame.mixer.get_init
if vad=='1':
    commands=[mixer.music.load("song1.mp3"), mixer.music.load("song2.mp3"),mixer.music.load("song3.mp3"),mixer.music.load("song4.mp3"),mixer.music.load("song5.mp3")]
    current_command=random.choice(commands)
    current_command
    mixer.music.play(0)

I looked at many answers for the same problem but all wer're just fixing thier (the uploader's) code and uploaded it so I couldn't use it for my code. And since i'm trying to learn python it would be great if you could also explain what went wrong?

CobraCabbe
  • 105
  • 6
  • 1
    Did you try reading the documentation for `mixer.music.load`? It seems as though you expect that picking a random value from `commands` will affect which song is played. Why? Did you try to check what `commands` contains? (After reading the documentation, do you understand why?) Aside: `current_command` doesn't do anything by itself; this is in a script, so you can't see the value that way - if you want a script to display something, you have to do that explicitly, for example using `print`. Also, `pygame.mixer.get_init` is a *function*, and this code does *not* call it. – Karl Knechtel May 14 '22 at 01:29
  • Welcome back to Stack Overflow. As a refresher, please re-read [ask] and the [formatting help](https://stackoverflow.com/help/formatting), and make sure you understand how to make the code appear with the same indentation as you actually have, since indentation is crucial in Python. – Karl Knechtel May 14 '22 at 01:30

1 Answers1

3
commands=[mixer.music.load("song1.mp3"), ...]
current_command=random.choice(commands)
current_command

You're doing this part all wrong.

It seems like you want to make a list of commands to be executed later, but that's not what you're actually doing. The load() commands are actually executed when the commands list is created. And because song5.mp3 is the last one, it gives the appearance of being "picked" every time.

Try it this way instead:

songs = ["song1.mp3", "song2.mp3", "song3.mp3", "song4.mp3", "song5.mp3"]
song = random.choice(songs)
mixer.music.load(song)
John Gordon
  • 29,573
  • 7
  • 33
  • 58
  • I think it's possible that OP didn't understand that multiple `mixer.music.load` calls *can't* just be done ahead of time. Given that a separate `.play` call is required in order to actually hear the music, it would seem like a reasonable expectation. – Karl Knechtel May 14 '22 at 01:31