Python“制作”midi音乐“两只老虎”

2017-02-03 董付国 Python小屋 Python小屋

从网上找了很多谱子,可惜没有音乐细胞看不太懂,根据自己的理解改了好几遍,还是听不出来“两只老虎”的感觉,于是在标题上加了双引号。这样的话就只能了解本文思路了,算是抛砖引玉吧,重点是Python标准库winsound的Beep()函数可以发出37到32767赫兹之间频率的声音,其第二个参数为发声时长。


from winsound import Beep
from random import randint


#列表中偶数位置是频率,奇数位置是时长
freqs = ['0FB', '08', '0F9', '08', '0FC', '08', '066', '08', '0FC', '08', '0C7', '08', '0FB', '08', '0F9', '08',
         '0FB', '08', '0F9', '08', '0FC', '08', '066', '08', '0FC', '08', '0C7', '08', '0FB', '08', '0F9', '08',
         '0FC', '08', '0C7', '08', '0FC', '08', '0F3', '08', '0FD', '10', '0A4', '10',
         '0FC', '08', '0C7', '08', '0FC', '08', '0F3', '08', '0FD', '08', '04A', '08',
         '0FD', '04', '04A', '04', '0FD', '04', '095', '04', '0FD', '04', '04A', '04', '0FC', '04', '0F3', '04', '0FC', '08', '0C7', '08', '0FB', '08', '0F9', '08',
         '0FD', '04', '04A', '04', '0FD', '04', '095', '04', '0FD', '08', '4A',  '04', '0FC', '04', '0FC', '04', '0FC', '08', '0C7', '08', '0FB', '08', '0F9', '08',
         '0FC', '08', '066', '08', '0FA', '08', '093', '08', '0FB', '08', '0F9', '08', '0FC', '04', '66', '04', '0FA', '08', '093', '08', '0FB', '08', '0F9', '08',
         '0FF', '10', '0FF', '10'
]

for i in range(0, len(freqs), 2):
    freq, d = map(lambda x: int(x, 16), freqs[i:i+2])
    d = d * 30
    #以指定的时长播放特定频率的声音
    Beep(freq, d)