经典alsa 录音和播放程序

本文提供了使用alsa库在Ubuntu环境下进行音频录制(capture.c)和播放(playback.c)的C语言源码。程序通过alsa的API设置访问模式、格式、通道数和采样率等参数,实现从默认PCM设备录音并保存为WAV文件,以及从WAV文件读取数据并播放。注意,playback程序只能播放原始的WAV文件,不支持MP3等编码过的音频格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里贴上虚拟机ubuntu下alsa的录音程序(capture.c)和播放程序(playback.c)的源码。

首先要测试一下自己的ubuntu是否打开了声音。这个可以打开/系统/首选项/声音  来调节。另外也可以在终端下输入alsaMixer 来调节,之前我的耳机就是只能放音不能录音,因为没有打开一些设置,在进入alsamixer界面后,按F4也就是capture选项,把声音调大就可以录音了。其中有两种模式测验,一种是使用fread和fwrite以读写文件的方式操作,把声卡里的采集到的frame通过dma发送到应用程序的缓存中,先./capture 录音再./playback 放音。另一种是read和write来操作,把输入输出重定向到标准输入和标准输出,下面的程序就可以用./capture > sound.wav 把输出定向到sound.wav文件中,然后./playback < sound.wav 把声音文件传输到playback的输入端。

另外playback只能播放原始的wav文件。不能播放如MP3类型的编码过的音频文件。



capture.c

/* 
This example reads from the default PCM device 
and writes to standard output for 5 seconds of data. 
*/  
/* Use the newer ALSA API */  
#include <stdio.h>
#define ALSA_PCM_NEW_HW_PARAMS_API  
#include <alsa/asoundlib.h>  
int main() {  
long loops;  
int rc,i = 0;  
int size;  
FILE *fp ;
snd_pcm_t *handle;  
snd_pcm_hw_params_t *params;  
unsigned int val,val2;  
int dir;  
snd_pcm_uframes_t frames;  
char *buffer;  
if(  (fp =fopen("sound.wav","w")) < 0)
printf("open sound.wav fial\n");
/* Open PCM device for recording (capture). */  
rc = snd_pcm_open(&handle, "default",  
SND_PCM_STREAM_CAPTURE, 0);  
if (rc < 0) {  
fprintf(stderr,  "unable to open pcm device: %s/n",  snd_strerror(rc));  
exit(1);  
}  
/* Allocate a hardware parameters object. */  
snd_pcm_hw_params_alloca(&params);  
/* Fill it in with default values. */  
snd_pcm_hw_params_any(handle, params);  
/* Set the desired hardware parameters. */  
/* Interleaved mode */  
snd_pcm_hw_params_set_access(handle, params,  
SND_PCM_ACCESS_RW_INTERLEAVED);  
/* Signed 16-bit little-endian format */  
snd_pcm_hw_params_set_format(handle, params,  
SND_PCM_FORMAT_S16_LE);  
/* Two channels (stereo) */  
snd_pcm_hw_params_set_channels(handle, params, 2);  
/* 44100 bits/second sampling rate (CD quality) */  
val = 44100;  
snd_pcm_hw_params_set_rate_near(handle, params,  &val, &dir);  
/* Set period size to 32 frames. */  
frames = 32;  
snd_pcm_hw_params_set_period_size_near(handle,  params, &frames, &dir);  
/* Write the parameters to the driver */  
rc = snd_pcm_hw_params(handle, params);  
if (rc < 0) {  
fprintf(stderr,  "unable to set hw parameters: %s/n",  
snd_strerror(rc));  
exit(1);  
}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值