本文主要是介绍Linux系统上C++使用alsa库播放声音文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 前言
- 一、命令行
- 1.ffmpeg
- 2.aplay
- 二、代码实现
- 总结
前言
平常读麦克风的场景居多,有时候也需要播放一个声音文件,这里就介绍怎么处理。
一、命令行
1.ffmpeg
ffmpeg -i <filename.wav> -f alsa default
2.aplay
aplay -i <filename.wav>
如果提示找不到aplay就安装工具:
sudo apt install alsa-utils
二、代码实现
main.cpp
#include <alsa/asoundlib.h>
#include <iostream>
#include <fstream>#define PCM_DEVICE "default"//默认的播放设备,你可以在settings里面调换int main(int argc, char *argv[]) {const char *audioFilename = "../wakeup.wav";// 配置ALSA参数snd_pcm_t *pcmHandle;if (snd_pcm_open(&pcmHandle, PCM_DEVICE, SND_PCM_STREAM_PLAYBACK, 0) < 0) {std::cerr << "Error: Failed to open PCM device" << std::endl;return 1;}snd_pcm_hw_params_t *params;snd_pcm_hw_params_alloca(¶ms);snd_pcm_hw_params_any(pcmHandle, params);snd_pcm_hw_params_set_access(pcmHandle, params, SND_PCM_ACCESS_RW_INTERLEAVED);snd_pcm_hw_params_set_format(pcmHandle, params, SND_PCM_FORMAT_S16_LE);snd_pcm_hw_params_set_channels(pcmHandle, params, 2);unsigned int sampleRate = 48000;snd_pcm_hw_params_set_rate_near(pcmHandle, params, &sampleRate, nullptr);snd_pcm_uframes_t bufferSize = 512;snd_pcm_hw_params_set_buffer_size_near(pcmHandle, params, &bufferSize);snd_pcm_hw_params(pcmHandle, params);std::ifstream ifs("../wakeup.wav");if (ifs.is_open()) {std::string data;size_t size;char buffer[8192];while ((size = ifs.readsome(buffer, 8192)) > 0) {data.append(buffer, size);}snd_pcm_sframes_t err = snd_pcm_writei(pcmHandle, (const void *) data.c_str(),data.size()); if (err < 0) {std::cerr << "Error: Failed to write PCM device" << std::endl;}ifs.close();}// 关闭PCM设备和文件snd_pcm_close(pcmHandle);return 0;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(write_speaker)set(CMAKE_CXX_STANDARD 11)add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} asound)
总结
1、不算太难
这篇关于Linux系统上C++使用alsa库播放声音文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!