PCM(Pulse Code Modulation,脉冲编码调制)是一种无损的音频编码格式,它通过采样、量化和编码过程将模拟音频信号转换为数字信号。PCM文件通常包含原始的音频样本数据,没有经过压缩,因此保真度高,但文件体积较大。
以下是一个使用arecord
命令行工具录制PCM文件的示例:
arecord -f S16_LE -r 44100 -c 2 output.pcm
-f S16_LE
:设置音频格式为16位小端(Little Endian)PCM。-r 44100
:设置采样率为44.1kHz。-c 2
:设置声道数为2(立体声)。output.pcm
:输出PCM文件的名称。以下是一个使用ALSA库录制PCM文件的简单示例:
#include <stdio.h>
#include <stdlib.h>
#include <alsa/asoundlib.h>
#define SAMPLE_RATE 44100
#define CHANNELS 2
#define SAMPLE_SIZE 16
#define BUFFER_SIZE 4096
int main() {
int err;
snd_pcm_t *capture_handle;
snd_pcm_hw_params_t *params;
unsigned int val;
int dir;
snd_pcm_uframes_t frames;
char *buffer;
// Open PCM device for recording
if ((err = snd_pcm_open(&capture_handle, "default", SND_PCM_STREAM_CAPTURE, 0)) < 0) {
fprintf(stderr, "Cannot open audio device (%s)\n", snd_strerror(err));
return 1;
}
// Allocate hardware parameters object
snd_pcm_hw_params_malloc(¶ms);
// Fill it in with default values
snd_pcm_hw_params_any(capture_handle, params);
// Set the desired hardware parameters
snd_pcm_hw_params_set_access(capture_handle, params, SND_PCM_ACCESS_RW_INTERLEAVED);
snd_pcm_hw_params_set_format(capture_handle, params, SND_PCM_FORMAT_S16_LE);
snd_pcm_hw_params_set_rate_near(capture_handle, params, &val, &dir);
snd_pcm_hw_params_set_channels(capture_handle, params, CHANNELS);
// Apply the hardware parameters
if ((err = snd_pcm_hw_params(capture_handle, params)) < 0) {
fprintf(stderr, "Cannot set hardware parameters (%s)\n", snd_strerror(err));
return 1;
}
// Allocate buffer to hold single period
snd_pcm_hw_params_get_period_size(params, &frames, &dir);
buffer = malloc(frames * CHANNELS * SAMPLE_SIZE / 8);
// Open file for writing
FILE *file = fopen("output.pcm", "wb");
if (!file) {
fprintf(stderr, "Cannot open file for writing\n");
return 1;
}
// Capture audio data
while (1) {
snd_pcm_readi(capture_handle, buffer, frames);
fwrite(buffer, 1, frames * CHANNELS * SAMPLE_SIZE / 8, file);
}
// Close file and PCM device
fclose(file);
snd_pcm_close(capture_handle);
return 0;
}
通过以上步骤和示例代码,你可以在Linux系统上录制PCM格式的音频文件。
领取专属 10元无门槛券
手把手带您无忧上云