python叮咚(我们来用python演奏一首铃儿响叮当吧)
《铃儿响叮当》是一首脍炙人口的经典圣诞歌曲,今晚平安夜我来用python奏起来——
用最原始的winsound库函数Beep()来演奏,用法如下:
私信小编01即可获取大量Python学习资源
>>> import winsound
>>> help(winsound.Beep)
Help on built-in function Beep in module winsound:
Beep(frequency, duration)
A wrapper around the Windows Beep API.
frequency
Frequency of the sound in hertz.
Must be in the range 37 through 32,767.
duration
How long the sound should play, in milliseconds.
先找来do,re,mi等音符的频率表:
'''休止符及do re mi等对应的频率数'''
Tone = [[0,0,0,0,0,0],
[523,262,1046,554,277,1109],
[578,294,1175,622,311,1245],
[659,330,1318,659,330,1318],
[698,349,1493,740,370,1556],
[784,392,1568,831,415,1661],
[880,440,1760,932,466,1865],
[988,494,1976,988,494,1976]]
然后找一份最简版的《铃儿响叮当》简谱:
照此编制乐谱,自定义一个规则,每个音符为一个元组:(音符,音长,音阶)
简谱的每个音符用一个三元素元组表示,其中:
第一个元素 1~7 对应do re mi fa so la si 0=休止符
第二个元素 1拍=1;半拍=0.5 四分之一拍=0.25 以此类推
第三个元素一般就为0,低音=1 高音=2 对应的半阶音=3 4 5
这样定义方便乐谱的编制,代码如下:
from winsound import Beep
'''休止符及do re mi等对应的频率数'''
Tone = [[0,0,0,0,0,0],
[523,262,1046,554,277,1109],
[578,294,1175,622,311,1245],
[659,330,1318,659,330,1318],
[698,349,1493,740,370,1556],
[784,392,1568,831,415,1661],
[880,440,1760,932,466,1865],
[988,494,1976,988,494,1976]]
'''乐谱编制'''
t1 = '33333335123'
t2 = '444333322125'
t3 = t1
t4 = '4444433355421'
'''对应的音长'''
p1 = [1,1,2,1,1,2,1,1,1.5,0.5,4]
p2 = [1,1,2,1,1,2,1,1,1,1,2,2]
p3 = p1
p4 = [1,1,1.5,0.5,1,1,1,1,1,1,1,1,4]
t = list(map(int,t1 t2 t1 t4))
p = p1 p2 p1 p4
Tune = list(zip(t,p,[0]*len(t))) #配曲音符都为中音,音阶值全为0
'''演奏乐谱'''
Pai = 360 #一拍的毫秒数,可以调节
for t in Tune:
Beep(Tone[t[0]][t[2]],int(t[1]*Pai))
按下运行键,动听的演奏开始了:
“叮叮当,叮叮当, 铃儿响叮当.
我们滑雪多快乐,我们坐在雪橇上...”
祝大家平安夜快乐,全家平安幸福!
为方便初学者理解怎样把简谱转换成Tune列表,另附一首《两只老虎》:
from winsound import Beep
'''休止符及do re mi等对应的频率数'''
Tone = [[0,0,0,0,0,0],
[523,262,1046,554,277,1109],
[578,294,1175,622,311,1245],
[659,330,1318,659,330,1318],
[698,349,1493,740,370,1556],
[784,392,1568,831,415,1661],
[880,440,1760,932,466,1865],
[988,494,1976,988,494,1976]]
'''按照简谱编制乐谱'''
t = [None]*4
t[0] = [(1,1,0),(2,1,0),(3,1,0),(1,1,0)] #两只老虎
t[1] = [(3,1,0),(4,1,0),(5,2,0)] #跑得快
t[2] = [(5,0.75,0),(6,0.25,0),(5,0.75,0),
(4,0.25,0),(3,1,0),(1,1,0)] #一只没眼睛|尾巴
t[3]= [(1,1,0),(5,1,1),(1,2,0)] #真奇怪
'''导入乐谱'''
Tune = []
for i in range(4):
Tune.extend(t[i]*2)
'''演奏乐谱'''
Pai = 360 #一拍的毫秒数,可以调节
for t in Tune*2:
Beep(Tone[t[0]][t[2]],int(t[1]*Pai))
免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com