[英]Is there a way to play multiple mp3 files at once in pygame?
我正在尝试播放 2 个 mp3 文件,但每次播放另一个文件时,第一个都会停止。 每当我使用频道时,游戏最终都会崩溃。
这是我的代码:
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()
有什么方法可以允许同时播放 2 个 mp3 文件,还是必须将它们全部转换为 wav?
就这样,这个问题有一个正式的答案......
使用 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.