background music not playing in pygame

2019-08-02 19:52发布

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?

标签: python pygame
1条回答
太酷不给撩
2楼-- · 2019-08-02 19:57

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).

查看更多
登录 后发表回答