background music not playing in pygame

2019-08-02 19:25发布

问题:

When i run the code it play only the .wav file

import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAYSURF = pygame.display.set_mode((500, 400), 0, 32)

pygame.mixer.music.load('background.ogg')
pygame.mixer.music.play()

soundObj = pygame.mixer.Sound('bird.wav')
soundObj.play()
pygame.mixer.music.stop()

someone know what i should do for the background.ogg to be played too?

回答1:

Remove this line:

pygame.mixer.music.stop()

Basically, you're loading and playing the background noise, and then immediately stopping it. I also suggest you create a main loop, like so:

import pygame
from pygame.locals import *

# This makes sure that you're not importing the module.
if __name__ == "__main__":
    # Create surface
    size = width, height = (500, 400)
    # You don't need the extra arguments
    window = pygame.display.set_mode(size)
    # Do sound stuff
    pygame.mixer.music.load('background.ogg')
    pygame.mixer.music.play()

    soundObj = pygame.mixer.Sound('bird.wav')
    soundObj.play()
    # This is your main loop.
    running = True
    while running:
        # Check if escape was pressed

Most of the time people just check if Escape was pressed in their main loop (if it was pressed, they set running = False and exit the program).



标签: python pygame