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

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

安装openal第三方库

unbuntu下安装命令:sudo apt-get install libopenal-dev
安装成功,如果找不到对应的头文件需要配置一下头文件路径
export CPLUS_INCLUDE_PATH=$CPLUS_INCLUDE_PATH:openal的头文件路径
不知道头文件路径可以使用find命令进行查找:find / -name 'al.h'

如果无法安装openal库,可以直接下载我编译好的文件,直接使用
链接:https://pan.baidu.com/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)
{
	// 初始化OpenAL
	ALCdevice* 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




  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值