Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

PCM tone generator

Name: Anonymous 2011-10-30 12:52

Hey /prog/

I'm trying to teach myself how to generate PCM audio in C, and I can't figure out why this isn't generating a clear sine wave signal when I pipe it to aplay.  Any ideas?


#include <math.h>

#define MIDDLE_C 261.626
#define HZ 8000.0
#define ONE_CYCLE 2.0
#define PI 3.14159265

int main() {

    float frames = HZ / MIDDLE_C;
    float i;
    float n;
    unsigned int x;
    int s, v;

    for(v=0; v<MIDDLE_C; v++) {
        for(i=0; i<frames; i++) {
            n = (1 + sin((i / frames) * (PI * 2))) / 2;
            x = (int)round(0xFF * n);
            putchar(x);
        }
    }

    return 0;

}

Name: Anonymous 2011-10-30 15:35

>>1,2

Try this:

#define MIDDLE_C 261.626
#define HZ 8000.0
#define ONE_CYCLE 2.0
#define PI 3.14159265
 
int main() {
 
    float frames = HZ / MIDDLE_C;
    int i;
    float n;
    signed char x;
    int v;
 
    for(v=0; v<MIDDLE_C; v++) {
        for(i=0; i<frames; i++) {
            n = sin((i / frames) * (PI * 2));
            x = (signed char)round(0x7F * n);
            putchar(x);
        }
    }
 
    return 0;
 
}


The problem is you're using unsigned values (0x80 being neutral) for output, while the device expects signed chars (0x00 being neutral). Compare the waveforms:

Signed:

  1    _--_
      /    \
     /      \
  0-|        |        |-
              \      /
               \    /
  1             -__-

Unsigned:

  1          .        .
             |\      /|
             | \_  _/ |
  0-|  _--_  |   --   |-
    | /    \ |
    |/      \|
  1 '        '


The jumps in the unsigned output make it sound more like a buzzing noise.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List