Search code examples
pythonpython-3.xpygamemixer

Skipping sound track (pygame.mixer.music)


I am making a snake game with pygame and I want to know something about pygame.mixer.music().

Code:

snakebodypos.insert(0, list(snakepos))
if snakepos[0] == foodpos[0] and snakepos[1] == foodpos[1]:
    pygame.mixer.music.stop()
    pygame.mixer.music.load(eatsound)
    pygame.mixer.music.play(1, 0.0)
    pygame.mixer.music.load(main)
    pygame.mixer.music.play(-1, 0.0)
    foodspawn = False
    score += 1

So, when I stop and the eatsound is supposed to play, it just skips it and plays the stopped sound again.

KEEP IN MIND!
When I use pause and unpause, it doesn't unpause again. I don't know why so I use the stop. If you know why that happens, please let me know.


Solution

  • Is there any reason you want to stop the background music while playing the eatsound?

    Your code does not work because after you load and play eatsound, you immediatly load main again, so eatsound has no time to play.


    Usually, you use pygame.mixer.music to play background music, and for sound effects, you use pygame.mixer.Sound, so your code should look like this:

    # load the Sound once at the beginning
    eatsound_sound = pygame.mixer.Sound(eatsound)
    
    ...
    
    snakebodypos.insert(0, list(snakepos))
    if snakepos[0] == foodpos[0] and snakepos[1] == foodpos[1]:
        # play the eat sound. don't touch the background music
        eatsound_sound.play() 
        foodspawn = False
        score += 1