Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- #include <string.h>
- #include <math.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <sys/soundcard.h>
- int format;
- int rate = 48000;
- int word_size = 2;
- int channels = 2;
- float pi = 3.1415926536;
- int write_sine(int out, float pitch, float volume, float t)
- {
- signed char *buf, *p;
- int length, buf_size;
- int i, j, k;
- int s;
- float period = 1.0f / pitch;
- float phase;
- length = t * rate;
- buf_size = length * channels * word_size;
- if (!(buf = malloc(buf_size))) {
- fprintf(stderr, "Couldn't allocate buffer: %s\n",
- strerror(errno));
- return -1;
- }
- p = buf;
- for (i=0;i<length;i++) {
- phase = ((float)i * pi * pitch) / (float)rate;
- // printf("phase: %f\n", phase);
- s = (sinf(phase) * volume) * (1 << word_size*8);
- for (j=0;j<channels;j++) {
- for (k=0;k<word_size;k++) {
- *p = (s>>(8*k)) % 256;
- // printf("s: %d i: %d j: %d k: %d p: %hhd\n", s, i, j, k, *p);
- p++;
- }
- }
- }
- if (-1 == write(out, buf, buf_size)) {
- fprintf(stderr, strerror(errno));
- return -1;
- }
- free(buf);
- }
- int main(int argc, char **argv)
- {
- const char *dsp;
- int out;
- if (argc > 2) {
- fprintf(stderr, "fuck.\n");
- }
- else if (argc == 2) {
- dsp = argv[1];
- } else {
- dsp = "/dev/dsp";
- }
- if (-1 == (out = open(dsp, O_WRONLY))) {
- fprintf(stderr, "error opening %s: %s\n", dsp,
- strerror(errno));
- exit(1);
- }
- ioctl(out, SNDCTL_DSP_CHANNELS, &channels);
- format = AFMT_S16_LE;
- ioctl(out, SNDCTL_DSP_SETFMT, &format);
- ioctl(out, SNDCTL_DSP_SPEED, &rate);
- if (write_sine(out, 440.0f, 0.01f, 10.0f)) {
- fprintf(stderr, "error in write_sine(): %s\n", strerror(errno));
- exit(1);
- }
- if (close(out)) error(;
- exit;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement