Linux ALSA 音频采集

在原生Linux上,我们使用ALSA库进行音频采集。在安卓上,使用OpenSL ES。

下面,超哥提供一段代码给音视频开发初学者,对于认识音频参数比如

采样率,通道,位,码率有很好的帮助。

首先 sudo apt-get install libalsa-ocaml-dev 下载alsa开发库。

然后安装cmake vscode

sudo apt-get install cmake

下载vscode以后,安装cmake tools c++工具

代码中使用了Linux 信号,完整结束程序,写入pcm。

然后建议下载audacity 程序,进行播放测试。

#include 
#include 
#include 
#include 

#define LSA_PCM_NEW_HW_PARAMS_API

static bool m_bRecording = true;

void stopRecording()
{
    printf("\n signal Stop recording...\n");
    m_bRecording = false;
}

int main()
{
    snd_pcm_t *handle;
    snd_pcm_hw_params_t *params;

    int ret = snd_pcm_open(&handle,"default",SND_PCM_STREAM_CAPTURE,0);
    if(ret < 0){
        fprintf(stderr,"unable to open pcm device: %s\n",snd_strerror(ret));
        exit(1);
    }

    snd_pcm_hw_params_alloca(¶ms);

    snd_pcm_hw_params_any(handle,params);

    snd_pcm_hw_params_set_access(handle,params,SND_PCM_ACCESS_RW_INTERLEAVED);

    snd_pcm_hw_params_set_format(handle,params,SND_PCM_FORMAT_S16_LE);

    snd_pcm_hw_params_set_channels(handle,params,2);

    int dir = 0;
    int sampleRate = 44100;
    snd_pcm_hw_params_set_rate_near(handle,params,&sampleRate,&dir);

    int frames = 32;
    snd_pcm_hw_params_set_period_size_near(handle,params,&frames,&dir);

    ret = snd_pcm_hw_params(handle,params);
    if(ret <0){
        fprintf(stderr,"unable toset hw params: %s\n",snd_strerror(ret));
        exit(1);
    }

    snd_pcm_hw_params_get_period_size(params,&frames,&dir);
    int size = frames *4;

    char* pcmBuff = (char*)malloc(size);

    unsigned int val =0;
    snd_pcm_hw_params_get_period_time(params,&val,&dir);

    FILE* pFile;
    pFile = fopen("test.pcm","wb");

    signal(SIGINT,stopRecording);

    while(m_bRecording)
    {
        ret = snd_pcm_readi(handle,pcmBuff,frames);
        if(ret == -EPIPE){
            fprintf(stderr,"overrun.... \n");
            snd_pcm_prepare(handle);
        }
        else if(ret < 0){
            fprintf(stderr,"error read: %s\n",snd_strerror(ret));
        }
        else if(ret != frames ){
            fprintf(stderr,"less read: %s\n",ret);
        }

        ret = fwrite(pcmBuff,sizeof(char),size,pFile);
        if(ret != size){
            fprintf(stderr,"less write: %s\n",ret);
        }


    }

    snd_pcm_drain(handle);
    snd_pcm_close(handle);

    free(pcmBuff);
    fclose(pFile);


    printf("audio capture exit.. \n");

    return 0;

}

然后使用cmake工具, 强烈建议Linux开发使用cmake,比makefile简单很多。

cmake_minimum_required(VERSION 3.5)

INCLUDE_DIRECTORIES("/usr/include")

add_executable(AudioCapture AudioCapture.c)

target_link_libraries(AudioCapture asound)

导入pcm到audacity注意,导入原始数据,然后正确选择你的参数比如通道,采样率才能正常播放,你也可以试试比较下各种错误的参数,比如错误的采样,播放的结果。

你可能感兴趣的:(音视频开发,c++,linux,音视频,运维)