Skip to main content
 首页 » 编程设计

python之使用pygame在左声道和右声道上播放两个不同的音频文件

2025年01月19日11lyhabc

我有一个代码,我在两个不同的 channel 中指定了两个不同的音频文件并同时播放,但我需要一种方法让每个文件只在一个 channel 上播放,另一个在另一个 channel 上播放。例如,两个音频文件同时在两个单独的 channel (右 channel 和左 channel )上播放。这样一个音频在右扬声器上播放,另一个音频在左扬声器上播放。

我尝试使用下面的代码,但音频未映射到任何特定 channel ,而是在两个扬声器上播放。

pygame.mixer.init(frequency=44000, size=-16,channels=2, buffer=4096) 
#pygame.mixer.set_num_channels(2) 
m = pygame.mixer.Sound('tone.wav') 
n = pygame.mixer.Sound('sound.wav') 
pygame.mixer.Channel(1).play(m,-1) 
pygame.mixer.Channel(2).play(n,-1) 

非常感谢任何帮助。

请您参考如下方法:

文档说你必须将左右扬声器的音量传递给 Channel.set_volume .

# Create Sound and Channel instances. 
sound0 = pg.mixer.Sound('my_sound.wav') 
channel0 = pg.mixer.Channel(0) 
 
# Play the sound (that will reset the volume to the default). 
channel0.play(sound0) 
# Now change the volume of the specific speakers. 
# The first argument is the volume of the left speaker and 
# the second argument is the volume of the right speaker. 
channel0.set_volume(1.0, 0.0) 

此外,如果您不想自己管理 channel ,您可以只使用 Sound.play() 返回的 channel 。

channel = sound0.play() 
channel.set_volume(1.0, 0.0)