OpenAL音频播放

//
//  OpenALPlayer.m
//  live
//
//  Created by lujunjie on 2016/11/5.
//  Copyright © 2016年 lujunjie. All rights reserved.
//

#import "OpenALPlayer.h"
#import <OpenAL/al.h>
#import <OpenAL/alc.h>
@interface OpenALPlayer()
{
    ALCdevice  *mDevice;
    ALCcontext *mContext;
    ALuint     outSourceID;
}
@end
@implementation OpenALPlayer
- (instancetype)init
{
    if (self=[super init]) {
        
        mDevice=alcOpenDevice(NULL);
        if (mDevice) {
            mContext=alcCreateContext(mDevice, NULL);
            alcMakeContextCurrent(mContext);
            alGenSources(1, &outSourceID);// 创建多个source
            alSpeedOfSound(1.0);
            alDopplerVelocity(1.0);
            alDopplerFactor(1.0);
            //设置源参数
            alSourcef(outSourceID, AL_PITCH, 1.0f);
            alSourcef(outSourceID, AL_GAIN, 1.0f);
            alSourcei(outSourceID, AL_LOOPING, AL_FALSE);
            alSourcef(outSourceID, AL_SOURCE_TYPE, AL_STREAMING);
        }
        
    }
    return self;
}
- (void)play:(void*)pcmData length:(unsigned int)length
{
    NSCondition* ticketCondition= [[NSCondition alloc] init];
    [ticketCondition lock];
    ALuint bufferID = 0;
    alGenBuffers(1, &bufferID); // 创建buffer并获取bufferID
    alBufferData(bufferID, AL_FORMAT_MONO16, pcmData, length, 8000);//把数据添加到buffer
    alSourceQueueBuffers(outSourceID, 1, &bufferID);// 入队bufferID
    ALint stateVaue;
    alGetSourcei(outSourceID, AL_SOURCE_STATE, &stateVaue);//获取状态
    
    if (stateVaue != AL_PLAYING)
    {
        alSourcePlay(outSourceID);
    }
    
    [ticketCondition unlock];
    ticketCondition = nil;
}
@end
原文地址:https://www.cnblogs.com/-ljj/p/6033748.html