Close

Crusher main.c description.

A project log for Beverly-Crusher: bit crushing toy for 1-bit audio.

I had been looking for a tool to convert audio down to 1-bit depth but gave up and wrote my own. Supports export for Arduino sketch.

electronoobElectronoob 10/06/2014 at 16:450 Comments

Click here to view the complete source on github.


All I do here to convert from 8 bit to 1 bit samples is to decide a cut off point approximately midway in the value between 0 and 255 depending on how it sounds when I preview.

In this example, we check is this current sample greater than decimal 128 ?

If it is we say then that this bit is on and off otherwise.

This is stored in an array which is used later for playback and dumping for microcontroller compatible C.

for (i = 0; i < rawDataSize; ++i)
{
  for (j = 0; j < BUFFER; j++)
  {
    if (rawData[offset] > 128)
    {
      buf[j] = 255;
    }
    else
    {
      buf[j] = 0;
    }
    int z;
    for (z = 0; z < output_bitrate_divisor; z++)
    {
      offset++;
    }
  }
  /* snip snip snip */
}

In order to offer a sample rate down conversion I used a naive approach of just skipping samples in the source array.

Once the samples have been converted to a 1-bit resolution it's now simply a case of going through those converted samples and joining them together to make a string of 8 bits; aka 1 byte of storage.

if (mode == P_STDOUT)
{
  /* get 8 bytes from buffer */
  for (j = 0; j < BUFFER; j = j + 8)
  {
    if (process_begun)
    {
      printf(", ");
    }
    else
    {
      process_begun = 1;
    }
    if (!(obsample_bytes % 15))
    {
      printf("\n");
    }
    /* move through those 8 bytes and convert to binary. 0x00 = 0, 0x255 = 1. */
    unsigned char converted_bits;
    converted_bits = 0;
    for (k = 0; k < 8; k++)
    {
      if (k >= BUFFER)
      {
        /* trying to read past buffer? */
        fprintf(stderr, "Critical error: Tried to exceed BUFFER.\n");
        exit(1);
      }
      converted_bits = converted_bits << 1;
      converted_bits = converted_bits + (buf[j + k] == 255);
      obsample_bits++;
    }
    printf("%#04X", converted_bits);
    obsample_bytes++;
  }
}

Discussions