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 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
|
#include "PlayerAL.h"
#include <al.h>
#include <alc.h>
#include <sndfile.h>
#include <vector>
#include <stdexcept>
#include <iostream>
using namespace std;
PlayerAL::PlayerAL() throw(runtime_error){
// We open the device. NULL = default device
device = alcOpenDevice(NULL);
if (device==false)
throw ("ERROR : could not open the device");
// We create the context
context = alcCreateContext(device, NULL);
if (context==false)
throw ("ERROR : could not create the context");
// We activate it
if (alcMakeContextCurrent(context)==false)
throw ("ERROR : could not activate the context");
//We create the buffer and the source
alGenBuffers(1,&buffer);
alGenSources(1,&source);
//gain=volume
alSourcef(source,AL_MIN_GAIN,0);
alSourcef(source,AL_MAX_GAIN,100);
alSourcef(source,AL_GAIN,100);
//We connect the source and the buffer
alSourcei(source,AL_BUFFER,buffer);
}
void PlayerAL::loadBuffer(const string & str) throw (invalid_argument){
SF_INFO fileInfos;
SNDFILE* audFile = sf_open(str.c_str(), SFM_READ, &fileInfos);
if (audFile==NULL)
throw ("null pointer");
// We fetch the bit rate and the number of samples
ALsizei nbSamples = static_cast<ALsizei>(fileInfos.channels * fileInfos.frames);
ALsizei sampleRate = static_cast<ALsizei>(fileInfos.samplerate);
// We read the file
vector <ALshort> samples(nbSamples);
if (sf_read_short(audFile, &samples[0], nbSamples) < nbSamples)
printf("File corrupted");
sf_close(audFile);
// We choose the format which depends on the number of channels
ALenum format;
switch (fileInfos.channels)
{
case 1 : format = AL_FORMAT_MONO16;
printf("mono");
break;
case 2 : format = AL_FORMAT_STEREO16;
printf("stereo");
break;
default : printf("Bad format");
}
alGetError();
// We fill the buffer with the samples
alBufferData(buffer, format, &samples[0], nbSamples * sizeof(ALushort), sampleRate);
// We check the errors
ALenum error = alGetError();
switch (error){
case AL_INVALID_NAME : printf("invalid name");
break;
case AL_INVALID_ENUM : printf("invalid enum");
break;
case AL_INVALID_VALUE : printf("invalid value");
break;
case AL_INVALID_OPERATION : printf("invalid operation");
break;
case AL_OUT_OF_MEMORY : printf("out of memory");
break;
default:printf("ok");
}
}
void PlayerAL::changeVolume(int value){
alSourcef(source,AL_GAIN,value);
}
void PlayerAL::play(){
alSourcePlay(source);
ALint status;
do{
ALfloat seconds;
alGetSourcef(source,AL_SEC_OFFSET, &seconds);
cout<<"reading..."<<std::fixed<<seconds;
alGetSourcei(source, AL_SOURCE_STATE, &status);
}while(status==AL_PLAYING);
}
void PlayerAL::pause(){
alSourcePause(source);
}
void PlayerAL::stop(){
alSourceStop(source);
} |