Reading output of arecord in C with popen

584 Views Asked by At

I have tried to pipe the output of arecord using c:

int main(int argc,char *argv[])
{    
    FILE* file = popen("arecord -r 8000 --format S32_LE -D plughw:0,0 -d 4", "r");
    long buffer[100];
    FILE *fp;
    fp=fopen("./record.dat", "w+"); 
    int i;

    for (i=0; i<40000; i++){
        fscanf(file, "%ld", &buffer[i%100]);
        fprintf(fp,"%d\t%ld\n", i , buffer[i%100] ) ; 
    }

    pclose(file);
    fclose(fp) ;

    FILE *p = popen(GNUPLOT,"w");
    fprintf(p,"plot 'record.dat' lt rgb 'red' title 'yeag' \n");
    fclose(p);

    return 0;
}

I have chosen "long" because of the "signed 32 bit" specification in the arecord command. However, gnuplot is showing me nonsense. Also the program finishes after milliseconds although I want to record for 4 seconds. What am I doing wrong?

1

There are 1 best solutions below

2
Peter Lustig On

it seems like fscanf() is for text not for binary. Thanks to Pablo. A corrected version looks like:

int main(int argc,char *argv[]){    
    FILE* file = popen("arecord -q -t raw -r 8000 --format S32_LE -D plughw:0,0 -d 4", "r");
    int32_t buffer[100];
    FILE *fp;
    fp=fopen("./record.dat", "w+"); 
    int i,k,s;

    for (i=0; i<100; i++){
        fread(&buffer, sizeof(int32_t), 100,  file);
        for (k=0; k<100; k++){
            s = k + 100 * i;
            fprintf(fp,"%d\t%d\n", s , buffer[k] ) ; 
        }    

    }

    pclose(file);
    fclose(fp) ;

    FILE *p = popen(GNUPLOT,"w");
    fprintf(p, "set xrange [3000:3400]\n");
    fprintf(p,"plot 'record.dat' lt rgb 'red' title 'raw' \n");
    fclose(p);

    return 0;
}

which returns a beautiful plot: waves