Hackster is hosting Hackster Holidays, Ep. 7: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Friday!Stream Hackster Holidays, Ep. 7 on Friday!
Infineon Team
Published © MIT

Silence, Meet Signal: A Beginner's Guide to PDM Microphones

Got ideas? PDM mics + MicroPython on PSOC™ 6 make capturing audio a breeze, so you can bring your voice-powered inventions to life!

BeginnerProtip30 minutes138
Silence, Meet Signal: A Beginner's Guide to PDM Microphones

Things used in this project

Story

Read more

Code

pdm_pcm_recording.py

MicroPython
Code to record audio from PDM microphones and generate raw .wav file
from machine import PDM_PCM, Pin, freq, AUDIO_PDM_24_576_000_HZ
import time
import struct
import uio

clk_pin = "P10_4"
data_pin = "P10_5"

rx_buf = bytearray([0] * 128)
            
def record_audio(filename, time_sec):
    with uio.open(filename, "wb") as f:
        f.write(wav_header)
        start_time = time.time()
        #Start conversion
        pdm_pcm.init()
        while time.time() - start_time < time_sec:  # record for "time_sec" second
            num_read = pdm_pcm.readinto(rx_buf)
            f.write(rx_buf)

#Set clock according to sample rate
freq(AUDIO_PDM_24_576_000_HZ)

pdm_pcm = PDM_PCM(
    0,
    sck=clk_pin,
    data=data_pin,
    sample_rate=8000,
    decimation_rate=64,
    bits=PDM_PCM.BITS_16,
    format=PDM_PCM.MONO_LEFT,
    left_gain=0,
    right_gain=0,
)


# Create a WAV file header
wav_header = bytearray(44)  # 44-byte WAV header
struct.pack_into('<4sI4s4sIHHIIHH', wav_header, 0,
                 'RIFF',        # ChunkID
                 36 + 80 * 32,  # ChunkSize (approximate)
                 'WAVE',        # Format
                 'fmt ',        # Subchunk1ID
                 16,            # Subchunk1Size
                 1,             # AudioFormat (PCM)
                 1,             # NumChannels (MONO_LEFT)
                 8000,          # SampleRate
                 8000 * 2,      # ByteRate
                 2,             # BlockAlign
                 16,            # BitsPerSample
                 )
struct.pack_into('<4sI', wav_header, 36,
                 'data',        # Subchunk2ID
                 80 * 32)       # Subchunk2Size (approximate)

# Record audio for mentioned time period(in secs) and store raw values to given .wav file
record_audio("pcm_audio.wav", 30)

pdm_pcm.deinit()

Credits

Infineon Team

Infineon Team

92 projects • 140 followers

Comments