There is a scene to record in Chapter 2 of the book Sound Source Separation Learned with Python, but I'll make a note of it because it's a little jammed.
sounddevice requires pip install sounddevice. wave is built-in and is not needed.
macOS 10.15.6 Python 3.7.8 sounddevice 0.4.1
import numpy as np
import sounddevice as sd
import wave
FILE_NAME = './test.wav' #File name to save
wave_length = 2 #Recording length (seconds)
sample_rate = 16_000 #Sampling frequency
#Start recording (wave_length Record for seconds. Wait until the recording is finished with wait)
data = sd.rec(int(wave_length * sample_rate), sample_rate, channels=1)
sd.wait()
#Normalize. Since it is recorded with 16 bits of quantization bit, it is maximized in the range of int16.
data = data / data.max() * np.iinfo(np.int16).max
# float -> int
data = data.astype(np.int16)
#Save file
with wave.open(FILE_NAME, mode='wb') as wb:
wb.setnchannels(1) #monaural
wb.setsampwidth(2) # 16bit=2byte
wb.setframerate(sample_rate)
wb.writeframes(data.tobytes()) #Convert to byte string
with statement herewave.open opens with wb, so the contents of writeframes should also be bytes.tobytes ()sd.rec returns float, so you need to convert data to an integer type (np.int16 for 16bit)I forgot to convert it to an integer type, and whatever I recorded, it sounded like white noise. We hope for your reference.
wave documentation https://docs.python.org/3.7/library/wave.htmlsounddevice documentation https://python-sounddevice.readthedocs.io/en/0.4.1/usage.html#recordingRecommended Posts