import time
import winsound
# 设置频率和持续时间
frequency = 37 # 频率,单位是Hz
duration = 1000 # 持续时间,单位是毫秒
# 发出声音
winsound.Beep(frequency, duration)
# 如果您想连续发出声音,可以使用循环
try:
while True:
winsound.Beep(frequency, duration)
time.sleep(1) # 暂停一秒
except KeyboardInterrupt:
# 允许使用Ctrl+C中断循环
print("声音停止")
修改频率可得到不同的声音,
频率的最大值是:37Hz
最小值是32767Hz
–
import winsound
import time
# 定义每个音符的频率(以Hz为单位)和持续时间(毫秒)
notes = {
'C4': 261.63,
'D4': 293.66,
'E4': 329.63,
'F4': 349.23,
'G4': 392.00,
'A4': 440.00,
'B4': 493.88,
'C5': 523.25
}
# 音符持续时间(毫秒)
duration = 500
# 四分音符的频率值,转换为整数
note_frequencies = {note: int(frequency) for note, frequency in notes.items()}
# 一个简化的主旋律,用音符名称表示
melody = [
'C4', 'E4', 'G4', 'C5',
'B4', 'A4', 'G4', 'F4',
'E4', 'D4', 'C4',
'A4', 'G4', 'F4', 'E4'
]
# 演奏旋律
for note in melody:
frequency = note_frequencies[note]
winsound.Beep(frequency, duration) # 发出音符
time.sleep(duration / 1000.0) # 等待音符结束
# 等待旋律结束后再退出
time.sleep(2)
–
import winsound
import time
# 定义每个音符的频率(以Hz为单位)和持续时间(毫秒)
notes = [
{"frequency": 262, "duration": 500}, # C5
{"frequency": 294, "duration": 500}, # D5
{"frequency": 330, "duration": 500}, # E5
{"frequency": 349, "duration": 1500}, # F5 (held longer)
{"frequency": 392, "duration": 500}, # G5
{"frequency": 440, "duration": 500}, # A5
{"frequency": 494, "duration": 500} # B5
]
# 定义休止符(无声)
rest = {"frequency": 0, "duration": 500}
# 旋律序列,每个元素是一个索引到notes列表
melody = [0, 1, 2, 3, 2, 1, 0, 2, 3, 2, 1, 0, 0, 2, 2, 1, 0]
# 演奏旋律
for note_index in melody:
if note_index != -1:
note = notes[note_index]
winsound.Beep(note["frequency"], note["duration"])
else:
time.sleep(rest["duration"] / 1000.0) # 休息片刻
# 等待每个音符结束后再继续
time.sleep(0.5) # 等待半秒钟
–
发表回复