# SPDX-FileCopyrightText: Copyright (c) 2024 Cooper Dalrymple
#
# SPDX-License-Identifier: Unlicense

import board
import ulab.numpy as np
import ulab.utils

import pio_i2s

FFT_SIZE = 32

mic = pio_i2s.I2S(
    bit_clock=board.GP0,  # word select is GP1
    data_in=board.GP2,
    channel_count=1,
    sample_rate=48000,
    bits_per_sample=16,  # ulab.numpy only works with integers up to 16-bits
    samples_signed=True,
    buffer_size=1024,  # increase this value to improve the resolution of the spectrogram
)

while True:
    
    # Grab a single buffer (1024 samples) from the microphone and convert it to an np.ndarray object
    data = np.array(mic.read(block=True), dtype=np.int16)
    
    # Perform Fourier Fast Transform (FFT) algorithm on audio signal
    data = ulab.utils.spectrogram(data)
    
    # Interpolate down to a smaller set of data
    data = np.interp(
        np.arange(0, len(data), len(data) / FFT_SIZE, dtype=np.float),
        np.arange(0, len(data), 1, dtype=np.uint16),
        data
    )
    
    # Print out the spectrum
    for i in range(len(data)):
        print(data[i], end="\t")
    print()