Make a Wav file


/ Published in: C
Save to your folder(s)

Makes a mono 8-bit (i.e. one byte per sample) wav file, "out.wav" containing a 500 Hertz sine wave signal. 22050 is the sample rate, and 64000 is the total size of audio data in bytes.


Copy this code and paste it in your HTML
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <math.h>
  5.  
  6. /* M_PI is declared in math.h */
  7. #define PI M_PI
  8.  
  9.  
  10. typedef unsigned int UI;
  11. typedef unsigned long int UL;
  12. typedef unsigned short int US;
  13. typedef unsigned char UC;
  14. typedef signed int SI;
  15. typedef signed long int SL;
  16. typedef signed short int SS;
  17. typedef signed char SC;
  18.  
  19.  
  20. #define attr(a) __attribute__((a))
  21.  
  22. #define packed attr(packed)
  23.  
  24. /* WAV header, 44-byte total */
  25. typedef struct{
  26. UL riff packed;
  27. UL len packed;
  28. UL wave packed;
  29. UL fmt packed;
  30. UL flen packed;
  31. US one packed;
  32. US chan packed;
  33. UL hz packed;
  34. UL bpsec packed;
  35. US bpsmp packed;
  36. US bitpsmp packed;
  37. UL dat packed;
  38. UL dlen packed;
  39. }WAVHDR;
  40.  
  41.  
  42.  
  43. int savefile(const char*const s,const void*const m,const int ml){
  44. FILE*f=fopen(s,"wb");
  45. int ok=0;
  46. if(f){
  47. ok=fwrite(m,1,ml,f)==ml;
  48. fclose(f);
  49. }
  50. return ok;
  51. }
  52.  
  53.  
  54. /* "converts" 4-char string to long int */
  55. #define dw(a) (*(UL*)(a))
  56.  
  57.  
  58. /* Makes 44-byte header for 8-bit WAV in memory
  59. usage: wavhdr(pointer,sampleRate,dataLength) */
  60.  
  61. void wavhdr(void*m,UL hz,UL dlen){
  62. WAVHDR*p=m;
  63. p->riff=dw("RIFF");
  64. p->len=dlen+44;
  65. p->wave=dw("WAVE");
  66. p->fmt=dw("fmt ");
  67. p->flen=0x10;
  68. p->one=1;
  69. p->chan=1;
  70. p->hz=hz;
  71. p->bpsec=hz;
  72. p->bpsmp=1;
  73. p->bitpsmp=8;
  74. p->dat=dw("data");
  75. p->dlen=dlen;
  76. }
  77.  
  78.  
  79. /* returns 8-bit sample for a sine wave */
  80. UC sinewave(UL rate,float freq,UC amp,UL z){
  81. return sin(z*((PI*2/rate)*freq))*amp+128;
  82. }
  83.  
  84.  
  85. /* make arbitrary audio data here */
  86. void makeaud(UC*p,const UL rate,UL z){
  87. float freq=500;
  88. UC amp=120;
  89. while(z--){
  90. *p++=sinewave(rate,freq,amp,z);
  91. }
  92. }
  93.  
  94.  
  95. /* makes wav file */
  96. void makewav(const UL rate,const UL dlen){
  97. const UL mlen=dlen+44;
  98. UC*const m=malloc(mlen);
  99. if(m){
  100. wavhdr(m,rate,dlen);
  101. makeaud(m+44,rate,dlen);
  102. savefile("out.wav",m,mlen);
  103. }
  104. }
  105.  
  106.  
  107. int main(){
  108. if(sizeof(WAVHDR)!=44)puts("bad struct");
  109. makewav(22050,64000);
  110. return 0;
  111. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.