Search code examples
iphoneiosaudioopenal

OpenAL iPhone: unable to play any sound


I'm trying to get to play a simple sound file through OpenAL by referring this tutorial:

I've created a monolithic code from it to test initially, but cant get the sound to play. I've been trying a lot of stuff but I can't get the sound to play. Any help is much appreciated. Thanks.

Here is my code:

ALCdevice* device;
device = alcOpenDevice(NULL);

ALCcontext* context;
alcCreateContext(device, NULL);
alcMakeContextCurrent(context);

NSString* path = [[NSBundle mainBundle] pathForResource:@"mg" ofType:@"caf"];
NSURL* pathURL = [NSURL fileURLWithPath:path];

AudioFileID audioID;
OSStatus audioStatus = AudioFileOpenURL((CFURLRef)pathURL, kAudioFileReadPermission, 0, &audioID);


UInt32 fileSize = 0;
UInt64 outDataSize;
UInt32 propSize = sizeof(UInt64);
OSStatus res = AudioFileGetProperty(audioID, kAudioFilePropertyAudioDataByteCount, &propSize, &outDataSize);
fileSize = (UInt32)outDataSize;

unsigned char* outData = malloc(fileSize);
OSStatus res2 = AudioFileReadBytes(audioID, false, 0, &fileSize, outData);

AudioFileClose(audioID);

ALuint bufferID;
alGenBuffers(1, &bufferID);
alBufferData(bufferID, AL_FORMAT_STEREO16, outData, fileSize, 44100);

ALuint sourceID = 2;
alGenSources(1, &sourceID);
alSourcei(sourceID, AL_BUFFER, bufferID);
alSourcef(sourceID, AL_PITCH, 1.0f);
alSourcef(sourceID, AL_GAIN, 1.0f);
alSourcei(sourceID, AL_LOOPING, AL_FALSE);
free(outData);
outData = NULL;

alSourcePlay(sourceID);

Solution

  • Just found out! I have been using:

    alcCreateContext(device, NULL);
    

    instead of:

    context = alcCreateContext(device, NULL);
    

    The alGetError() helped in pointing this out.