文章目录

  • 一、背景与需求
  • 二、必备知识
    • 2.1 Python生成音乐的原理
    • 2.2 十二平均律
    • 2.3 简单乐理知识
  • 三、实现
    • 3.1 对琴谱进行编码
    • 3.2 Music类
    • 3.3 Staff类
    • 3.4 Converter类
  • 四、项目代码
  • 五、不足与展望

一、背景与需求

前一段时间在B站看到一个视频,up主用matlab演奏出了《小星星》这首歌1。当时我就在想,python能不能做到这一点呢?《小星星》的谱子太简单了,我决定尝试演奏《国际歌》

二、必备知识

2.1 Python生成音乐的原理

想要生成一段音乐,首先要了解声音产生的原理:

声音是由物体振动产生的声波。是通过介质(空气或固体、液体)传播并能被人或动物听觉器官所感知的波动现象。最初发出振动(震动)的物体叫声源。声音以波的形式振动(震动)传播。声音是声波通过任何介质传播形成的运动。
声音是一种波。可以被人耳识别的声(频率在20 Hz~20000 Hz之间),我们称之为声音。

想要用Python生成一段音乐,道理其实非常简单。只要我们想办法生成这段音乐的波形数据,再将其写入文件保存,就可以播放了。

怎样生成一段声波呢?这可以通过Numpy库实现。

下面的代码用于生成一段正弦波并可视化:

import numpy as np
import matplotlib.pyplot as plt# 生成一条正弦波
x = np.linspace(0, 2*np.pi, 8192)
y = np.sin(x)
#可视化
plt.plot(x,y)
plt.show()

可视化结果如图所示:

当然,如果我们把这样一段正弦波写入文件并播放,是不会听到任何声音的。这是因为人耳可以听到的声音的频率范围在20到2万赫兹(Hz)之间,而上面这条正弦波的频率为1Hz,属于人耳听不到的次声波。


接下来这段代码用于生成一条频率为440Hz的正弦波并可视化:

import numpy as np
import matplotlib.pyplot as pltfrequency = 440
x = np.linspace(0, 2*np.pi, 8192)
y = np.sin(frequency * x)
plt.plot(x,y)
plt.show()

结果如下:

由于频率太大,生成的波周期太短,水平方向挤在了一起。我们不妨将图片放大看一看:

如果将这条正弦曲线写入文件并播放,我们就可以听到声音了。这条440Hz的波对应的正是中央A2,也就是我们常说的la。

2.2 十二平均律

十二平均律3
(英语:Equal temperament),又称十二等程律,音乐律式的一种,也是当今最主流的律式。将一个八度平均分成十二等份,每等分称为半音,音高八度音指的是频率乘上二倍。八度音的频率分为十二等分,即是分为十二项的等比数列,也就是每个音的频率为前一个音的2的12次方根:


根据此表,我们可以计算出各个音符所对应的频率,从而生成对应的波。

2.3 简单乐理知识

想要用Python演奏国际歌,首先要对琴谱进行编码,将五线谱输入计算机中。这要求我们必须对乐理知识具备一定的了解。这里不作详细介绍,可参考 乐理知识以及musicXml属性介绍 这篇文章。

三、实现

3.1 对琴谱进行编码

我手里现有的国际歌琴谱是五线谱形式的。

然而,计算机可不识谱。为了让它能理解琴谱的内容,我们必须首先对琴谱进行编码。这里我自行制定了一种编码格式,并手工对其进行了编码:

其中每个section表示一个小节,每个音符用一个3维向量表示。如[0,1,3]表示一个持续3拍的中央C的do.

3.2 Music类

Music类用来实例化一首歌。其包含以下成员:

主要变量

  • name : 一个字符串,歌曲名称
  • staff : 一个Staff对象,歌曲的五线谱。
  • wave : np.array()数组,五线谱对应的波形。
  • Fs : 采样率
  • converter : 一个Converter对象,用来实现五线谱到波形的转换。

主要函数

  • load_staff(self,file_name) : 读取编码后的五线谱。
  • update_music(self) : 根据读取的五线谱更新波形。
  • save_music(self,file_name,file_type="wav") : 保存音频文件。
  • draw_wave(self) : 画出波形图。
