Reputation: 66
I'm trying to create a simple game by using Pygame and I want to add some in-game sounds repeating during play time. However, the game stops running when I apply those codes:
def in-gameSounds():
pygame.mixer.init()
startTime = time.time()
theFile = 'Sounds/gameSound.ogg'
theFile2 = 'Sounds/gameSound2.ogg'
pygame.mixer.music.load(theFile)
pygame.mixer.music.play()
playing = True
while playing == True:
while time.time() <= startTime + 457:
time.sleep(0.01)
pygame.mixer.music.stop()
pygame.mixer.music.load(theFile2)
while time.time() > startTime + 457 and time.time() <= startTime+ 3752:
time.sleep(0.01)
pygame.mixer.music.stop()
for click in pygame.event.get():
if click.type == pygame.KEYDOWN:
if click.key == pygame.K_ESCAPE:
playing = False
startTime -= 3752
pygame.mixer.quit()
Upvotes: 0
Views: 375
Reputation: 21
Have you tried passing pygame.mixer.music.play() an argument of -1? That makes it loop indefinitely. From there you can use the pause(), unpause(), and rewind() methods.
Upvotes: 1
Reputation: 3106
You could always use pygame.mixer.init()
followed by pygame.mixer.music.play(-1)
in the top of your program instead of putting it in a function. Since a value of -1 one inside of the ()
will mean an infinite loop, the music will continuously play unless forced to stop via program killing, Ctrl-C, etc.
pygame.mixer.init() # Initiate pygame.mixer
pygame.mixer.music.load('song_name_here') # Load song to play
pygame.mixer.music.set_volume(0.7) # Change volume
pygame.mixer.music.play(-1) # Play song infinitely
Upvotes: 0