如何在 Pygame 中为通道分配声音?

Sor*_*ade 5 python audio pygame python-2.7

我正在尝试在 Pygame 中同时播放多个声音。我有一个背景音乐,我想要一个连续播放的雨声并播放偶尔的雷声。

我尝试了以下方法,但是当雷声播放时我的雨声停止了。我曾尝试使用频道,但我不知道如何选择播放声音的频道,或者是否可以同时播放两个频道。

        var.rain_sound.play()

        if random.randint(0,80) == 10:                
            thunder = var.thunder_sound                
            thunder.play()
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助

Pik*_*er2 7

Pygame 的find_channel函数可以很容易地在未使用的频道上播放音频:

sound1 = pygame.mixer.Sound("sound.wav")
pygame.mixer.find_channel().play(sound1)
Run Code Online (Sandbox Code Playgroud)

请注意,默认情况下,None如果没有可用的免费频道, find_channel 将返回。通过传递它True,您可以改为返回播放音频时间最长的频道:

sound1 = pygame.mixer.Sound("sound.wav")
pygame.mixer.find_channel(True).play(sound1)
Run Code Online (Sandbox Code Playgroud)

您可能还对set_num_channels函数感兴趣,它可以让您设置音频通道的最大数量:

pygame.mixer.set_num_channels(20)
Run Code Online (Sandbox Code Playgroud)


Bat*_*aBe 5

每个频道一次只能播放一个声音,但您可以一次播放多个频道。如果你不命名频道,pygame 会选择一个未使用的频道来播放声音;默认情况下,pygame 有 8 个通道。您可以通过创建 Channel 对象来指定通道。至于无限循环播放声音,您可以通过使用参数 loops = -1 播放声音来实现。您可以在http://www.pygame.org/docs/ref/mixer.html找到这些类和方法的文档
我还建议使用内置模块 time,尤其是 sleep() 函数,它可以将执行暂停指定的时间(以秒为单位)。这是因为播放声音的 pygame.mixer 函数会在声音播放完毕之前很久就返回,并且当您尝试在同一频道上播放第二个声音时,第一个声音会停止播放第二个声音。因此,为了保证您的 Thunder Sound 播放完毕,最好在播放时暂停执行。我将 sleep() 行放在 if 语句之外,因为在 if 语句内部,如果未播放雷声,则 sleep() 行不会暂停执行,因此循环将很快循环到下一个雷声声音,输出频率远高于“偶尔”。

import pygame
import random
import time
import var

# initialize pygame.mixer
pygame.mixer.init(frequency = 44100, size = -16, channels = 1, buffer = 2**12) 
# init() channels refers to mono vs stereo, not playback Channel object

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

# plays loop of rain sound indefinitely until stopping playback on Channel,
# interruption by another Sound on same Channel, or quitting pygame
channel1.play(var.rain_sound, loops = -1)

# plays occasional thunder sounds
duration = var.thunder_sound.get_length() # duration of thunder in seconds
while True: # infinite while-loop
    # play thunder sound if random condition met
    if random.randint(0,80) == 10:
        channel2.play(var.thunder_sound)
    # pause while-loop for duration of thunder
    time.sleep(duration)
Run Code Online (Sandbox Code Playgroud)