PDMIn – Record an input PDM audio stream

PDMIn can be used to record an input audio signal on a given set of pins.

class audiobusio.PDMIn(clock_pin, data_pin, *, sample_rate=16000, bit_depth=8, mono=True, oversample=64, startup_delay=0.11)

Create a PDMIn object associated with the given pins. This allows you to record audio signals from the given pins. Individual ports may put further restrictions on the recording parameters. The overall sample rate is determined by sample_rate x oversample, and the total must be 1MHz or higher, so sample_rate must be a minimum of 16000.

Parameters:
  • clock_pin (Pin) – The pin to output the clock to
  • data_pin (Pin) – The pin to read the data from
  • sample_rate (int) – Target sample_rate of the resulting samples. Check sample_rate for actual value. Minimum sample_rate is about 16000 Hz.
  • bit_depth (int) – Final number of bits per sample. Must be divisible by 8
  • mono (bool) – True when capturing a single channel of audio, captures two channels otherwise
  • oversample (int) – Number of single bit samples to decimate into a final sample. Must be divisible by 8
  • startup_delay (float) – seconds to wait after starting microphone clock to allow microphone to turn on. Most require only 0.01s; some require 0.1s. Longer is safer. Must be in range 0.0-1.0 seconds.

Record 8-bit unsigned samples to buffer:

import audiobusio
import board

# Prep a buffer to record into
b = bytearray(200)
with audiobusio.PDMIn(board.MICROPHONE_CLOCK, board.MICROPHONE_DATA, sample_rate=16000) as mic:
    mic.record(b, len(b))

Record 16-bit unsigned samples to buffer:

import audiobusio
import board

# Prep a buffer to record into. The array interface doesn't allow for
# constructing with a set size so we append to it until we have the size
# we want.
b = array.array("H")
for i in range(200):
    b.append(0)
with audiobusio.PDMIn(board.MICROPHONE_CLOCK, board.MICROPHONE_DATA, sample_rate=16000, bit_depth=16) as mic:
    mic.record(b, len(b))
deinit()

Deinitialises the PDMIn and releases any hardware resources for reuse.

__enter__()

No-op used by Context Managers.

__exit__()

Automatically deinitializes the hardware when exiting a context.

record(destination, destination_length)

Records destination_length bytes of samples to destination. This is blocking.

An IOError may be raised when the destination is too slow to record the audio at the given rate. For internal flash, writing all 1s to the file before recording is recommended to speed up writes.

Returns:The number of samples recorded. If this is less than destination_length, some samples were missed due to processing time.
sample_rate

The actual sample_rate of the recording. This may not match the constructed sample rate due to internal clock limitations.