Linux声卡录音程序之——mp3(通过ALSA操作声卡)
来源:互联网 发布:学校机房监控软件 编辑:程序博客网 时间:2024/06/05 18:50
本文转载自博客:http://blog.sina.com.cn/s/blog_936739790101b4og.html
————————————————--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
此程序通过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, unsignedint 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));
}
returnret;
}
int main(int argc, char **argv)
{
intfd_dsp;
FILE*fd_tmp;
FILE*fd_mp3;
lame_global_flags* gfp;
short*input_buff;
unsignedchar *mp3_buff;
intsamples;
intmp3_bytes;
intwrite_bytes;
int num =0;
intch;
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, speed44100.\n");
return -1;
}
if ((fd_mp3= fopen(argv[1], "w")) == NULL) {
fprintf(stderr, "Open file error: %s\n", strerror(errno));
ret = -1;
goto CLOSE_DSP;
}
gfp =lame_init();
if (gfp ==NULL) {
printf("lame_init failed\n");
ret = -1;
goto CLOSE_MP3;
}
lame_set_in_samplerate(gfp, RATE);
//lame_set_out_samplerate(gfp, RATE);
lame_set_num_channels(gfp, CHANNELS);
//lame_set_brate(gfp, 24);
//lame_set_VBR_min_bitrate_kbps(gfp, lame_get_brate(gfp));
//lame_set_quality(gfp,7);
ret =lame_init_params(gfp);
if (ret< 0) {
printf("lame_init_params returned %d\n", ret);
ret = -1;
goto CLOSE_LAME;
}
ch =lame_get_num_channels(gfp);