您的位置:首页 > 其它

使用/dev/dsp的wav文件播放器源码

2010-04-07 19:09 351 查看
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <linux/soundcard.h>

void usage(const char* self)
{
printf("usage:/n");
printf("/t%s [-c channels -r rate -s samplesize] wavfile/n", self);
};

int set_fmt(int fd, int channels, int rate, int samplesize)
{
int c = channels;
if (ioctl(fd, SNDCTL_DSP_CHANNELS, &c) == -1)
exit(1);

if (ioctl(fd, SNDCTL_DSP_SPEED, &rate) == -1)
exit(1);

if (ioctl(fd, SNDCTL_DSP_SAMPLESIZE, &samplesize) == -1)
exit(1);

return 0;
}

int main(int argc, char **argv)
{
int i = 1;
char* filename = NULL;
int channels = 1;
int samplerate = 8000;
int samplesize = 16;

int dsp;
int fd;
char buf[1024];
int len;

if (argc%2)
{
usage(argv[0]);
exit(1);
}

while (i < argc)
{
if (argv[i][0] != '-')
{
filename = argv[i];
i++;
}
else
{
if (i+1 < argc)
{ switch (argv[i][1])
{
case 'c':
channels = atoi(argv[i+1]);
i += 2;
break;

case 'r':
samplerate = atoi(argv[i+1]);
i += 2;
break;

case 's':
samplesize = atoi(argv[i+1]);
i += 2;
break;

default:
perror("bad option/n");
exit(1);
}
}
else
{
perror("bad options/n");
exit(1);
}
}
}

dsp = open("/dev/dsp", O_RDWR);
if (dsp == -1)
{
perror("can not open /dev/dsp/n");
exit(1);
}

set_fmt(dsp, channels, samplerate, samplesize);

fd = open(filename, O_RDWR);
if (fd == -1)
{
close(dsp);

fprintf(stderr, "can not open file %s/n", filename);
exit(1);
}

while ((len = read(fd, buf, 1024)) > 0)
{
write(dsp, buf, len);
}

close(fd);
close(dsp);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: