Linux声卡录音程序之——mp3(通过ALS…

该程序通过ALSA库与默认声卡交互,进行音频捕获,然后利用LAME库将捕获的数据编码为MP3格式。程序首先打开声卡设备,设置采样参数,然后读取声卡数据并使用LAME编码为MP3,最后将结果写入文件。
摘要由CSDN通过智能技术生成
此程序通过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));
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值