提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
一、基础
系统:LINUX(接收端)
协议:UDP
二、代码
键盘输入0结束接收
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
typedef struct
{
unsigned int id;
unsigned int size;
unsigned int format;
}RIFF_S;
typedef struct
{
unsigned int id;
unsigned int size;
unsigned short audioformat;
unsigned short channels;
unsigned int sampleRate;
unsigned int ByteRate;
unsigned short BlockAlign;
unsigned short SampleBit;
}FMT_S;
typedef struct
{
unsigned int id;
unsigned int size;
}Data_s;
typedef struct
{
RIFF_S riff;
FMT_S format;
Data_s data;
}wav_f;
volatile int wav_flag = 1;
void *wav_close_pthread(void *arg)
{
printf("pthread create ok\r\n");
while(1)
{
scanf("%d",&wav_flag);
}
}
int main(int argc, char const *argv[])
{
//pthread
pthread_t tid;
pthread_create(&tid,NULL,wav_close_pthread,NULL);
//wav
wav_f wav;
wav.riff.id = 0x46464952;
wav.riff.format = 0x45564157;
wav.format.id = 0x20746D66;
wav.format.size = 16;
wav.format.audioformat = 0x1;
wav.format.channels = 1; //通道数(根据需求自行修改)
wav.format.sampleRate = 0x3E80; //采样率(根据需求自行修改)
wav.format.ByteRate = wav.format.sampleRate * 2 * wav.format.channels;
wav.format.BlockAlign = wav.format.channels * 2;
wav.format.SampleBit = 16;
wav.data.id = 0x61746164;
wav.data.size = 0;
//file
system("rm -rf wav_temp");
system("rm -rf st_wav.wav");
int temp_fd = open("wav_temp",O_RDWR|O_CREAT);
int wav_fd = open("st_wav.wav",O_RDWR|O_CREAT);
if(temp_fd == -1 || wav_fd == -1)
{
printf("open error\n");
return -1;
}
//socket
int wav_sock = socket(AF_INET,SOCK_DGRAM,0);
struct sockaddr_in servaddr,cliaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(12250);
bind(wav_sock, (struct sockaddr *)&servaddr, sizeof(servaddr));
unsigned short wav_recv_buf[512]; //缓冲区大小(根据需求自行修改)
socklen_t len = sizeof(cliaddr);
ssize_t recv_len;
while(wav_flag)
{
memset(wav_recv_buf,0,sizeof(wav_recv_buf));
recv_len = recvfrom(wav_sock, wav_recv_buf, sizeof(wav_recv_buf), 0, (struct sockaddr *)&cliaddr, &len);
if( recv_len != sizeof(wav_recv_buf) )
{
printf("recv error\n");
}
if( recv_len > 0 )
{
write(temp_fd,wav_recv_buf,recv_len);
wav.data.size += recv_len;
}
}
wav.riff.size = wav.data.size+36;
write(wav_fd,&wav,sizeof(wav));
lseek(temp_fd,0,SEEK_SET);
while(1)
{
memset(wav_recv_buf,0,sizeof(wav_recv_buf));
if( read(temp_fd,wav_recv_buf,sizeof(wav_recv_buf)) > 0 )
write(wav_fd,wav_recv_buf,sizeof(wav_recv_buf));
else
break;
}
close(temp_fd);
close(wav_fd);
printf("wav record over\n");
system("rm -rf wav_temp");
return 0;
}