class Music():def __init__(self, name=""):"""Init an instance of MyMusic.Parameters----------name : str, [optional]Name of the music. Must be str."""#Judge the type of input.assert name is None or isinstance(name, str)self.__name = nameself.__staff = Noneself.__wave = np.array([])self.__Fs = 8192self.__converter = Converter(self.__Fs)def load_staff(self,file_name):"""Load the staff from a file.Parameters----------file_name : strThe file to read from.Returns-------state : boolWhether loaded the data successfully."""#Judge the input.assert isinstance(file_name, str), "file_name must be a string"assert len(file_name.split(".")) == 2, "Input error. \neg.'start.txt'"self.__staff = Staff(file_name)self.update_music()def save_staff(self,file_name):"""Save the staff to a file.Parameters----------file_name : strThe file to save to.Returns-------state: boolWhether saved the data successfully."""def update_music(self):"""Update the music(wave) by self.__staff."""self.__wave = self.__converter.gen_music(self.__staff)def save_music(self,file_name,file_type="wav"):"""Save the music as an audio.Parameters----------file_name : strThe file to save to.file_type : strType of the file to save to. Defaults to 'wav'and it means save the audio as "{file_name}.wav".Returns-------state : boolWhether successfully saved the music as an audio."""path = file_name.split(".")[0]+"."+file_typesf.write(path, self.__wave, self.__Fs, 'PCM_24')def play(self):"""Play the music."""def draw_wave(self):"""Draw the waveform according to self.__wave."""n = len(self.__wave)     # Number of samples.t = n/self.__Fs          # Range of t is [0,t]x = np.linspace(0, t, n)plt.plot(x,self.__wave)  # Draw the wave.plt.show()

3.3 Staff类

Staff类用于表示琴谱

主要变量

  • rythm : 琴谱的节奏。
  • loop : 储存琴谱循环信息。

主要函数

  • read(self) : 读取编码后的五线谱。
class Staff():def __init__(self, file_name):"""Init an instance of a Staff.Parameters----------f_name : strThe name of the file.f_type : strThe type of the file."""self.__sections = []self.__name ,self.__type = file_name.split(".")self.__text = ""self.__rythm = 60self.__loop = Noneself.__supported_type = {"txt"}            # The type of file supported.self.read()    # Read file.def read(self):"""Init the staff from a file."""assert self.__type in self.__supported_type, "Sorry, this type of file is not supported."if self.__type == "txt":self.read_from_txt()def read_from_txt(self):"""Load the staff from a txt file.Parameters----------file_name : str ("xxx.txt")The full name of the file."""file_name = self.__name + "." + self.__typewith open(file_name, "r") as file:self.__text = file.read()re_rythm = re.compile("rythm=([0-9]*)",re.S)re_loop = re.compile("loop=(.*?\))",re.S)re_section = re.compile("(<section.*?>.*?</section>)",re.S)re_section_att = re.compile("<section (.*?)>(.*)</section>",re.S)self.__rythm = int(re_rythm.findall(self.__text)[0])  # Find the rythm.self.__loop = eval(re_loop.findall(self.__text)[0])sections = re_section.findall(self.__text)       # Find all sections.for section in sections:# Create a temp dict to save the information of this section.dict_att = {}# Find the attributions and the notes of this section.match = re_section_att.findall(section)# Add every attribute to `dict_att`.attributes = match[0][0].split()for att in attributes:key, value = att.split("=")dict_att[key] = value# Create a list `notes` and add every note to this list.notes_temp = match[0][1].split("\n")notes = []for i in range(len(notes_temp)):note = notes_temp[i].strip(" ")note = note.strip("\t")if note:notes.append(note)# Create a dict to save the information of this section, and add it to `self.__section`.self.__sections.append({"attribute":dict_att, "notes":notes})# print(self.__sections)@propertydef sections(self):return self.__sections@propertydef rythm(self):return self.__rythm@propertydef loop(self):return self.__loop

3.4 Converter类

Converter类用于实现五线谱到波形的转换。

主要变量

  • Fs : 采样率。

主要函数

  • read(self) : 读取编码后的五线谱。
  • get_frequency(self,major,scale) :计算给定音符的频率。
  • get_wave(self,major,scale,rythm=1) : 生成给定音符的波形。
  • gen_music(self,staff) : 拼接各音符的波形,生成整首音乐的波形。
