1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
#include "wave.hpp"
#include <AL/al.h>
#include <AL/alc.h>
class SoundSys
{
public:
SoundSys() { Init(); }
~SoundSys() { Close(); }
void Init();
void Close();
void Play(const Wave* const wave );
typedef std::string SoundExcept;
private:
ALCdevice* m_device;
ALCcontext* m_ctx;
};
void SoundSys::Init()
{
m_ctx = 0;
m_device = alcOpenDevice(NULL);
if ( !m_device )
throw SoundExcept("Couldn't open default OpenAL device.");
m_ctx = alcCreateContext(m_device, NULL);
if ( !m_ctx )
{
alcCloseDevice(m_device);
throw SoundExcept("Could not create context.");
}
}
void SoundSys::Play( const Wave* const wave )
{
if ( !m_ctx || !m_device )
throw SoundExcept("SoundSys not initialized");
if ( !wave )
throw SoundExcept("Wave not available for play");
const PCM_Wave& w = wave->Peek();
if (w.data.cksize < 1)
throw SoundExcept("Empty file will not be played");
ALCcontext* old_ctx = alcGetCurrentContext();
alcMakeContextCurrent(m_ctx);
ALuint buf_id = 0;
alGenBuffers(1, &buf_id);
if ( !buf_id )
{
if ( old_ctx ) alcMakeContextCurrent(old_ctx);
throw SoundExcept("Could not generate OpenAL buffer");
}
alBufferData(buf_id, w.format.wBitsPerSample == 16 ?
(w.format.nChannels == 2 ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16):
(w.format.nChannels == 2 ? AL_FORMAT_STEREO8 : AL_FORMAT_MONO8 ),
w.data.data, w.data.cksize, w.format.nSamplesPerSec);
ALuint src;
alGenSources(1, &src);
ALfloat zero[3] = { 0 };
alSourcei ( src, AL_BUFFER , buf_id );
alSourcef ( src, AL_PITCH , 1.0f );
alSourcef ( src, AL_GAIN , 1.0f );
alSourcei ( src, AL_LOOPING , 0 );
alSourcefv( src, AL_POSITION, zero );
alSourcefv( src, AL_VELOCITY, zero );
alSourcePlay( src );
if ( old_ctx ) alcMakeContextCurrent(old_ctx);
}
void SoundSys::Close()
{
if (m_ctx ) alcDestroyContext(m_ctx );
if (m_device) alcCloseDevice(m_device);
m_ctx = 0;
m_device = 0;
}
|