Try to output audio with M5STACK

Write down what you learned anew when outputting music with a microcomputer

In realizing the technology, I referred to the following article of "Chikuwa-san". http://nn-hokuson.hatenablog.com/entry/2017/09/01/092945

What is sound

For the time being, I knew that sound was a composite of sine waves of various frequencies. I started by checking it in Python.

sumsound.PNG

Somehow, it looks like an audio signal.

The realized code is shown below.


import numpy as np
import matplotlib.pyplot as plt

#frequency[Hz]
f1 = 100
f2 = 500
f3 = 1000
f4 = 10000
f = [f1,f2,f3,f4]

#amplitude[V]
A1 = 5
A2 = 3
A3 = 1
A4 = 0.1
A = [A1,A2,A3,A4]

#time
t = np.arange(0,0.01,0.00001)

#function
fig = plt.figure()
#Add Axes
ax = fig.add_subplot(111)

y = []

for i in range(4):
    y.append(A[i]*np.sin(2*np.pi*f[i]*t))
    plt.plot(t,y[i])
    #Draw execution

#Axis label settings
ax.set_xlabel("time[s]", size = 14, weight = "light")
ax.set_ylabel("Volatage[V]", size = 14, weight = "light")
plt.show()

Wave composition is realized by the sum of sine waves of each frequency

plt.plot(t,sum(y))

Audio output

If you vibrate the air with some kind of signal, it should be recognized as some kind of sound.

We use a speaker as a method to vibrate the air. (It seems that this speaker converts electrical signals into vibrations)

A PWM signal is generally used to give an electric signal to a speaker.

スピーカー.PNG

** Image of composite wave applied as input to speaker **

Implementation flow

This time, we aimed to output MP3 files as audio. I used M5STACK as a microcomputer for voice control.

** 1. Convert MP3 file format ** In doing this work, I referred to the following site. http://nn-hokuson.hatenablog.com/entry/2017/09/01/092945

I prepared the MP3 file I want to play and converted it on the next site. https://audacity.softonic.jp/

Here, you can change the file format of the original data (prepared MP3 file) and It is possible to determine an arbitrary sampling frequency and create data with a lighter capacity than the original data. Since the memory capacity is limited when mounting on a microcomputer such as M5STACK It is necessary to consult with the playback time and sampling frequency.

** 2. Convert to text file **

Taking sampled music as an example Save in the following save format save.PNG

Then the file name .raw will be generated. Put it on a linux terminal

xxd -i file name.raw

(Tentatively name the file sound.raw)

unsigned char sound_raw[] ={
//The result of sampling music
}

unsigned int  sound_raw_len = xx

It is output with. Turn this result into an Arduino script By copying and pasting, the audio file is stored in the memory of Arduino. You can now save it.

** 3. Implemented in M5STACK **

In M5STACK, it could be realized with the following code.

#include <M5Stack.h>
unsigned char sound_raw[] ={
//Input the result of sampling music
}

unsigned int  sound_raw_len = xx; //Number of samples
unsigned char pwm;

void play() {
  for (int i = 0; i < sound_raw_len; i++) {
    pwm = sound_raw[i];
    dacWrite(25, pwm); //In M5STACK, 25PIN is connected to the speaker.
    delayMicroseconds(xx);// xx:Depends on sampling frequency
  }
   dacWrite(25, 0); //speakeroff
} 

void setup() {

  M5.begin();

  delay(500);

  M5.Lcd.fillScreen(WHITE);
}

void loop()
{
   if(M5.BtnA.wasPressed())//Sound when button A is pressed
    {
        play();
    }

    M5.update();
}

** Supplement ** I ran this code on an Arduino Nano and it didn't work. Simply put, it was how to define the carrier frequency and array of pwm. I hope I can write about this in another article.

Recommended Posts

Try to output audio with M5STACK
Try to factorial with recursion
Try Python output with Haxe 3.2
Output to syslog with Loguru
Try to operate Facebook with Python
Output to csv file with Python
Try audio signal processing with librosa-Beginner
Output cell to file with Colaboratory
Try to reproduce color film with Python
Output Python log to console with GAE
Try to predict cherry blossoms with xgboost
Quickly try to visualize datasets with pandas
First YDK to try with Cisco IOS-XE
Try to generate an image with aliasing
Try to make your own AWS-SDK with bash
Try to solve the fizzbuzz problem with Keras
3.14 π day, so try to output in Python
Try to aggregate doujin music data with pandas
Try to solve the man-machine chart with Python
Try to extract Azure document DB document with pydocumentdb
Try to draw a life curve with python
Try to communicate with EV3 and PC! (MQTT)
How to try the friends-of-friends algorithm with pyfof
Try to make a "cryptanalysis" cipher with Python
I tried to output LLVM IR with Python
Try to automatically generate Python documents with Sphinx
Try to make a dihedral group with Python
Output test function docstring to report with pytest-html
Try to make client FTP fastest with Pythonista
Try to detect fish with python + OpenCV2.4 (unfinished)
Try scraping with Python.
Procedure to load MNIST with python and output to png
Try to solve the programming challenge book with python3
[First API] Try to get Qiita articles with Python
Output PDF with Django
Markdown output with Django
Convert 202003 to 2020-03 with pandas
Try to make a command standby tool with python
Start M5Stack with UIFlow
Try to dynamically create a Checkbutton with Python's Tkinter
Try to visualize the room with Raspberry Pi, part 1
Try to solve the internship assignment problem with Python
Try to predict forex (FX) with non-deep machine learning
Try to make RESTful API with MVC using Flask 1.0.2
Schema-driven development with Responder: Try to display Swagger UI
[GCP] Try a sample to authenticate users with Firebase
Output PDF with WeasyPrint
How to output CSV of multi-line header with pandas
Python audio input / output
Try to get the contents of Word with Golang
Try to implement yolact
[Neo4J] ④ Try to handle the graph structure with Cypher
Try SNN with BindsNET
A sample to try Factorization Machines quickly with fastFM
Try to tamper with requests from iphone with Burp Suite
[Python-pptx] Output PowerPoint font information to csv with python
Try to automate pdf format report creation with Python
Try to create a waveform (audio spectrum) that moves according to the sound with python
Try regression with TensorFlow
Try to specify the axis with PyTorch's Softmax function
Try to build a deep learning / neural network with scratch