栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

每个通道一次只能播放一个声音,但是一次可以播放多个通道。如果您不命名频道,pygame会选择一个未使用的频道来播放声音。默认情况下,pygame有8个频道。您可以通过创建Channel对象来指定通道。至于无限循环声音,您可以通过使用参数loops

-1播放声音来实现。您可以在http://www.pygame.org/docs/ref/mixer.html上找到这些类和方法的文档。
我还建议使用内置的模块时间,尤其是使用sleep()函数将执行暂停几秒钟的指定时间。这是因为pygame.mixer函数会在声音结束播放之前很早就返回声音,并且当您尝试在同一通道上播放第二声音时,第一声音会停止播放第二声音。因此,为确保您的“雷声”已播放完毕,最好在播放时暂停执行。我将sleep()行放在if语句之外,因为在if语句内,如果没有播放雷声,sleep()行将不会暂停执行,因此循环会非常快地循环到下一个雷声声音,输出频率远高于“偶然”。

import pygameimport randomimport timeimport var# initialize pygame.mixerpygame.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 playbackchannel1 = pygame.mixer.Channel(0) # argument must be intchannel2 = pygame.mixer.Channel(1)# plays loop of rain sound indefinitely until stopping playback on Channel,# interruption by another Sound on same Channel, or quitting pygamechannel1.play(var.rain_sound, loops = -1)# plays occasional thunder soundsduration = var.thunder_sound.get_length() # duration of thunder in secondswhile 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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/648359.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号