Advertisement
Guest User

Untitled

a guest
Jun 21st, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <errno.h>
  4. #include <string.h>
  5. #include <math.h>
  6. #include <sys/stat.h>
  7. #include <fcntl.h>
  8. #include <sys/soundcard.h>
  9.  
  10.  
  11. int format;
  12. int rate = 48000;
  13. int word_size = 2;
  14. int channels = 2;
  15. float pi = 3.1415926536;
  16. int write_sine(int out, float pitch, float volume, float t)
  17. {
  18.         signed char *buf, *p;
  19.         int length, buf_size;
  20.     int i, j, k;
  21.     int s;
  22.     float period = 1.0f / pitch;
  23.     float phase;
  24.         length = t * rate;
  25.     buf_size = length * channels * word_size;
  26.     if (!(buf = malloc(buf_size))) {
  27.         fprintf(stderr, "Couldn't allocate buffer: %s\n",
  28.             strerror(errno));
  29.         return -1;
  30.     }
  31.     p = buf;
  32.     for (i=0;i<length;i++) {
  33.         phase = ((float)i * pi * pitch) / (float)rate;
  34. //      printf("phase: %f\n", phase);
  35.         s = (sinf(phase) * volume) * (1 << word_size*8);
  36.         for (j=0;j<channels;j++) {
  37.             for (k=0;k<word_size;k++) {
  38.                 *p = (s>>(8*k)) % 256;
  39.                 //      printf("s: %d i: %d j: %d k: %d p: %hhd\n", s, i, j, k, *p);
  40.                 p++;
  41.             }
  42.         }
  43.     }
  44.     if (-1 == write(out, buf, buf_size)) {
  45.         fprintf(stderr, strerror(errno));
  46.         return -1;
  47.     }
  48.     free(buf);
  49. }
  50.  
  51. int main(int argc, char **argv)
  52. {
  53.     const char *dsp;
  54.     int out;
  55.  
  56.     if (argc > 2) {
  57.         fprintf(stderr, "fuck.\n");
  58.     }
  59.     else if (argc == 2) {
  60.         dsp = argv[1];
  61.     } else {
  62.         dsp = "/dev/dsp";
  63.     }
  64.     if (-1 == (out = open(dsp, O_WRONLY))) {
  65.         fprintf(stderr, "error opening %s: %s\n", dsp,
  66.             strerror(errno));
  67.         exit(1);
  68.     }
  69.         ioctl(out, SNDCTL_DSP_CHANNELS, &channels);
  70.         format = AFMT_S16_LE;
  71.     ioctl(out, SNDCTL_DSP_SETFMT, &format);
  72.     ioctl(out, SNDCTL_DSP_SPEED, &rate);
  73.     if (write_sine(out, 440.0f, 0.01f, 10.0f)) {
  74.         fprintf(stderr, "error in write_sine(): %s\n", strerror(errno));
  75.         exit(1);
  76.     }
  77.     if (close(out)) error(;
  78.     exit;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement