Preface:

Weekend to give you some interesting things, in the absence of the computer sound card, only use the computer motherboard on the buzzer, you can let the computer hum a song, it is still quite fun feeling ~ no more talk, let us happily begin ~

The development tools

**Python version: **3.6.4

Related modules:

PyQt5 module;

And some modules that come with Python.

Environment set up

Install Python and add it to the environment variables. PIP installs the required related modules.

Introduction of the principle

The principle is actually quite simple, mainly is to use Python to control the computer motherboard buzzer to emit sound at different frequencies to simulate the effect of human hum ~

Specifically, we have learned in primary school that sound is produced by the vibration of objects, which includes the following parts:

1.Pitch: The level of sound is determined by the vibration frequency of the vocal body. The higher the frequency, the higher the pitch.2.Loudness: The perceived volume of a sound by the human ear, which is related to the amplitude of the speaker. The greater the amplitude, the greater the loudness; The smaller the amplitude, the smaller the loudness;3.Timbre: The quality of sound of a speaker, determined by the characteristics of the speaker itself. It's an important marker for distinguishing sounds.Copy the code

This is a test, bother notes read in junior high school of fans, the examination to test, don’t only play mobile phones don’t work as soon as I get to the weekend ~ for the buzzer on the computer motherboard, timbre and loudness has basically can not changed, so we can only on the frequency, so that the buzzer hum ~ we want to hear song

Specifically, we can call this function to make the buzzer hum:

1 import ctypes
2 beep_player = ctypes.windll.kernel32
3 beep_player.Beep(freq, beats)
Copy the code

Freq stands for frequency and beats stands for beats (the duration of the current note). All right, now that someone’s confused here, hold on, let me give you an example of exactly what we should do.

First of all, let’s go to the Internet to find a simple music score of a favorite song. Here’s little Luck as an example:

The seven basic notes are the number 1234567, sung and written:

1 1: do
2 2: re
3 3: mi
4 4: fa
5 5: sol
6 6: la
7 7: si
Copy the code

Each basic note represents a frequency of the sound. When the “·” is marked above the basic note, it means that the note is raised an octave, which is called high, and vice versa, it means that the note is lowered an octave, which is called low (the case of double treble and double bass is not considered here) :

In general, we can assume that the high do is twice as frequent as the do, and four times as frequent as the low DO, and the other notes are similar. And according to the law of twelve-equal:

A musical principle in which an octave is divided into twelve equal parts, two for each equal part called a semitone, and is the primary method of tuning. The octave 3 refers to the doubling of frequency (that is, doubling frequency). The frequency of 4 octaves is divided into 12 equal parts, which is a series of 12 equal parts. 5 is the frequency of each note is the 12th root of 2 of the previous note: 6 is approximately 2^(1/12) = 1.06Copy the code

We just need to know the frequency of do to figure out the frequency of the other notes (for example, if do is 1, then re is 11.061.06). In general, the frequency of DO corresponds to the key sign in the simplified spectrum as follows:

1 'C': 523, 
2 'D': 587, 
3 'E': 659, 
4 'F': 698, 
5 'G': 784, 
6 'A': 880, 
7 'B': 988
Copy the code

Ok, so we’ve got Freq out of the way. Now let’s move on to Beats. In simplified music, the length of the sound is usually indicated by adding a “·” and a dash “-” :

1 1.Add a dash to the right of the base note to increase the duration of a quarter note (the length of the note *)2)
2 2.A short line is added below the base note to shorten the duration of the original note by half3 3.Adding · hour to the right of the note X increases the time value of the original note by half4 4.In simplified music, simple notes greater than a quarter note are usually left out of notation, and X- is used insteadCopy the code

Steal a picture to make it more intuitive:

OK, so we can easily determine the freq and beats of each note in the above musical notation, and then call the function to make the buzzer hum this note, so the hum of the notes is not equal to the buzzer hum

To make it easier for the program to determine the freq and beats for each note, let’s rewrite the notation like this:

That is, each note is composed of three elements:

[Basic note][bass/midrange/treble][length of note]Copy the code

Then write a function to parse it:

1 "' resolution ' ' '
2 def parse(self, filepath) :
3     song_info = open(filepath, 'r').read().replace('\n'.' ').split(', ')
4     tone = song_info[0]
5     song_info = song_info[1:]
6     return tone, song_info
Copy the code

And play according to the result of parsing ok:

1 "' play '
2 def play(self) :
3     filepath = self.musicfilepath_edit.text()
4     if not os.path.isfile(filepath):
5         return
6     tone, song_info = self.parse(filepath)
7     do = self.tone2freq_dict[tone]
8     re = int(do * self.tone_scale * self.tone_scale)
9     mi = int(re * self.tone_scale * self.tone_scale)
10    fa = int(mi * self.tone_scale * self.tone_scale)
11    sol = int(fa * self.tone_scale * self.tone_scale)
12    la = int(sol * self.tone_scale * self.tone_scale)
13    si = int(la * self.tone_scale * self.tone_scale)
14    notes = [0, do, re, mi, fa, sol, la, si]
15    for item in song_info:
16         if notes[int(item[0= =]]0:
17          time.sleep(self.beats / 1000)
18        else:
19 self.beep_player.Beep(int(notes[int(item[0])]*self.pitchs_dict[item[1]]), int(self.beats * float(item[2:)))Copy the code

That’s the end of this article, thank you for watching, follow me every day to share a series of Python gadgets, next article based on the Chinese name guess gender

To thank you readers, I’d like to share some of my recent programming favorites to give back to each and every one of you in the hope that they can help you.

Dry goods mainly include:

① Over 2000 Python ebooks (both mainstream and classic books should be available)

②Python Standard Library (Most Complete Chinese version)

③ project source code (forty or fifty interesting and classic practice projects and source code)

④Python basic introduction, crawler, Web development, big data analysis video (suitable for small white learning)

⑤ A Roadmap for Learning Python

⑥ Two days of Python crawler boot camp live access

All done~ Complete source code + dry plus Python novice learning exchange community: 594356095