class Converter():def __init__(self, Fs=8192):"""Init an instance of Converter.Parameters----------Fs : int [optional]The sampling rate."""self.__Fs = Fsdef get_frequency(self,major,scale):"""Calculate the Frequency.Parameters----------major : intThe major. For example, when it takes 0, it means C major.scale : int, range[-1,12]The scale. -1 means a rest, and 1 means "do", 12 means "si".Returns-------frequency : floatThe Frequncy calculated by the major and scale."""frequency = 440*(2**major)frequency = frequency*2**((scale-1)/12)return frequencydef get_wave(self,major,scale,rythm=1):"""Generate the wave of a note.Parameter---------major : intThe major. For example, when it takes 3, it means C major.scale : int, range[-1,12]The scale. -1 means a rest, and 1 means "do", 12 means "si".rythm : intThe rythm of the note. When it takes 1.5, int means 1.5 unit-time per beat.Returns-------y : np.arrayThe wave generated."""Pi = np.pix = np.linspace(0, 2*Pi*rythm, int(self.__Fs*rythm), endpoint=False) # time variable# When scale==-1, it means a rest.if scale == -1:y = x*0else:frequency = self.get_frequency(major, scale)y = np.sin(frequency*x)*(1-x/(rythm*2*Pi))return ydef gen_music(self,staff):"""Play a piece of music based on section.Parameters----------staff : class Staff.Returns-------wave : np.arrayThe wave of the staff."""sections = staff.sectionstime = 60/staff.rythmloop_start, loop_end, loop_times, loop_sub = staff.loopwave = np.array([])section_wave_ls = []for section in sections:notes = section["notes"]wave_list = []for line_str in notes:line = [eval(note) for note in line_str.split()]line_wave = np.array([])for note in line:major, scale, rythm = noterythm *= timey = self.get_wave(major, scale, rythm)line_wave = np.concatenate((line_wave,y),axis=0)wave_list.append(line_wave)length = min([len(line_wave) for line_wave in wave_list])section_wave = wave_list[0][:length]for i in range(1,len(wave_list)):section_wave += wave_list[i][:length]# wave = np.concatenate((wave,section_wave),axis=0)section_wave_ls.append(section_wave)temp = [w for w in section_wave_ls[:loop_start-1]]for i in range(loop_times):for w in section_wave_ls[loop_start-1:loop_end]:temp.append(w)if loop_sub:section_wave_ls = temp[:-1] + [w for w in section_wave_ls[loop_end:]]else:section_wave_ls = temp + [w for w in section_wave_ls[loop_end:]]for w in section_wave_ls:wave = np.concatenate((wave,w), axis=0)return wave

四、项目代码

完整代码已经上传至github,传送门: Python演奏国际歌

五、不足与展望

  1. 对琴谱的编码方式有待优化。我采用的方法太过粗糙,只提取了原谱最关键的少量信息。此外,由于编码规则是我自己指定的,这种编码也缺乏通用性。接下来可以尝试MusicXML4编码。
  2. 琴谱编码需要人工进行,费时费力,后期可以采用图像识别技术自动识别并编码琴谱。
  3. 后期可以再写一个UI界面,提高用户体验度。

  1. 【Matlab番外篇】怎样用Matlab生成一段音乐 ↩︎

  2. 维基百科:A(音名) ↩︎

  3. 维基百科:十二平均律 ↩︎

  4. Songs and Schemas ↩︎

