⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 read.c

📁 s3c2410IIS总线实验代码 实现录音以及放音功能
💻 C
字号:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/ioctl.h>
#include<pthread.h>
#include<linux/soundcard.h>

#define RATE 44000
#define SIZE 16
#define CHANNELS 1

struct WaveHead
{
	char flag[4];
	unsigned long fileSize;
	char format[4];
	char chunkid[4];	
	long chunksize;
	unsigned short wformattag;
	unsigned short wchannels;
 / / / 声道道	unsigned long  dwsamplespersec;
 / / 采样率录	unsigned long  dwavgbytespersec;
 / / / / 传 输 速 率 
	unsigned short wblockalign;//
	unsigned short wbitspersample;
 / / / 数 据 位 	
	char datachunkid[4];
	unsigned long datasize;
};

int stop = 0;

void finish()
{
	char buf[80];

	fgets(buf,sizeof(buf),stdin);
	if(buf[0] == '\n')
		stop = 1;
}

int main(int argc,char * argv[])
{
	int id;
	int fd;
	int arg;
	FILE * fp;	
	int status;	
	char buf[44];
	char temp[5];
	char sound[1024];
	struct WaveHead * whp;

	int count;
	long total;

	pthread_t th;
	pthread_attr_t ta;

	pthread_attr_init(&ta);
	pthread_attr_setdetachstate(&ta,PTHREAD_CREATE_DETACHED);
	
	fp = fopen(argv[1],"wb");
	whp = (struct WaveHead *)buf;

	strcpy(temp,"RIFF");
	memcpy(whp->flag,temp,4);
	strcpy(temp,"WAVE");
	memcpy(whp->format,temp,4);
	strcpy(temp,"fmt ");
	memcpy(whp->chunkid,temp,4);
	whp->chunksize = 16;
	whp->wformattag = 1;
	whp->wchannels = 1;
	whp->dwsamplespersec = 44000;
	whp->dwavgbytespersec = 44000;
	whp->wblockalign = 2;
	whp->wbitspersample = 16;
	strcpy(temp,"data");
	memcpy(whp->datachunkid,temp,4);

	fwrite(buf,44,1,fp);		

	if ((fd = open("/dev/dsp",O_RDONLY)) < 0)
	{
		printf("无法打开声卡进行录音!\n");
		exit(1);
	}

	arg = SIZE;
	status = ioctl(fd,SOUND_PCM_WRITE_BITS,&arg);
	if(status == -1)
		printf("SOUND_PCM_WRITE_BITS ioctl failed");
	if(arg != SIZE)
		printf("unable to set sample size");
	
	arg = CHANNELS; 
	status = ioctl(fd,SOUND_PCM_WRITE_CHANNELS,&arg);
	if(status == -1)
		printf("SOUND_PCM_WRITE_CHANNELS ioctl failed");
	if(arg != CHANNELS)
		printf("unable to set number of channels");
	
	arg = RATE;
	status = ioctl(fd,SOUND_PCM_WRITE_RATE,&arg);
	if(status == -1)
		printf("SOUND_PCM_WRITE_WRITE ioctl failed");

	printf("Say something:\n");

	if(pthread_create(&th,&ta,(void * (*)(void *))finish,NULL) < 0)	//创建线程
	{
		printf("创建线程错误!\n");
		exit(1);
	}

	total = 0;
	while(stop == 0)
	{
		count = read(fd,sound,sizeof(sound));
		fwrite(sound,sizeof(sound),1,fp);
		total += count;
	}
	
	fseek(fp,4L,SEEK_SET);	
	whp->fileSize = total - 8;
	fwrite(&buf[4],4,1,fp);
	fseek(fp,40L,SEEK_SET);
	whp->datasize = total - 44;
	fwrite(&buf[40],4,1,fp);	

	close(fd);
	fclose(fp);
	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -