1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Linux下使用C++播放wav音频文件

Linux下使用C++播放wav音频文件

时间:2024-03-08 01:39:38

相关推荐

Linux下使用C++播放wav音频文件

Linux下使用C++播放wav音频文件

安装openal第三方库上代码

安装openal第三方库

unbuntu下安装命令:sudo apt-get install libopenal-dev

安装成功,如果找不到对应的头文件需要配置一下头文件路径

export CPLUS_INCLUDE_PATH=$CPLUS_INCLUDE_PATH:openal的头文件路径

不知道头文件路径可以使用find命令进行查找:find / -name 'al.h'

如果无法安装openal库,可以直接下载我编译好的文件,直接使用

链接:/s/1DNauU3HZkfhnJayOfkR5tw

提取码:jy7q

上代码

#include <iostream>#include <al.h>#include <alc.h>#include <vector>#include <fstream>#include <sstream>#include <cstring>using namespace std;struct WavHeader {char chunkID[4];uint32_t chunkSize;char format[4];char subchunk1ID[4];uint32_t subchunk1Size;uint16_t audioFormat;uint16_t numChannels;uint32_t sampleRate;uint32_t byteRate;uint16_t blockAlign;uint16_t bitsPerSample;char subchunk2ID[4];uint32_t subchunk2Size;};uint32_t GetSampleRate(const char* file){ifstream ifs(file, ios::in|ios::binary);if(!ifs.is_open()){std::cerr << "Can't open file:" << file << endl;return 0;}WavHeader header;ifs.read(reinterpret_cast<char *>(&header), sizeof(WavHeader));ifs.close();if (std::string(header.chunkID, 4) != "RIFF" ||std::string(header.format, 4) != "WAVE" ||std::string(header.subchunk1ID, 4) != "fmt " ||(std::string(header.subchunk2ID, 4) != "data" &&std::string(header.subchunk2ID, 4) != "LIST")) {std::cerr << "Invalid WAV file" << std::endl;return 0;}return header.sampleRate;}bool PlaySound(const char* file){// 初始化OpenALALCdevice* device = alcOpenDevice(nullptr);ALCcontext* context = alcCreateContext(device, nullptr);alcMakeContextCurrent(context);const unsigned int False = 0;unsigned int nSampleRate = GetSampleRate(file);if(False == nSampleRate)return false;std::ifstream ifs(file, ios::binary|ios::in);std::ostringstream tmp;tmp << ifs.rdbuf();std::string str = tmp.str();ifs.close();ALuint source;alGenSources(1, &source);ALuint bufferId;alGenBuffers(1, &bufferId);alBufferData(bufferId, AL_FORMAT_MONO16, str.c_str(), str.size(), nSampleRate);alSourcei(source, AL_BUFFER, bufferId);alSourcePlay(source);// 等待音频播放完毕ALint state;do{alGetSourcei(source, AL_SOURCE_STATE, &state);} while (state == AL_PLAYING);// 清理alDeleteSources(1, &source);alDeleteBuffers(1, &bufferId);alcDestroyContext(context);alcCloseDevice(device);return true;}int main(){PlaySound("wavFile");return 0;}//编译指令:g++ audio.cpp -o test -std=c++11 -lopenal

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。