此程序通过ALSA打开声卡设备,和从声卡读取数据,避免直接操作声卡。由于不同主机,不同声卡的名字可能不一样,直接通过设备名操作声卡有局限性,故改进成通过ALSA操作。
#include "lame.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
//#include <signal.h>
//#include <sys/ioctl.h>
#include <memory.h>
//#include <linux/soundcard.h>
#include <alsa/asoundlib.h>
#include <sys/time.h>
#define TIMES
10
//录音时间,秒
#define RATE
41000 //采样频率
#define BITS
16
//量化位数
#define CHANNELS 2
//声道数目
#define INBUFF_SIZE 4096
#define MP3BUFF_SIZE (int) (1.25 * INBUFF_SIZE) + 7200
// handle the case of underrun or overrun
int xrun(snd_pcm_t* handle);
// handle the case that device busy
int suspend(snd_pcm_t* handle);
// set alsa params
int SetFormat(snd_pcm_t* handle, unsigned int channels, unsigned int rate)
{
int ret = 0;
ret = snd_pcm_set_params(handle, SND_PCM_FORMAT_S16_LE, SND_PCM_ACCESS_RW_INTERLEAVED, channels, rate, 1, 500000);
if (ret != 0) {
printf("Unable to set params,error(%s)\n", snd_strerror(ret));
}
return ret;
}
int main(int argc, char **argv)
{
int fd_dsp;
FILE* fd_tmp;
FILE* fd_mp3;
lame_global_flags* gfp;
short *input_buff;
unsigned char *mp3_buff;
int samples;
int mp3_bytes;
int write_bytes;
int num = 0;
int ch;
int i = 0;
int ret = 0;
snd_pcm_t* handle;
if (argc != 2) {
fprintf(stderr, "Useage: ./mp3_record test.mp3\n");
return -1;
}
if (snd_pcm_open(&handle, "default", SND_PCM_STREAM_CAPTURE, 0) != 0) {
printf("Failed to open device\n");
return -1;
}
if (SetFormat(handle, CHANNELS, RATE) != 0) {
printf("Cannot set sound device in bit 16, channel 2, speed 44100.\n");
return -1;
}
if ((fd_mp3 = fopen(argv[1], "w")) == NULL) {
fprintf(stderr, "Open file error: %s\n", strerror(errno));
#include "lame.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
//#include <signal.h>
//#include <sys/ioctl.h>
#include <memory.h>
//#include <linux/soundcard.h>
#include <alsa/asoundlib.h>
#include <sys/time.h>
#define TIMES
#define RATE
#define BITS
#define CHANNELS 2
#define INBUFF_SIZE 4096
#define MP3BUFF_SIZE (int) (1.25 * INBUFF_SIZE) + 7200
// handle the case of underrun or overrun
int xrun(snd_pcm_t* handle);
// handle the case that device busy
int suspend(snd_pcm_t* handle);
// set alsa params
int SetFormat(snd_pcm_t* handle, unsigned int channels, unsigned int rate)
{
}
int main(int argc, char **argv)
{