Reputation: 386
So i've been trying to play music on Python, what I've done is define variables inside the function and call that function inside a loop.
I've tried changing the parameters and changing the location of the variables which did not try out too well. I did try to play the music file from another location and it worked, just don't know what's wrong with my function.
def main_menu():
DS.blit(mainmenu, (0, 0))
pygame.display.update()
MenuMusic = pygame.mixer.music.load("MainMenu.mp3")
MenuMusic = pygame.mixer.music.set_volume(0.45)
MenuMusic = pygame.mixer.music.play()
while loop:
main_menu()
I expect the output to be the sound playing smoothly and properly in the background, but instead I'm getting these strange clicking sounds in the background kinda like someone's drumming.
Upvotes: 1
Views: 310
Reputation: 14906
This code snippet looks like you're continually re-starting the playing of the MP3.
It needs to start the playing of the sound, and when it stops re-start it. The output status of the mixer can be checked with pygame.mixer.get_busy(), which returns False when there is no sound output.
So for a looping sound, simply test that it's stopped, and re-start:
import pygame
import enum
pygame.mixer.init()
pygame.mixer.music.set_volume(0.45)
class GameState( enum.Enum ):
PLAYING = 1
MENU = 2
GAMEOVER = 3
# Set the game state initially. Start on the menu screen/music
game_state = GameState.MENU
def main_menu():
DS.blit(mainmenu, (0, 0))
pygame.display.update()
...
while loop:
# If the sound has not started (or has finished), play it (again)
if ( pygame.mixer.get_busy() == False ):
if ( game_state == GameState.MENU ):
pygame.mixer.music.load( "elevator_music.mp3" )
elif ( game_state == GameState.PLAYING ):
pygame.mixer.music.load( "battle_music.mp3" )
elif ( game_state == GameState.GAMEOVER ):
pygame.mixer.music.load( "other_music.mp3" )
pygame.mixer.music.play()
main_menu()
EDIT: I forgot the pygame
and enum
imports.
Upvotes: 1