简体   繁体   English

Pygame 混音器音乐(多首音乐曲目)

[英]Pygame Mixer music (multiple music tracks)

I have a quite simple question but surprisingly did not find a duplicate.我有一个非常简单的问题,但令人惊讶的是没有找到重复的问题。

I have 2 music tracks for my game and want to switch fom the first music to something else before it runs out naturally.我的游戏有 2 个音乐曲目,想在第一首音乐自然用完之前将其切换到其他音乐。

mixer.music.load('music.mp3')
mixer.music.queue("music_phase2.mp3")
mixer.music.play(1, 0.0, 3000)

Normally i can use music.queue to go to the next music track.通常我可以使用 music.queue 到 go 到下一首音乐曲目。 But i want the first music to stop after a specific event (like a timer or counter) and immediately start the next track.但我希望第一首音乐在特定事件(如计时器或计数器)后停止并立即开始下一首曲目。

I thought of something like this but it didnt work.我想到了这样的事情,但没有用。 (I need to mention that in my program i want to load the music within a while loop so maybe that is causing problems.) This part of the code handles the music. (我需要指出的是,在我的程序中,我想在 while 循环中加载音乐,所以这可能会导致问题。)这部分代码处理音乐。 The first music stops as it should afte the counterr reaches 10. But the second music doesnt start to play (just silence).在计数器达到 10 后,第一首音乐会停止播放。但是第二首音乐不会开始播放(只是静音)。

from pygame import mixer
pygame.mixer.init()

running = True

mixer.music.load('music.mp3')
mixer.music.play(1, 0.0, 3000)

# main loop
while running:
    if logic.counter > 10:
        mixer.music.stop()
        mixer.music.unload()
        mixer.music.load('music_phase2.mp3')
        mixer.music.play(1, 0.0, 3000)


#code doesnt end here but the rest shouldnt influence the music

I found your mistake.我发现了你的错误。 You are doing:你在做:

while running:
    if logic.counter > 10:
        mixer.music.stop()
        mixer.music.unload()
        mixer.music.load('music_phase2.mp3')
        mixer.music.play(1, 0.0, 3000)

The problem is, the logic.counter keeps increasing!问题是, logic.counter一直在增加! I don't see anywhere a flag or something inside the code that is supposed to stop the logic.counter from increasing!我没有在代码中的任何地方看到任何应该阻止logic.counter增加的标志或东西!

This means that once the logic.counter reaches 11, it enters the if block.这意味着一旦logic.counter达到 11,它就会进入if块。 However , it will enter the if when it is 12 and re-load the music again.但是,它会在 12 时进入if并再次重新加载音乐。 and again, and again.一次又一次。 Forever.永远。 You need to change it to:您需要将其更改为:

    if logic.counter == 10:

So it will unload the first music and load the second music only once.所以它只会卸载第一首音乐并加载第二首音乐。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM