我是Objective-C的新手......
我找到了源代码如何使用OpenAl,复制它然后进行测试,但声音是干扰播放的。你能看一下代码并告诉我有什么问题吗?
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);
答案 0 :(得分:0)
如果声音数据未存储在内存中,则无法播放声音。
free(buffer);
您的声音数据从内存中擦除,alBufferData()仅将OpenAL绑定到声音数据。我建议将缓冲区指针存储在其他位置,以便在您希望从内存中删除声音时释放它。
答案 1 :(得分:0)
您对磁盘上的源数据做了很多假设(字节序,通道数,交错,格式)。您应该在加载文件时查看ASBD并为您转换音频服务。
以下是加载用于OpenAL的音频数据的示例:https://github.com/kstenerud/ObjectAL-for-iPhone/blob/master/libs/ObjectAL/Support/OALAudioFile.m