首页 > 解决方案 > Is there a way to play multiple mp3 files at once in pygame?

问题描述

I'm trying to play 2 mp3 files, but every time the other one plays, the first one stops. Whenever I use channel, the game ends up crashing.

Here is my code:

pygame.mixer.music.load('music.mp3')
pygame.mixer.music.play(-1)
#insert generic if statement here
pygame.mixer.music.load("differentmusic.mp3')
pygame.mixer.music.play()

is there any way to allow 2 mp3 files to be playing at the same time, or do I have to convert them all to wav?

标签: pythonpygame

解决方案


就这样,这个问题有了一个正式的答案……

PyGame无法MP3同时使用通道播放多个声音文件。它们可以单独与一pygame.mixer.music组功能一起播放。

但是,绝对有可能将您的声音文件转换为OGG 声音格式——其压缩方式与 MP3 或未压缩的 WAV 格式非常相似。显然,如果您想编写 MP3 音乐播放器,这不是一个解决方案,但对于游戏来说,这是一个次要的要求。Audacity等免费软件可以轻松转换声音格式。

我已将评论链接中的示例改编为不使用该var模块。就像链接的代码一样,它会不断播放雨声,按下会在输出中h添加一个汽车喇叭meep-meep

import pygame

# Window size
WINDOW_WIDTH    = 400
WINDOW_HEIGHT   = 400
WINDOW_SURFACE  = pygame.HWSURFACE|pygame.DOUBLEBUF|pygame.RESIZABLE

DARK_BLUE = (   3,   5,  54)

### initialisation
pygame.init()
pygame.mixer.init()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ), WINDOW_SURFACE )
pygame.display.set_caption("Multi Sound")

### sound
# create separate Channel objects for simultaneous playback
channel1 = pygame.mixer.Channel(0) # argument must be int
channel2 = pygame.mixer.Channel(1)

# Rain sound from: https://www.freesoundslibrary.com/sound-of-rain-falling-mp3/ (CC BY 4.0)
rain_sound = pygame.mixer.Sound( 'rain-falling.ogg' )
channel1.play( rain_sound, -1 )   # loop the rain sound forever

# Car Horn sound from: https://www.freesoundslibrary.com/car-horn-sound-effect/ (CC BY 4.0)
horn_sound = pygame.mixer.Sound( 'car-horn.ogg' )

### Main Loop
clock = pygame.time.Clock()
done = False
while not done:

    # Handle user-input
    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ):
            done = True
        elif ( event.type == pygame.KEYUP ):
            if ( event.key == pygame.K_h ):
                if ( not channel2.get_busy() ):                          # play horn if not already playing
                    channel2.play( horn_sound )
                    print( 'meep-meep' )

    # Window just stays blue
    window.fill( DARK_BLUE )
    pygame.display.flip()

    # Clamp FPS
    clock.tick_busy_loop(60)

pygame.quit()

推荐阅读