# When I learned Python, I became not only a programmer, but also a musician!

Nowadays, many people try to create musical instruments by computer. The common method is to randomly generate a piece of music and score it according to the similarity of the existing music. I do the same? No, it's inefficient to do so. There are thousands of randomly generated songs and only one passed. The computing speed is also very low (supercomputer doesn't say it), and the songs screened out are not necessarily pleasant.

What method do I use? Today, we are going to learn a lot about the heinous music theory, as well as the calculation of the heinous music theory formula. Are you ready for pen and paper? Today, let me take you to the wonderful and complex music hall!

Leli Code:

Without much nonsense, let's talk about "interval":

Interval and its algorithm:

Looking at xuanhu is actually the simplest. It means the "distance" between two tones. Its basic unit is called degree. In mido, the basic unit is "semitone". Next, I use semitone count.

```1: Small second degree**
2: * large 2 degrees * * / minus 3 degrees
3: Small third degree * * / increase second degree
4: * big three degrees * * / minus four degrees
5: * pure 4 degrees * * / increase 3 degrees
6: * increase by four degrees * * / decrease by five degrees
7: * pure five degrees * * / minus six degrees
8: * small six degrees * * / increase five degrees
9: * big six degrees * * / minus seven degrees
10: * small 7 degrees * * / increase 6 degrees
11: * big seven**
(* * unit: * * * * halftone *)
```

Except for four and five degrees (not counting eight degrees), degrees are calculated by reducing and increasing, and there is no benchmark. However, general "magnanimity" is the best choice. If you don't believe it, you can try it. It's a big three or a small three. Except for the fourth degree, only the theoretical increase and decrease, not the increase of the third degree, only the pure fourth degree. So, just do 11 functions. For example, small second degree:

```def sd_two(low=None,high=None):         #Small second degree
if type(low) == str:
···#It's conversion. The previous code has been written
yin = []
if low and high == None:
high = low + 1
if high and low == None:
low = high - 1
yin.append(low)
yin.append(high)
return yin
```

Three chords:

The major triad structure is: major third + minor third. The minor triads are: minor + major. The increasing triad structure is: big third degree + big third degree, and the decreasing triad structure is: small third degree + small third degree. The most comfortable chord is the big triad, and the most disgusting chord is the minus triad.

Therefore, as long as we know one sound, we can find other sounds. I'll post the big triad code here:

```def b_three(geng=None,zhong=None,wu=None):
yin = []
if geng and zhong == None and wu == None:    #Know the root sounds
zhong = geng + 4
wu = zhong + 3
yin.append(geng)
yin.append(zhong)
yin.append(wu)
return yin
if zhong and geng == None and wu == None:      #Know the middle voice.
geng = zhong - 4
wu = zhong + 3
····#Ditto
if wu and geng == None and zhong == None:      #Know five tone
zhong = wu - 3
geng = zhong - 4
····#Ditto
```

# transposition

There are four types of triads, each of which has three "forms" called "transposition", which are: first transposition (in situ), second transposition (4 transposition), and third transposition (46 transposition)

Each transpose raises the lowest pitch (root) eight degrees (12 semitones). For your understanding, I drew a big three chord rotation bitmap (unit: semitone).

X stands for root (lowest), Y stands for three (middle), and Z stands for five (highest). It's much clearer. The other three are the same.

Don't use your brain, just change the code. (convert bit big 4 chord)

```·····  #Ahead of you
yin = []
if geng and zhong and wu:                        #If there are three
if zhong - geng == 4 and wu - zhong == 3:    #If the first turns to (TRIAD)
geng += 12
yin.append(zhong)
yin.append(wu)
yin.append(geng)
return yin
if zhong - geng == 5 and wu - zhong == 4:    #If the third is (46 chord)
wu -= 12
yin.append(wu)
yin.append(geng)
yin.append(zhong)
return yin
if zhong - geng == 3 and wu - zhong == 5:
return True
```

But there are so many kinds that it took me 10 days to finish

With chord (interval):

WOW! You can find chord sum and interval! Applause! Use your brain, on the basis of myin, change the following, and chord the tune:

```    def myin(fu,pai,time=120,du=None,chord=None,high=64,note="low",yue=2):
#Harmony Edition
pig = int(beat(time))    #int rounding, time requires integer
for i in range(len(pai)):
if type(pai[i]) == list:
···   #Last article has, take a look
else:
if chord == None and du == None:
···  #Last article has, take a look
else:
#chord
if chord == "dasan":            #Major chord
if note == "low":
fu[i] = b_three(fu[i])
elif note == "zhong":
fu[i] = b_three(zhong=fu[i])
elif note == "wu":
fu[i] = b_three(wu=fu[i])
····· #A thousand lines are omitted here

#Interval (degree)
if du == "xiaoer":                   #Small second degree
if note == "low":
fu[i] = sd_two(fu[i])
if note == "high":
fu[i] = sd_two(high=fu[i])
····#A thousand lines are omitted here

#loop
for x in range(len(fu[i])):
yin(fu[i][x],pai[i]*pig,liang=high,unit=tra[x],qi=yue)
```

There are too many "intervals" and "chords", which can not be fully pasted

To celebrate, I used this function to match the chord and interval for Mary has a little goat. You are the only one who didn't expect it. I can't do it without it

Baroque music algorithm and Implementation:

There are many different kinds of music in the Baroque period, such as two, three, four, binge, Fugue Countless, different kinds of music have different forms. Today we have achieved the two-part. There are many forms of the duet, single open, double rise, thickened Let's choose a simple one, "single open".

This is the first part of Bach's two creative songs. Before you talk about it, post a few pieces of code:

Inverted reflection in water:

For example, the reflection of [3,4,5] is [3,2,1]. This form was all in Baroque time, implementing functions:

```def dao(yin):                 #Computed reflection
a = yin[0] * 2
daoyin = []
for i in yin:
b = a - i
daoyin.append(b)
return daoyin
```

Multiply the first tone by 2 to subtract the next number to get the array (list)

Is the pitch of the reflection unchanged? It has to change. Using the brain and brain, we can get the answer:

```def getdao(xuanlu,base):
for i in range(len(xuanlu)):
if type(xuanlu[i]) == str:
xuanlu[i] = num(xuanlu[i])
if type(base) == str:
base = num(base)
xuanlu = dao(xuanlu)
high = base - xuanlu[0]
for i in range(len(xuanlu)):
xuanlu[i] += high
return xuanlu
```

With the base pitch, we get the xuanlu reflection.

Split chord, time:

In the Baroque period, the theme (Theme) is always separated and divided into themes. But you don't know what kind of rhythm the user will type in. If you use your brain again, you can separate the melody according to the different rhythms.

```    def getlu(first,second,ind):
s = 0
c = 0
for i in range(1,len(second)):
if second[i] != second[s]:
c += 1
if c == ind:
return first[s:i]
else:
s = i
return first[s:]
```

Similarly, split time:

```    def gettime(paizi,ind):
s = 0
c = 0
for i in range(1,len(paizi)):
if paizi[i] != paizi[s]:
c += 1
if c == ind:
return paizi[s:i]
else:
s = i
return paizi[s:]
```

So you can get any piece of code and time.

Music implementation of computer calculation:

Xiaobai is angry, and the algorithm is not yet told! Don't worry, algorithm is coming? The most classic BWV772 example:

All rights reserved! We use the blue box to select the theme, the green box to select the subtitle and match the melody. ****Use yellow for reflection. Let's sum it up in mathematical terms: (I drew it)

There's a special one. All songs should be "solved" and "solved" is more complex, and those who are interested can be searched. I have made a personalized solution for you to use.

```lastyin = [b_three(".do"),b_three(".mi"),b_three(".so"),b_three("do"),b_three("mi"),b_three("so"),'so','mi','do',"do","si"]
lastpai = [xxxx,xxxx,xxxx,xxxx,xxxx,xxxx,0.5,0.5,1.5,5]
myin(lastyin,lastpai,track=track4)
myin(["do"],[10],high=120)
```

This solution is strictly prohibited from plagiarism. To this point, I believe that as long as IQ > 100, it can be written out. However, many of the little white still can't write. In order to take care of Xiaobai, I wanted to paste it here, but it was too long to put.

epilogue

Now you can use the computer to calculate the opening of the Baroque period's two pieces, as long as you have a good melody, you can make a good piece. But what about the other kinds? You can buy a Bach collection of creative songs, a total of 30 pieces, each of which is very classic. You can analyze and write code one by one.

Tags: Python

Posted on Mon, 06 Apr 2020 09:56:06 -0400 by dukeu03