Search code examples
ios4openal

IOS/OpenAl Sound Interference


I'm new in Objective - C...

I found source code how to use OpenAl, copying this and then testing, but sound was played with interference. Can you look at code and tell what is wrong ?

ALCcontext *context = NULL;
ALCdevice *device = alcOpenDevice(NULL);
if (device)
{
    context = alcCreateContext(device, NULL);
    alcMakeContextCurrent(context);
}
NSString *path = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"caf"];

AudioFileID fileID = 0;
NSURL *url = [NSURL fileURLWithPath:path];

OSStatus result = AudioFileOpenURL((CFURLRef)url, kAudioFileReadPermission, 0, &fileID);
if (result != 0)
    NSLog(@"Faild to load file at path:%@",path);

UInt32 fileSize = 0;
UInt32 propSize = sizeof(UInt64);

OSStatus result1 = AudioFileGetProperty(fileID, kAudioFilePropertyAudioDataByteCount, &propSize, &fileSize);
if (result1 != 0)
    NSLog(@"Cannot get size of file!");

unsigned char *buffer = malloc(fileSize);
OSStatus result2 = noErr;
result2 = AudioFileReadBytes(fileID, false, 0, &fileSize, buffer);
AudioFileClose(fileID);
if (result2 != 0)
    NSLog(@"Cannot load data from file!");

ALuint bufferId = 0;
alGenBuffers(1, &bufferId);
alBufferData(bufferId, AL_FORMAT_STEREO16,  buffer, fileSize, 44100);

free(buffer); 

ALuint sourceId = 0;
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_TRUE);

alSourcePlay(sourceId);

Solution

  • The sound won't play if the sound data is not stored in memory.

    free(buffer); 
    

    Your sound data is wiped from memory, alBufferData() only binds OpenAL to the sound data. I suggest to store the buffer pointer elsewhere so it can be freed when you want the sound removed from memory.