// // 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