这平安夜,我们来用python演奏一首铃儿响叮当吧

x33g5p2x  于2021-12-30 转载在 Python  
字(2.1k)|赞(0)|评价(0)|浏览(168)

《铃儿响叮当》是一首脍炙人口的经典圣诞歌曲,今晚平安夜我来用python奏起来——

用最原始的winsound库函数Beep()来演奏,用法如下:

>>> 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))

相关文章