OpenAL学习笔记(一)---播放音频(*.wav)


1.简介

OpenAL和OpenGL编码风格很像,跟OpenGL中我们常用的glut类似,OpenAL中也用alut.

2.实现

实现中参考了samples里的loadfile.c;

源码:
TEAudio.h

//! Created 2013/04/22;

//! c++;
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <iostream>

//! OpenAl;
#include "al/alut.h"

using namespace std;
namespace TE
{
	class TEAudio
	{
	private:
		static TEAudio* m_pAudio;

	public:
		TEAudio(void);
		~TEAudio(void);

		//! Singleton. Return the single instance;
		static TEAudio* sharedAudio(void);

		//! Load file and play the media(only *.wav...now)
		void loadFile(const char* strFilePath);
	};
}

TEAudio.cpp (main.cpp)
#include "TEAudio.h"

using namespace TE;

TEAudio* TEAudio::m_pAudio = NULL;

TE::TEAudio::TEAudio( void )
{
	int argc = 1;
	char* argv = "TEApp";
	if (!alutInit (&argc, &argv))
	{
		ALenum error = alutGetError ();
		fprintf (stderr, "%s\n", alutGetErrorString (error));
		exit (EXIT_FAILURE);
	}
}

TE::TEAudio::~TEAudio( void )
{

}

TEAudio* TE::TEAudio::sharedAudio( void )
{
	if (NULL == m_pAudio)
	{
		m_pAudio = new TEAudio();
	}
	return m_pAudio;
}

void TE::TEAudio::loadFile( const char* strFilePath )
{
	ALuint buffer;
	ALuint source;
	ALenum error;
	ALint status;

	/* Create an AL buffer from the given sound file. */
	buffer = alutCreateBufferFromFile (strFilePath);
	if (buffer == AL_NONE)
	{
		error = alutGetError ();
		fprintf (stderr, "Error loading file: '%s'\n",
			alutGetErrorString (error));
		alutExit ();
		exit (EXIT_FAILURE);
	}

	/* Generate a single source, attach the buffer to it and start playing. */
	alGenSources (1, &source);
	alSourcei (source, AL_BUFFER, buffer);
	alSourcePlay (source);

	/* Normally nothing should go wrong above, but one never knows... */
	error = alGetError ();
	if (error != ALUT_ERROR_NO_ERROR)
	{
		fprintf (stderr, "%s\n", alGetString (error));
		alutExit ();
		exit (EXIT_FAILURE);
	}

	/* Check every 0.3 seconds if the sound is still playing. */
	do
	{
		alutSleep (0.3f);
		alGetSourcei (source, AL_SOURCE_STATE, &status);

		std::cout << ".";
	}
	while (status == AL_PLAYING);

}

int main(int argc, char** argv)
{
	//F:\\backup\\c++\\TEGameTest\\Debug\\;
	TEAudio::sharedAudio()->loadFile("lovesong.wav");

	return 0;
}


3.待续....

①加入播放控制(播放、暂停、恢复、动态加载资源);
②与GL mainloop结合(防止图像和音频单独进入死循环);



4.下载链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值