用Python演奏《国际歌》相关推荐

  1. 用Python演奏《太阳照常升起》

    用Python演奏<太阳照常升起> 一.准备工作 1.1 找谱子,看谱子 1.2 确定频率 二.创建载有一个音符的正弦信号 2.1 创建正弦信号并采样 2.2 包络 2.2.1 一次函数, ...

  2. python演奏音乐

    今天早晨闲来无事逛b站,看到有大佬用c++演奏了很多歌曲,然后心血来潮,就想着用python做一个,无奈,自己早年间学过的吉他的乐理知识早就忘得一干二净了,没办法,开展cv大法,找到了一首大佬编写的l ...

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

    <铃儿响叮当>是一首脍炙人口的经典圣诞歌曲,今晚平安夜我来用python奏起来-- 用最原始的winsound库函数Beep()来演奏,用法如下: >>> import ...

  4. 牛逼了!菜鸟也能用Python演奏一段钢琴曲

    小编一直有着一个钢琴弹奏的梦想,但是苦于没有这样的基础,所以很难在实际生活中弹奏出一曲美妙的钢琴曲,不过,为了实现自己的钢琴梦,我决定用python来帮我实现. 今天,小编就带领大家利用python来 ...

  5. python 抽奖 配音乐,用Python演奏音乐

    背景 笔者什么乐器也不会,乐理知识也只有中小学音乐课学的一点点.不过借助Python,调用编曲家常用的MIDI程序库,也能弹奏出一些简单的音乐,以下是笔者的一些心得. 准备 安装mingus 首先是安 ...

  6. 用python演奏歌曲

    一.准备 电脑一台.python. 首先使用pip安装winsound: pip install winsound 接下来,就开始我们的正文.(当然,这篇文章正文会很短) 二.正文 此处,我以< ...

  7. python 背景音乐程序代码_用Python演奏音乐

    背景 笔者什么乐器也不会,乐理知识也只有中小学音乐课学的一点点.不过借助Python,调用编曲家常用的MIDI程序库,也能弹奏出一些简单的音乐,以下是笔者的一些心得. 准备 安装mingus 首先是安 ...

  8. python123用户登录c_【视频】[2019.1.9]用python演奏键盘钢琴谱(最初版的tantan离线客户端)【弹弹123吧】_百度贴吧...

    该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 给没当年没见识过这谱的老哥们看看... 应该是那个年代最好的一张键盘钢琴谱了,音符时值准确,对原曲高度还原 除了不好弹,真的是挑不出来问题了 (AEJ)- ...

  9. 最简单方式利用Python演奏字母歌

    winsound.Beep(frequency , duration) 可以发声的,参数frequency 为频率, 参数duration为持续时间,单位是毫秒.音名与频率关系如下: 此为字母歌全曲: ...

最新文章

  1. 网站响应慢的原因分析
  2. php使用referer,php中HTTP_REFERER函数用法实例
  3. idea 在tomcat中部署的时候 莫名其妙的错误
  4. 2018 blockchain innovation final round of the chain valley
  5. layui.table.render设置自定义高度高度
  6. 如何高效学习 Kubernetes 知识图谱?
  7. 通用权限管理系统组件 (GPM - General Permissions Manager) - 支持请求
  8. PKU 学生反馈 3
  9. 三次握手和四次挥手图解_详解 TCP 连接的“三次握手”与“四次挥手”
  10. 汇编:汇编语言实现冒泡排序(loop指令实现)
  11. 为Visual Studio更换皮肤和背景图
  12. Elasticsearch入门四:Elasticsearch-搜索、过滤、聚合
  13. 联想linux无线网卡驱动,联想E431笔记本CentOS系统安装无线网卡驱动
  14. Center OS 7
  15. 计算机桌面全部内容自定义,电脑win10如何恢复自定义桌面图标排列的方法
  16. 关闭app服务器系统,ios12系统服务哪些关掉
  17. multism中ui和uo应该怎么表示_Multisim在模拟与数字电子技术中的应用(最终版)最新版...
  18. Unmatched braces in the pattern
  19. Jsp(二)——简单的Jsp程序
  20. ESP8266 WIFI 模块串口调试过程-实现通过互联网实现数据远程传输(结尾含驱动代码链接)

热门文章

  1. ERP容灾备份维护工作有哪些?服务器容灾备份
  2. Cadence 绘制PCB添加泪滴与差分布线与铺铜简单介绍
  3. 自助售货机(附源码)
  4. 英国留学生论文Synthesis Essay写作技巧
  5. Java 创建类的四种方式
  6. 【Micropython】肝货~使用USB_VCP通过USB串口与树莓派或PC端通信
  7. git push 报错:fatal: unable to access ‘https://github.com/...‘......
  8. Illustrator CS5初学者必读(10)——实时描摹图像
  9. 6个免费PPT模板网站
  10. 大数据平台框架、组件以及处理流程详解