linux c播放音频
时间: 2023-11-16 14:07:11 浏览: 132
你可以使用ALSA(Advanced Linux Sound Architecture)库来在Linux上播放多种格式的音频。以下是一个简单的C代码示例,演示了如何使用ALSA播放WAV和MP3文件:
```c
#include <stdio.h>
#include <stdlib.h>
#include <alsa/asoundlib.h>
#define BUFFER_SIZE 4096
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <audio_file>\n", argv[0]);
return 1;
}
const char *audioFile = argv[1];
int err;
snd_pcm_t *handle;
snd_pcm_hw_params_t *params;
unsigned int sampleRate = 44100;
int channels = 2;
snd_pcm_uframes_t frames;
char buffer[BUFFER_SIZE];
// 打开PCM设备
if ((err = snd_pcm_open(&handle, "default", SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
printf("Error opening PCM device: %s\n", snd_strerror(err));
return 1;
}
// 配置PCM参数
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, channels);
snd_pcm_hw_params_set_rate_near(handle, params, &sampleRate, 0);
// 应用PCM参数
if ((err = snd_pcm_hw_params(handle, params)) < 0) {
printf("Error setting PCM parameters: %s\n", snd_strerror(err));
return 1;
}
// 打开音频文件
FILE *audioFp = fopen(audioFile, "rb");
if (!audioFp) {
printf("Error opening audio file: %s\n", audioFile);
return 1;
}
// 播放音频
while ((frames = fread(buffer, sizeof(char), BUFFER_SIZE, audioFp)) > 0) {
if ((err = snd_pcm_writei(handle, buffer, frames)) != frames) {
printf("Error playing audio: %s\n", snd_strerror(err));
break;
}
}
// 关闭音频文件和PCM设备
fclose(audioFp);
snd_pcm_drain(handle);
snd_pcm_close(handle);
return 0;
}
```
请注意,此示例仅处理WAV和MP3格式的音频文件。如果要处理其他格式的音频,可能需要使用额外的库和工具,如libogg、libvorbis、libflac等库。
阅读全文