#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));
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);
printf("default rate is %d, out rate is %d.\n", lame_get_in_samplerate(gfp), lame_get_out_samplerate(gfp));