开发者

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, kAudioFilePro开发者_StackOverflow中文版pertyAudioDataByteCount, &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);


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.


You're making a lot of assumptions about the source data on disk (endianness, number of channels, interleaving, format). You should be looking at the ASBD and having audio services convert for you when loading the file.

Here's an example of loading audio data for use in OpenAL: https://github.com/kstenerud/ObjectAL-for-iPhone/blob/master/libs/ObjectAL/Support/OALAudioFile.m

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