使用 simpleio.tone(board, frequency, duration=),我知道如何使用 for 循环遍历频率参数中的频率列表。我将如何为持续时间参数执行此操作?我想用压电蜂鸣器播放一首歌,我需要不同的频率来播放不同的持续时间。
任何帮助表示赞赏,谢谢。
使用 simpleio.tone(board, frequency, duration=),我知道如何使用 for 循环遍历频率参数中的频率列表。我将如何为持续时间参数执行此操作?我想用压电蜂鸣器播放一首歌,我需要不同的频率来播放不同的持续时间。
任何帮助表示赞赏,谢谢。
字典
您可以创建一个字典来存储频率作为键和持续时间作为它的值。这意味着您可以然后迭代字典并在持续时间指定的时间内播放频率。
# The key is the frequency and the value is the duration
data = {"124hz": 10, "125hz": 1, "126hz": 5}
for sound, duration in data.items():
# Play sound for duration.
print("Playing {} for {}s".format(sound, duration))
上述代码的输出将如下所示。
Playing 124hz for 10s
Playing 125hz for 1s
Playing 126hz for 5s
无需将这些作为打印语句输出,您只需使用 simpleio 模块中的方法将数据发送到压电蜂鸣器以发出声音