【问题标题】:How to assign sounds to channels in Pygame?如何在 Pygame 中为通道分配声音?
【发布时间】:2016-06-25 13:21:21
【问题描述】:

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

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

        var.rain_sound.play()

        if random.randint(0,80) == 10:                
            thunder = var.thunder_sound                
            thunder.play()

感谢您的帮助

【问题讨论】:

    标签: python python-2.7 audio pygame


    【解决方案1】:

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

    sound1 = pygame.mixer.Sound("sound.wav")
    pygame.mixer.find_channel().play(sound1)
    

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

    sound1 = pygame.mixer.Sound("sound.wav")
    pygame.mixer.find_channel(True).play(sound1)
    

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

    pygame.mixer.set_num_channels(20)
    

    【讨论】:

      【解决方案2】:

      每个频道一次只能播放一种声音,但您可以一次播放多个频道。如果不命名通道,pygame 会选择一个未使用的通道来播放声音;默认情况下,pygame 有 8 个通道。您可以通过创建 Channel 对象来指定通道。至于无限循环播放声音,您可以通过使用参数 loops = -1 播放声音来做到这一点。您可以在 http://www.pygame.org/docs/ref/mixer.html
      找到这些类和方法的文档 我还建议使用内置模块 time,特别是 sleep() 函数,该函数将执行暂停指定时间(以秒为单位)。这是因为播放声音的 pygame.mixer 函数会在声音完成播放之前很久就返回,并且当您尝试在同一通道上播放第二个声音时,第一个声音会停止播放第二个声音。所以,为了保证你的雷声播放完成,最好在播放的时候暂停执行。我将 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)
      

      【讨论】:

      • 您也可以通过pygame.mixer.Channel.get_busy()查看某个频道当前是否忙于播放声音。
      猜你喜欢
      • 2019-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多