[Raspi4; Introduction to Sound] Stable recording of sound input with python ♪

I've covered sound input several times, but this time I've been able to input and output stably with Rasipi4, so I decided to summarize it. The important thing is as shown in Reference 1. Last year, I was playing with something like Reference 2. I'm thinking of doing something a little different this year. 【reference】 1.PyAudio Input overflowed 2. [Scipy] I played with FFT, STFT and wavelet transform ♬ ~ ⑦ Real-time spectrogram; Speed up

The point

In other words, if you write the following magic when reading, overflow will not occur and you can record endlessly.

# -*- coding:utf-8 -*-
import pyaudio
import matplotlib.pyplot as plt
import numpy as np
import wave
import struct

Save the read sound as a wav file with the following function.

def savewav(sig,sk):
    RATE = 44100 #Sampling frequency
    #Sine wave-Convert from 32768 to 32767 integer value(to signed 16bit pcm)
    swav = [(int(32767*x)) for x in sig] #32767
    #Binary
    binwave = struct.pack("h" * len(swav), *swav)
    #Export sine wave as wav file
    w = wave.Wave_write("./wine/"+str(sk)+".wav")
    params = (1, 2, RATE, len(binwave), 'NONE', 'not compressed')
    w.setparams(params)
    w.writeframes(binwave)
    w.close()

Sound input / output is set to True. Since voice (sentence) is input, record a long time (102400/44100 = 2.3sec).

RATE=44100
p=pyaudio.PyAudio()
N=100
CHUNK=1024*N
stream=p.open(format = pyaudio.paInt16,
        channels = 1,
        rate = RATE,
        frames_per_buffer = CHUNK,
        input = True,
        output = True) #Set input and output to True at the same time

And finally, continuous recording has started. Exception_on_overflow is set to False. sig is divided by 32768.

sk=0
while stream.is_active():
    input = stream.read(CHUNK, exception_on_overflow = False)
    print(len(input))
    sig =[]
    sig = np.frombuffer(input, dtype="int16") / 32768
    savewav(sig,sk)
    fig, (ax1,ax2) = plt.subplots(2,1,figsize=(1.6180 * 4, 4*2))
    lns1=ax1.plot(sig[0:1024] ,".-",color="red")
    ax1.set_xticks(np.linspace(0, 882, 3))
    ax1.set_ylabel("sig0")
    ax1.set_title('short plot')
    lns2=ax2.plot(sig[0:CHUNK], "-",color="blue")
    ax2.set_xticks(np.linspace(0, 44100*2, 5))
    ax2.set_ylabel("sig1")
    ax2.set_title('long plot')
    ax1.grid()
    ax2.grid()
    plt.pause(0.5)
    plt.savefig("./wine/sound_{}.png ".format(sk))
    plt.close()
    sk+=1
    output = stream.write(input)

Ah, uh, eh. .. Continuous measurement result of x-axis memory; 44100 = 1sec sound_1.png sound_4.png

Summary

・ Continuous measurement is now possible

・ I want to link R-python with sound.

Recommended Posts

[Raspi4; Introduction to Sound] Stable recording of sound input with python ♪
[Chapter 5] Introduction to Python with 100 knocks of language processing
[Chapter 3] Introduction to Python with 100 knocks of language processing
[Chapter 2] Introduction to Python with 100 knocks of language processing
[Chapter 4] Introduction to Python with 100 knocks of language processing
IPynb scoring system made with TA of Introduction to Programming (Python)
From the introduction of JUMAN ++ to morphological analysis of Japanese with Python
Introduction to Python Image Inflating Image inflating with ImageDataGenerator
Easy introduction of speech recognition with Python
[Introduction to Udemy Python3 + Application] 41. Input function
[Introduction to Python] Let's use foreach with Python
[Python] Introduction to CNN with Pytorch MNIST
[Introduction to Data Scientists] Basics of Python ♬
Introduction of Python
Introduction of Python
[Introduction to Python] How to sort the contents of a list efficiently with list sort
[Introduction to Python] What is the method of repeating with the continue statement?
[Python] Easy introduction to machine learning with python (SVM)
Introduction to Artificial Intelligence with Python 1 "Genetic Algorithm-Theory-"
[Introduction to Udemy Python 3 + Application] 26. Copy of dictionary
Markov Chain Chatbot with Python + Janome (1) Introduction to Janome
Markov Chain Chatbot with Python + Janome (2) Introduction to Markov Chain
Introduction to Artificial Intelligence with Python 2 "Genetic Algorithm-Practice-"
[Introduction to Udemy Python 3 + Application] 19. Copy of list
How to specify attributes with Mock of python
Introduction to Python with Atom (on the way)
Introduction to Generalized Linear Models (GLM) with Python
[Introduction to Udemy Python3 + Application] 9. First, print with print
[Introduction to Python] Basic usage of lambda expressions
[Introduction to Python] How to get the index of data with a for statement
Introduction to OpenCV (python)-(2)
[Introduction to Python] How to iterate with the range function?
Discord Bot with recording function starting with Python: (1) Introduction discord.py
Change IP settings to ACL of conoha with python
An introduction to Python distributed parallel processing with Ray
Introduction to Mathematics Starting with Python Study Memo Vol.1
Reading Note: An Introduction to Data Analysis with Python
[Introduction to Udemy Python3 + Application] 53. Dictionary of keyword arguments
[Introduction to RasPi4] Environment construction; OpenCV / Tensorflow, Japanese input ♪
[Introduction to Python] Basic usage of the library matplotlib
[Introduction to Udemy Python3 + Application] 52. Tupleization of positional arguments
Introduction to Simple Regression Analysis with Python (Comparison of 6 Libraries of Numerical Calculation/Computer Algebra System)
[Python] Introduction to web scraping | Summary of methods that can be used with webdriver
[Introduction to Sound] Let's arrange the introduction to sounds of python and R ♬-Listen to the sound of the explosion of Nikkei 255-
I tried to find the entropy of the image with python
Connect to BigQuery with Python
I want to specify another version of Python with pyvenv
Introduction to Python Django (2) Win
A collection of competitive pro techniques to solve with Python
Connect to Wikipedia with Python
Introduction to her made with Python ~ Tinder automation project ~ Episode 6
[For beginners] Summary of standard input in Python (with explanation)
Introduction to RDB with sqlalchemy Ⅰ
[Python] Localize sound source only to human voice with ReSpeaker
Introduction of activities applying Python
20200329_Introduction to Data Analysis with Python Second Edition Personal Summary
Introduction to serial communication [Python]
Introduction to her made with Python ~ Tinder automation project ~ Episode 5
Try to automate the operation of network devices with Python
Introduction to Python for VBA users-Calling Python from Excel with xlwings-
Switch python to 2.7 with alternatives