OpenSL ES是无授权费、跨平台、针对嵌入式系统精心优化的硬件音频加速API。该库允许使用C或C++来实现高性能,低延迟的音频操作。
Android的OpenSL ES库同样位于NDK的platforms文件夹内。关于OpenSL ES的使用可以进入bdk-sample查看native-audio工程:
OpenSL ES的开发流程主要有如下7个步骤:
- 创建接口对象
- 设置混音器
- 创建播放器
- 设置播放回调函数
- 设置播放状态
- 启动回调函数
- 释放
1 创建引擎与接口
SLresult result;
//1.1 创建引擎
result = slCreateEngine(&engineObject,0,NULL,0,NULL,NULL);
if(SL_RESULT_SUCCESS != result){
return;
}
//1.2 初始化引擎
result = (*engineObject)->Realize(engineObject,SL_BOOLEAN_FALSE);
if(SL_RESULT_SUCCESS != result){
return;
}
//1.3 获取引擎接口SLEngineItf engineInterface
result = (*engineObject)->GetInterface(engineObject,SL_IID_ENGINE,&engineInterface);
2 设置混音器
//创建混音器SLObjectItf outputMixObject
result = (*engineInterface)->CreateOutputMix(engineInterface,&outputMixObject,0,
0,0);
if(SL_RESULT_SUCCESS != result){
return;
}
//初始化混音器outputMixObject
result = (*outputMixObject)->Realize(outputMixObject,SL_BOOLEAN_FALSE);
if(SL_RESULT_SUCCESS != result){
return;
}
//不启用混响可以不用获取接口
//获取混音器接口
//result = (*outputMixObject)->GetInterface(outputMixObject,SL_IID_ENVIRONMENTALREVERB,&outputMixEnvironmentalReverb);
//if(SL_RESULT_SUCCESS == result){
//设置混响:默认
//SL_I3DL2_ENVIRONMENT_PRESET_ROOM :室内
//SL_I3DL2_ENVIRONMENT_PRESET_AUDITORIUM:礼堂
// const SLEnvironmentalReverbSetting settings = SL_I3DL2_ENVIRONMENT_PRESET_DEFAULT
// (*outputMixEnvironmentalReverb)->SetEnvironmentalReverbProperties(outputMixEnvironmentalReverb,&settings)
//
//}
3 创建播放器
//3.1 匹配输入声音信息
//创建buffer缓冲类型的队列 2个队列
SLDataLocator_AndroidSimpleBufferQueue android_queue = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE,
2};
//pcm数据格式
SLDataFormat_PCM pcm = {SL_DATAFORMAT_PCM, 2, SL_SAMPLINGRATE_44_1, SL_PCMSAMPLEFORMAT_FIXED_16,
SL_PCMSAMPLEFORMAT_FIXED_16,
SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT,
SL_BYTEORDER_LITTLEENDIAN};
//数据源 将上述配置信息放到这个数据源中
SLDataSource slDataSource = {&android_queue, &pcm};
//设置混音器
SLDataLocator_OutputMix outputMix = {SL_DATALOCATOR_OUTPUTMIX,outputMixObject};
SLDataSink audioSnk = {&outputMix,NULL};
//需要的接口
const SLInterfaceID ids[1] {SL_IID_BUFFERQUEUE};
const SLboolean req[1] = {SL_BOOLEAN_TRUE};
//创建播放器
(*engineInterface)->CreateAudioPlayer(engineInterface,&bqPlayerObject,&slDataSource,
&audioSnk,1,ids,req);
//初始化播放器
(*bqPlayerObject)->Realize(bqPlayerObject,SL_BOOLEAN_FALSE);
//得到接口后调用 获取Player接口
(*bqPlayerObject)->GetInterface(bqPlayerObject,SL_IID_PLAY,&bqPlayerInterface)
4 设置播放回调
//获取播放器队列接口
(*bqPlayerObject)->GetInterface(bqPlayerObject,SL_IID_BUFFERQUEUE,&bqPlayerBufferQueue);
//设置回调
(*bqPlayerBufferQueue)->RegisterCallback(bqPlayerBufferQUeue,bqPlayerCallback,this);
5 设置播放状态
(*bqPlayerInterface)->SetPlayState(bqPlayerInterface,SL_PLAYSTATE_PLAYING);
6 启动回调函数
bqPlayerCallback(bqPlayerBufferQueue,this);