Sound Recorder

This program records Au format sound files. It uses the mBed ADC to sample at a rate of 8KHz and outputs 8-bit signed values to the serial port at 115200 baud. A Au header is prepended to this to allow playback in common audio applications.

Circuit

The program has been tested with a SparkFun Breakout Board for Electret Microphone. The GND terminal of the breakout board is wired to the mBed GND (duh!) and the breakout's Vcc is connected to the mBed's 3.3 regulated VOUT. The AUD pin on the breakout is connected to Analog input pin 20.

Code

#include <stdint.h>
#include "mbed.h"

DigitalOut l1(LED1);
DigitalOut l2(LED2);
DigitalOut l3(LED3);
DigitalOut l4(LED4);
AnalogIn ain(20);
Ticker ticker;
Serial pc(USBTX, USBRX);

/* Sampling routine; records a single sample */
void sample()
{
    static const float ALPHA = 0.999f;
    static float v;
    float l, s =  ain.read();
    
    /* Convert raw value to sample */
    int8_t b = (s - 0.5f) * 127.0f * 2.0f;

    /* Compute next bar graph value */
    l = abs(s - 0.5f) * 2.0;
    v = l > v ? l : v * ALPHA;

    /* Snazzy bar graph */
    l1 = v > 0.08;
    l2 = v > 0.16;
    l3 = v > 0.32;
    l4 = v > 0.62;  

    pc.printf("%c", b);
}

/* Write a 32 bit value in correct byte order for SND files */
void write32(uint32_t v)
{
    uint8_t *b = (uint8_t *)&v;
    
    pc.printf("%c%c%c%c", b[3], b[2], b[1], b[0]);
}

int main() 
{
    pc.baud(115200);
    
    /* Au format header: http://en.wikipedia.org/wiki/Au_file_format */
    pc.printf(".snd");
    write32(24);
    write32(-1);    
    write32(2);     
    write32(8000);      
    write32(1);     
    
    /* Sampler */
    ticker.attach(sample, 1.0f / 8000.0f);

    while(1) {
        wait(1);           
    }
}


Usage

PuTTY or similar can be used to capture the output of the serial port to a file. Beware that PuTTY and some programs may include a text header on the captured file making it unplayable. In such a case, I recommend using HxD or a similar hex editor to remove those bytes. The first four bytes of the file should be '.', 's', 'n' and 'd'.

Attachments