资源简介
纯C语言+libalsa实现最简单录音程序
代码片段和文件信息
#include “head4audio.h“
// 根据本系统的具体字节序处理的存放格式
#if __BYTE_ORDER == __LITTLE_ENDIAN
#define RIFF (‘F‘<<24 | ‘F‘<<16 | ‘I‘<<8 | ‘R‘<<0)
#define WAVE (‘E‘<<24 | ‘V‘<<16 | ‘A‘<<8 | ‘W‘<<0)
#define FMT (‘ ‘<<24 | ‘t‘<<16 | ‘m‘<<8 | ‘f‘<<0)
#define DATA (‘a‘<<24 | ‘t‘<<16 | ‘a‘<<8 | ‘d‘<<0)
#define LE_SHORT(val) (val)
#define LE_INT(val) (val)
#elif __BYTE_ORDER == __BIG_ENDIAN
#define RIFF (‘R‘<<24 | ‘I‘<<16 | ‘F‘<<8 | ‘F‘<<0)
#define WAVE (‘W‘<<24 | ‘A‘<<16 | ‘V‘<<8 | ‘E‘<<0)
#define FMT (‘f‘<<24 | ‘m‘<<16 | ‘t‘<<8 | ‘ ‘<<0)
#define DATA (‘d‘<<24 | ‘a‘<<16 | ‘t‘<<8 | ‘a‘<<0)
#define LE_SHORT(val) bswap_16(val)
#define LE_INT(val) bswap_32(val)
#endif
#define DURATION_TIME 3
// 准备WAV格式参数
void prepare_wav_params(wav_format *wav)
{
wav->format.fmt_id = FMT;
wav->format.fmt_size = LE_INT(16);
wav->format.fmt = LE_SHORT(WAV_FMT_PCM);
wav->format.channels = LE_SHORT(2); // 声道数目
wav->format.sample_rate = LE_INT(44100); // 采样频率
wav->format.bits_per_sample = LE_SHORT(16); // 量化位数
wav->format.block_align = LE_SHORT(wav->format.channels
* wav->format.bits_per_sample/8);
wav->format.byte_rate = LE_INT(wav->format.sample_rate
* wav->format.block_align);
wav->data.data_id = DATA;
wav->data.data_size = LE_INT(DURATION_TIME
* wav->format.byte_rate);
wav->head.id = RIFF;
wav->head.format = WAVE;
wav->head.size = LE_INT(36 + wav->data.data_size);
}
// 设置WAV格式参数
void set_wav_params(pcm_container *sound wav_format *wav)
{
// 1:定义并分配一个硬件参数空间
snd_pcm_hw_params_t *hwparams;
snd_pcm_hw_params_alloca(&hwparams);
// 2:初始化硬件参数空间
snd_pcm_hw_params_any(sound->handle hwparams);
// 3:设置访问模式为交错模式(即帧连续模式)
snd_pcm_hw_params_set_access(sound->handle hwparams
SND_PCM_ACCESS_RW_INTERLEAVED);
// 4:设置量化参数
snd_pcm_format_t pcm_format = SND_PCM_FORMAT_S16_LE;
snd_pcm_hw_params_set_format(sound->handle
hwparams pcm_format);
sound->format = pcm_format;
// 5:设置声道数目
snd_pcm_hw_params_set_channels(sound->handle
hwparams LE_SHORT(wav->format.channels));
sound->channels = LE_SHORT(wav->format.channels);
// 6:设置采样频率
// 注意:最终被设置的频率被存放在来exact_rate中
uint32_t exact_rate = LE_INT(wav->format.sample_rate);
snd_pcm_hw_params_set_rate_near(sound->handle
hwparams &exact_rate 0);
// 7:设置buffer size为声卡支持的最大值
snd_pcm_uframes_t buffer_size;
snd_pcm_hw_params_get_buffer_size_max(hwparams
&buffer_size);
snd_pcm_hw_params_set_buffer_size_near(sound->handle
hwparams &buffer_size);
评论
共有 条评论