tone.c 1007 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <math.h>
  4. #include <string.h>
  5. void usage(){
  6. fprintf(stderr,"tone <frequency_Hz>,[<amplitude>] [<frequency_Hz>,[<amplitude>]...]\n");
  7. exit(1);
  8. }
  9. int main (int argc,char *argv[]){
  10. int i,j;
  11. double *f;
  12. double *amp;
  13. if(argc<2)usage();
  14. f=alloca(sizeof(*f)*(argc-1));
  15. amp=alloca(sizeof(*amp)*(argc-1));
  16. i=0;
  17. while(argv[i+1]){
  18. char *pos=strchr(argv[i+1],',');
  19. f[i]=atof(argv[i+1]);
  20. if(pos)
  21. amp[i]=atof(pos+1)*32767.f;
  22. else
  23. amp[i]=32767.f;
  24. fprintf(stderr,"%g Hz, %g amp\n",f[i],amp[i]);
  25. i++;
  26. }
  27. for(i=0;i<44100*10;i++){
  28. float val=0;
  29. int ival;
  30. for(j=0;j<argc-1;j++)
  31. val+=amp[j]*sin(i/44100.f*f[j]*2*M_PI);
  32. ival=rint(val);
  33. if(ival>32767.f)ival=32767.f;
  34. if(ival<-32768.f)ival=-32768.f;
  35. fprintf(stdout,"%c%c%c%c",
  36. (char)(ival&0xff),
  37. (char)((ival>>8)&0xff),
  38. (char)(ival&0xff),
  39. (char)((ival>>8)&0xff));
  40. }
  41. return(0);
  42. }