| Paste number 56237: | lyd |
| Pasted by: | lol |
| When: | 1 year, 4 months ago |
| Share: | Tweet this! | http://paste.lisp.org/+17E5 |
| Channel: | None |
| Paste contents: |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/soundcard.h>
#define DEVICE_NAME "/dev/dsp"
typedef struct {
unsigned char *buffer;
size_t size;
int sample_rate;
} sound_t;
sound_t *
new_sound(int size, int sample_rate)
{
sound_t *sb = (sound_t *) malloc(sizeof (sound_t));
sb->buffer = (unsigned char *) malloc(sizeof (unsigned char) * size);
sb->size = size;
sb->sample_rate = sample_rate;
return sb;
}
void
insert_sinus_tone(sound_t *sb, int frequency, int start, int length)
{
int i;
for (i = 0; i < length; ++i) {
float f = sin((i * frequency) / (sb->sample_rate * 2 * M_PI));
unsigned char sample = (unsigned char) ((f * 127) + 128);
/* printf("%d %d\n", i, sample); */
sb->buffer[start + i] = sample;
}
}
void
free_sound(sound_t *sb)
{
if (sb != 0) {
if (sb->buffer != 0) {
free(sb->buffer);
sb->buffer = 0;
}
free(sb);
sb = 0;
}
}
int
init_audio()
{
int audio_fd;
if ((audio_fd = open(DEVICE_NAME, O_WRONLY, 0)) == -1) {
perror(DEVICE_NAME);
return (-1);
}
return audio_fd;
}
int
play_sound(int audio_fd, sound_t *sb)
{
int len;
if ((len = write(audio_fd, sb->buffer, sb->size)) == -1) {
perror("write");
return (-1);
}
if (len != sb->size) {
fprintf(stderr, "buffer size: %i, len: %i\n", sb->size, len);
return (-1);
}
return (0);
}
int
main(int argc, char **argv)
{
int audio_fd, ret;
sound_t *sb = 0;
if ((audio_fd = init_audio()) == -1) {
return (EXIT_FAILURE);
}
sb = new_sound(4096, 8000);
insert_sinus_tone(sb, 44000, 0, 4096);
if ((ret = play_sound(audio_fd, sb)) == -1) {
free_sound(sb);
close(audio_fd);
return (EXIT_FAILURE);
}
free_sound(sb);
close(audio_fd);
return (EXIT_SUCCESS);
}
This paste has no annotations.