joeky888 / awesome-micropython-lib

Awesome MicroPython libs
29 stars 10 forks source link

Can the wave module be used with an electret microphone to create an audio file? #1

Open gabemorris12 opened 1 year ago

gabemorris12 commented 1 year ago

Hi,

I just wanted to ask this simple question before I go about purchasing this item. I have yet to find any great resources for taking in audio using Micropython,

I am looking to use a Raspberry Pi Pico to capture ADC data from the electret microphone and store or do whatever I please with the data. I just wanted to make sure that this module was the tool to do it as I am unsure how the process works for taking a list of numbers between 0 and 65535 and converting it into an audio file. I have this sample script prepared if this is how it is supposed to be used.

import rp2
from rp2 import PIO, StateMachine, asm_pio
import array
import wave

# Define the audio recording parameters
SAMPLE_RATE = 16000
RECORD_SECONDS = 5
ADC_PIN = 26

# Configure the PIO state machine for audio capture
@asm_pio(sideset_init=PIO.OUT_LOW, out_shiftdir=PIO.SHIFT_LEFT, autopull=True, pull_thresh=32)
def audio_capture():
    # Shift out 0 on each cycle and shift in the ADC value
    pull()
    in_(ADC_PIN)
    out(pins=1, shift_left=8)

# Initialize the PIO state machine
sm = StateMachine(0, audio_capture, freq=8*SAMPLE_RATE, sideset_base=PIO.PIN_BASE)

# Create an array to store the audio data
audio_data = array.array("H", [0] * (SAMPLE_RATE * RECORD_SECONDS))

# Start the audio capture
sm.active(1)

# Capture audio samples
for i in range(len(audio_data)):
    sm.put()
    audio_data[i] = sm.get()

# Stop the audio capture
sm.active(0)

# Create a WAV file and store the audio data
with wave.open("audio_capture.wav", "wb") as wav_file:
    wav_file.setnchannels(1)
    wav_file.setsampwidth(2)
    wav_file.setframerate(SAMPLE_RATE)
    wav_file.writeframes(audio_data.tobytes())

print("Audio capture complete.")

Will this plan work?

joeky888 commented 1 year ago

Hmm... Sounds like a homework or a personal project. Here is a little background of me, I'm a Golang backend developer right now, back when I was an embed developer about 5 years ago, I found Micropython and then gave up on it because it lacks a lot of library support. I'd recommend c++/rust/tinygo instead, here is the tutorial.

Here is a little advice for you:

  1. Just buy it and do it.
  2. If Micropython doesn't work, please try C++, it's not that scary.
  3. Performance first.
  4. Always have a plan B, learn from failure.
  5. Come up with a business model, like how to profit from your idea.

That's the reasons I end up choose Go and Rust for my main language. Not Micropython.