static int android_audio_init(audio_decoder_t *ad) { decoder_t *d = (decoder_t *)ad; d->d_gain = 1.0f; d->d_last_set_vol = 0; if(slCreateEngine(&d->d_engine, 0, NULL, 0, NULL, NULL)) { TRACE(TRACE_ERROR, "SLES", "Unable to create engine"); return -1; } if((*d->d_engine)->Realize(d->d_engine, SL_BOOLEAN_FALSE)) { TRACE(TRACE_ERROR, "SLES", "Unable to relize engine"); return -1; } if((*d->d_engine)->GetInterface(d->d_engine, SL_IID_ENGINE, &d->d_eif)) { TRACE(TRACE_ERROR, "SLES", "Unable to get interface for engine"); return -1; } TRACE(TRACE_DEBUG, "SLES", "Engine opened"); if((*d->d_eif)->CreateOutputMix(d->d_eif, &d->d_mixer, 0, NULL, NULL)) { TRACE(TRACE_ERROR, "SLES", "Unable to create output mixer"); return -1; } if((*d->d_mixer)->Realize(d->d_mixer, SL_BOOLEAN_FALSE)) { TRACE(TRACE_ERROR, "SLES", "Unable to realize output mixer"); return -1; } TRACE(TRACE_DEBUG, "SLES", "Mixer opened"); return 0; }
//----------------------------------------------------------------- int main(int argc, char* const argv[]) { SLresult result; SLObjectItf sl; fprintf(stdout, "OpenSL ES test %s: exercises SLPlayItf, SLVolumeItf, SLMuteSoloItf\n", argv[0]); fprintf(stdout, "and AudioPlayer with SLDataLocator_URI source / OutputMix sink\n"); fprintf(stdout, "Plays a sound and alternates the muting of the channels (for 5s).\n"); fprintf(stdout, " and then alternates the solo\'ing of the channels (for 5s).\n"); fprintf(stdout, "Stops after 10s\n"); if (argc == 1) { fprintf(stdout, "Usage: \t%s url\n", argv[0]); fprintf(stdout, "Example: \"%s /sdcard/my.mp3\"\n", argv[0]); exit(EXIT_FAILURE); } SLEngineOption EngineOption[] = { {(SLuint32) SL_ENGINEOPTION_THREADSAFE, (SLuint32) SL_BOOLEAN_TRUE} }; result = slCreateEngine( &sl, 1, EngineOption, 0, NULL, NULL); ExitOnError(result); /* Realizing the SL Engine in synchronous mode. */ result = (*sl)->Realize(sl, SL_BOOLEAN_FALSE); ExitOnError(result); if (argc > 1) { TestPlayUri(sl, argv[1]); } /* Shutdown OpenSL ES */ (*sl)->Destroy(sl); return EXIT_SUCCESS; }
HowieError EngineImpl::init() { HOWIE_TRACE_FN(HOWIE_TRACE_LEVEL_CALLS) SLresult result; // create EngineImpl HOWIE_CHECK(slCreateEngine(&engineObject_, 0, NULL, 0, NULL, NULL)); // realize the EngineImpl HOWIE_CHECK((*engineObject_)->Realize(engineObject_, SL_BOOLEAN_FALSE)); // get the EngineImpl interface, which is needed in order to create other objects HOWIE_CHECK((*engineObject_)->GetInterface(engineObject_, SL_IID_ENGINE, &engineItf_)); // create output mix, HOWIE_CHECK((*engineItf_)->CreateOutputMix(engineItf_, &outputMixObject_, 0, NULL, NULL)); // realize the output mix HOWIE_CHECK((*outputMixObject_)->Realize(outputMixObject_, SL_BOOLEAN_FALSE)); return HOWIE_SUCCESS; }
AudioInterfaceOpenSL::AudioInterfaceOpenSL() { SLuint32 lEngineMixIIDCount = 1; const SLInterfaceID lEngineMixIIDs[] = {SL_IID_ENGINE}; const SLboolean lEngineMixReqs[] = {SL_BOOLEAN_TRUE}; const SLuint32 lOutputMixIIDCount = 0; const SLInterfaceID lOutputMixIIDs[] = {}; const SLboolean lOutputMixReqs[] = {}; SLresult lRes; lRes = slCreateEngine(&mSlEngineObject, 0, NULL, lEngineMixIIDCount, lEngineMixIIDs, lEngineMixReqs); lRes=(*mSlEngineObject)->Realize(mSlEngineObject, SL_BOOLEAN_FALSE); lRes=(*mSlEngineObject)->GetInterface(mSlEngineObject, SL_IID_ENGINE, &mSlEngine); lRes=(*mSlEngine)->CreateOutputMix(mSlEngine, &mSlOutputObject, lOutputMixIIDCount, lOutputMixIIDs, lOutputMixReqs); lRes=(*mSlOutputObject)->Realize(mSlOutputObject, SL_BOOLEAN_FALSE); createSoundPlayer(); mInstance = this; }
HowieError EngineImpl::init() { __android_log_print(ANDROID_LOG_VERBOSE, "HOWIE", __func__); SLresult result; // create EngineImpl HOWIE_CHECK(slCreateEngine(&engineObject_, 0, NULL, 0, NULL, NULL)); // realize the EngineImpl HOWIE_CHECK((*engineObject_)->Realize(engineObject_, SL_BOOLEAN_FALSE)); // get the EngineImpl interface, which is needed in order to create other objects HOWIE_CHECK((*engineObject_)->GetInterface(engineObject_, SL_IID_ENGINE, &engineItf_)); // create output mix, HOWIE_CHECK((*engineItf_)->CreateOutputMix(engineItf_, &outputMixObject_, 0, NULL, NULL)); // realize the output mix HOWIE_CHECK((*outputMixObject_)->Realize(outputMixObject_, SL_BOOLEAN_FALSE)); return HOWIE_SUCCESS; }
SLresult AudioEngine::initialize() { SLresult ret = SL_RESULT_SUCCESS; ret = slCreateEngine(&engine_object_, 0, NULL, 0, NULL, NULL); if (SL_RESULT_SUCCESS != ret) { LOG_E("error: slCreateEngine ret = %lx", ret); goto err; } ret = (*engine_object_)->Realize(engine_object_, SL_BOOLEAN_FALSE); if (SL_RESULT_SUCCESS != ret) { LOG_E("error: Realize ret = %lx", ret); goto err; } ret = (*engine_object_)->GetInterface(engine_object_, SL_IID_ENGINE, &engine_engine_); if (SL_RESULT_SUCCESS != ret) { LOG_E("error: GetInterface SL_IID_ENGINE ret = %lx", ret); goto err; } ret = (*engine_engine_)->CreateOutputMix(engine_engine_, &output_mix_object_, 0, NULL, NULL); if (SL_RESULT_SUCCESS != ret) { LOG_E("error: CreateOutputMix ret = %lx", ret); goto err; } ret = (*output_mix_object_)->Realize(output_mix_object_, SL_BOOLEAN_FALSE); if (SL_RESULT_SUCCESS != ret) { LOG_E("error: Realize ret = %lx", ret); goto err; } err: return ret; }
// create the engine and output mix objects void naCreateEngine(JNIEnv* env, jclass clazz) { SLresult result; // create engine result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL); assert(SL_RESULT_SUCCESS == result); // realize the engine result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); // get the engine interface, which is needed in order to create other objects result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); assert(SL_RESULT_SUCCESS == result); // create output mix, with environmental reverb specified as a non-required interface const SLInterfaceID ids[1] = {SL_IID_ENVIRONMENTALREVERB}; const SLboolean req[1] = {SL_BOOLEAN_FALSE}; result = (*engineEngine)->CreateOutputMix(engineEngine, &outputMixObject, 1, ids, req); assert(SL_RESULT_SUCCESS == result); // realize the output mix result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); // get the environmental reverb interface // this could fail if the environmental reverb effect is not available, // either because the feature is not present, excessive CPU load, or // the required MODIFY_AUDIO_SETTINGS permission was not requested and granted result = (*outputMixObject)->GetInterface(outputMixObject, SL_IID_ENVIRONMENTALREVERB, &outputMixEnvironmentalReverb); if (SL_RESULT_SUCCESS == result) { result = (*outputMixEnvironmentalReverb)->SetEnvironmentalReverbProperties( outputMixEnvironmentalReverb, &reverbSettings); } }
// create the engine and output mix objects void Java_com_v2soft_V2AndLib_demoapp_ui_activities_OpenSLSample_createPlayerEngine( JNIEnv* env, jclass clazz) { // create engine SLresult result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL); assert(SL_RESULT_SUCCESS == result); // realize the engine result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); // get the engine interface, which is needed in order to create other objects result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); assert(SL_RESULT_SUCCESS == result); // create output mix, with environmental reverb specified as a non-required interface const SLInterfaceID ids[1] = {SL_IID_ENVIRONMENTALREVERB}; const SLboolean req[1] = {SL_BOOLEAN_FALSE}; result = (*engineEngine)->CreateOutputMix(engineEngine, &gOutputMixObject, 1, ids, req); assert(SL_RESULT_SUCCESS == result); // realize the output mix result = (*gOutputMixObject)->Realize(gOutputMixObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); }
Error AudioDriverOpenSL::init() { SLresult res; SLEngineOption EngineOption[] = { (SLuint32)SL_ENGINEOPTION_THREADSAFE, (SLuint32)SL_BOOLEAN_TRUE }; res = slCreateEngine(&sl, 1, EngineOption, 0, NULL, NULL); if (res != SL_RESULT_SUCCESS) { ERR_EXPLAIN("Could not Initialize OpenSL"); ERR_FAIL_V(ERR_INVALID_PARAMETER); } res = (*sl)->Realize(sl, SL_BOOLEAN_FALSE); if (res != SL_RESULT_SUCCESS) { ERR_EXPLAIN("Could not Realize OpenSL"); ERR_FAIL_V(ERR_INVALID_PARAMETER); } return OK; }
void AndroidSoundEngine::startBGMService() { Log::info("Starting BGM Service."); SLresult result = slCreateEngine(&_engineObj, 0, NULL, 0, NULL, NULL); slCheckErrorWithStatus(result, "Problem creating SLESengine (Error %d).", result); result = (*_engineObj)->Realize(_engineObj, SL_BOOLEAN_FALSE); slCheckErrorWithStatus(result, "Problem realizing SLES engine (Error %d).", result); result = (*_engineObj)->GetInterface(_engineObj, SL_IID_ENGINE, &_engine); slCheckErrorWithStatus(result, "Problem getting SL_IID_ENGINE for engine (Error %d).", result); // Creates audio output. const SLuint32 outputMixIIDCount = 0; const SLInterfaceID outputMixIIDs[] = {}; const SLboolean outputMixReqs[] = {}; result = (*_engine)->CreateOutputMix(_engine, &_outputMix, outputMixIIDCount, outputMixIIDs, outputMixReqs); slCheckErrorWithStatus(result, "Problem creating audio output (Error %d).", result); result = (*_outputMix)->Realize(_outputMix, SL_BOOLEAN_FALSE); slCheckErrorWithStatus(result, "Problem realizing audio output (Error %d).", result); slCheckErrorWithStatus(result, "Problem while getting DeviceVolume (Error %d).", result); Log::info("BGM Service ........ OK"); }
void createEngine() { SLresult result; // create engine result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL); assert(SL_RESULT_SUCCESS == result); // realize the engine result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); // get the engine interface result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); assert(SL_RESULT_SUCCESS == result); // create output mix const SLInterfaceID ids[1] = {SL_IID_ENVIRONMENTALREVERB}; const SLboolean req[1] = {SL_BOOLEAN_FALSE}; result = (*engineEngine)->CreateOutputMix(engineEngine, &outputMixObject, 1, ids, req); assert(SL_RESULT_SUCCESS == result); // realize the output mix result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); #if 0 // get the environmental reverb interface result = (*outputMixObject)->GetInterface(outputMixObject, SL_IID_ENVIRONMENTALREVERB, &outputMixEnvironmentalReverb); if (SL_RESULT_SUCCESS == result) { result = (*outputMixEnvironmentalReverb)->SetEnvironmentalReverbProperties(outputMixEnvironmentalReverb, &reverbSettings); } #endif // ignore unsuccessful result codes for env reverb }
// create the engine and output mix objects int OpenSLWrap_Init(AndroidAudioCallback cb) { audioCallback = cb; SLresult result; // create engine result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL); if(SL_RESULT_SUCCESS != result) { goto FAIL; } result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); if(SL_RESULT_SUCCESS != result) { goto FAIL; } result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); if(SL_RESULT_SUCCESS != result) { goto FAIL; } result = (*engineEngine)->CreateOutputMix(engineEngine, &outputMixObject, 0, 0, 0); if(SL_RESULT_SUCCESS != result) { goto FAIL; } result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE); if(SL_RESULT_SUCCESS != result) { goto FAIL; } SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2}; SLDataFormat_PCM format_pcm = { SL_DATAFORMAT_PCM, 1,//2, SL_SAMPLINGRATE_44_1, SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16, SL_SPEAKER_FRONT_CENTER,//SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT, SL_BYTEORDER_LITTLEENDIAN }; SLDataSource audioSrc = {&loc_bufq, &format_pcm}; // configure audio sink SLDataLocator_OutputMix loc_outmix = {SL_DATALOCATOR_OUTPUTMIX, outputMixObject}; SLDataSink audioSnk = {&loc_outmix, NULL}; // create audio player const SLInterfaceID ids[2] = {SL_IID_BUFFERQUEUE, SL_IID_VOLUME}; const SLboolean req[2] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE}; result = (*engineEngine)->CreateAudioPlayer(engineEngine, &bqPlayerObject, &audioSrc, &audioSnk, 2, ids, req); if(SL_RESULT_SUCCESS != result) { goto FAIL; } result = (*bqPlayerObject)->Realize(bqPlayerObject, SL_BOOLEAN_FALSE); if(SL_RESULT_SUCCESS != result) { goto FAIL; } result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_PLAY, &bqPlayerPlay); if(SL_RESULT_SUCCESS != result) { goto FAIL; } result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_BUFFERQUEUE, &bqPlayerBufferQueue); if(SL_RESULT_SUCCESS != result) { goto FAIL; } result = (*bqPlayerBufferQueue)->RegisterCallback(bqPlayerBufferQueue, bqPlayerCallback, NULL); if(SL_RESULT_SUCCESS != result) { goto FAIL; } result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_VOLUME, &bqPlayerVolume); if(SL_RESULT_SUCCESS != result) { goto FAIL; } result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_PLAYING); if(SL_RESULT_SUCCESS != result) { goto FAIL; } // Render and enqueue a first buffer. (or should we just play the buffer empty?) curBuffer = 0; audioCallback(buffer[curBuffer], BUFFER_SIZE); result = (*bqPlayerBufferQueue)->Enqueue(bqPlayerBufferQueue, buffer[curBuffer], BUFFER_SIZE); if (SL_RESULT_SUCCESS != result) { goto FAIL; } SUCCESS: return 1; FAIL: return 0; }
int main(int argc, char **argv) { SLresult result; // create engine SLObjectItf engineObject; result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL); assert(SL_RESULT_SUCCESS == result); result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); SLEngineItf engineEngine; result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); assert(SL_RESULT_SUCCESS == result); // create output mix SLObjectItf mixObject; result = (*engineEngine)->CreateOutputMix(engineEngine, &mixObject, 0, NULL, NULL); assert(SL_RESULT_SUCCESS == result); result = (*mixObject)->Realize(mixObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); // create threads int i; int ok; for (i = 0; i < MAX_THREAD; ++i) { ThreadArgument *ta = &thread_args[i]; int r = rand(); switch (r & 1) { #if 0 case 0: ta->mObjectID = SL_OBJECTID_OUTPUTMIX; ta->mURI = NULL; ta->mEngineEngine = engineEngine; ta->mMixObject = NULL; ta->mCounter = 0; break; case 1: #endif default: ta->mObjectID = SL_OBJECTID_AUDIOPLAYER; ta->mURI = (SLchar *) uris[(r >> 1) & 3]; ta->mEngineEngine = engineEngine; ta->mMixObject = mixObject; ta->mCounter = 0; break; } //pthread_mutex_lock(&mutex); //pthread_mutex_unlock(&mutex); ok = pthread_create(&threads[i], (const pthread_attr_t *) NULL, thread_start, &thread_args[i]); assert(0 == ok); } // let it run for a while int j; for (j = 0; j < 100; ++j) { sleep(1); for (i = 0; i < MAX_THREAD; ++i) { ThreadArgument *ta = &thread_args[i]; printf("[%d]=%u ", j, ta->mCounter); } printf("\n"); } // signal threads that they should exit timeToExit = 1; for (j = 0; j < 3; ++j) { sleep(1); for (i = 0; i < MAX_THREAD; ++i) { ThreadArgument *ta = &thread_args[i]; printf("[%d]=%u ", j, ta->mCounter); } printf("\n"); } // now wait for the threads to actually exit for (i = 0; i < MAX_THREAD; ++i) { ok = pthread_join(threads[i], NULL); assert(0 == ok); } // tear down objects (*mixObject)->Destroy(mixObject); (*engineObject)->Destroy(engineObject); return EXIT_SUCCESS; }
void cahal_initialize( void ) { if( CAHAL_STATE_NOT_INITIALIZED == g_cahal_state ) { SLresult result; SLEngineOption engine_option; memset( &engine_option, 0, sizeof( SLEngineOption ) ); engine_option.feature = SL_ENGINEOPTION_THREADSAFE; engine_option.data = SL_BOOLEAN_TRUE; result = slCreateEngine ( &g_engine_object, 1, &engine_option, 0, NULL, NULL ); if( SL_RESULT_SUCCESS == result ) { result = ( *g_engine_object )->Realize ( g_engine_object, SL_BOOLEAN_FALSE ); if( SL_RESULT_SUCCESS == result ) { result = ( *g_engine_object )->GetInterface ( g_engine_object, SL_IID_ENGINE, &g_engine_interface ); if( SL_RESULT_SUCCESS != result ) { CPC_ERROR( "Error attempting to initialize interface: %d.", result ); } else { CPC_LOG_STRING( CPC_LOG_LEVEL_INFO, "Initialized CAHAL." ); g_cahal_state = CAHAL_STATE_INITIALIZED; } } else { CPC_ERROR( "Error attempting to realize engine: %d.", result ); } } else { CPC_ERROR( "Error attempting to create engine: %d.", result ); } } else { CPC_LOG_STRING( CPC_LOG_LEVEL_WARN, "CAHAL is already intialized" ); } }
bool OpenSLRecorder::init(int sampleRate, int channels){ if(mInited) return true; SLresult result; do{ // create engine result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL); if(SL_RESULT_SUCCESS != result){ ALOGE("failed to create slengine obj!!"); break; } (void)result; // realize the engine result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); if(SL_RESULT_SUCCESS != result){ ALOGE("failed to realize slengine obj!!"); break; } (void)result; // get the engine interface, which is needed in order to create other objects result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); if(SL_RESULT_SUCCESS != result){ ALOGE("failed to get engine itf!!"); break; } (void)result; // create output mix, with environmental reverb specified as a non-required interface const SLInterfaceID ids[1] = {SL_IID_ENVIRONMENTALREVERB}; const SLboolean req[1] = {SL_BOOLEAN_FALSE}; result = (*engineEngine)->CreateOutputMix(engineEngine, &outputMixObject, 1, ids, req); if(SL_RESULT_SUCCESS != result){ ALOGE("failed to create sloutput mix!!"); break; } (void)result; // realize the output mix result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE); if(SL_RESULT_SUCCESS != result){ ALOGE("failed to realize sl outputmix!!"); break; } (void)result; // get the environmental reverb interface // this could fail if the environmental reverb effect is not available, // either because the feature is not present, excessive CPU load, or // the required MODIFY_AUDIO_SETTINGS permission was not requested and granted result = (*outputMixObject)->GetInterface(outputMixObject, SL_IID_ENVIRONMENTALREVERB, &outputMixEnvironmentalReverb); if (SL_RESULT_SUCCESS == result) { result = (*outputMixEnvironmentalReverb)->SetEnvironmentalReverbProperties(outputMixEnvironmentalReverb, &reverbSettings); (void)result; } /////////////////// configure audio source SLDataLocator_IODevice loc_dev = {SL_DATALOCATOR_IODEVICE, SL_IODEVICE_AUDIOINPUT, SL_DEFAULTDEVICEID_AUDIOINPUT, NULL}; SLDataSource audioSrc = {&loc_dev, NULL}; // configure audio sink SLDataLocator_AndroidSimpleBufferQueue loc_bq = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2}; SLDataFormat_PCM format_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}; SLDataSink audioSnk = {&loc_bq, &format_pcm}; // create audio recorder // (requires the RECORD_AUDIO permission) const SLInterfaceID ids2[1] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE}; const SLboolean req2[1] = {SL_BOOLEAN_TRUE}; result = (*engineEngine)->CreateAudioRecorder(engineEngine, &recorderObject, &audioSrc, &audioSnk, 1, ids2, req2); if(SL_RESULT_SUCCESS != result){ ALOGE("failed to create sl audio recorder obj!!"); break; } // realize the audio recorder result = (*recorderObject)->Realize(recorderObject, SL_BOOLEAN_FALSE); if(SL_RESULT_SUCCESS != result){ ALOGE("failed to realize sl recorder obj!!"); break; } // get the record interface result = (*recorderObject)->GetInterface(recorderObject, SL_IID_RECORD, &recorderRecord); if(SL_RESULT_SUCCESS != result){ ALOGE("failed to get record itf!!"); break; } (void)result; // get the buffer queue interface result = (*recorderObject)->GetInterface(recorderObject, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &recorderBufferQueue); if(SL_RESULT_SUCCESS != result){ ALOGE("failed to get buffer queue itf for audio record!!"); break; } (void)result; // register callback on the buffer queue result = (*recorderBufferQueue)->RegisterCallback(recorderBufferQueue, bqRecorderCallback, this); if(SL_RESULT_SUCCESS != result){ ALOGE("failed to register callback for audio record!!"); break; } (void)result; mInited = true; }while(0); if(!mInited) reset(); return mInited; }
static void *sl_init(const char *device, unsigned rate, unsigned latency) { (void)device; sl_t *sl = (sl_t*)calloc(1, sizeof(sl_t)); if (!sl) goto error; SLEngineOption EngineOption[] = { (SLuint32) SL_ENGINEOPTION_THREADSAFE, (SLuint32) SL_BOOLEAN_TRUE }; sl->res_ptr = slCreateEngine(&sl->sl, 1, EngineOption, 0, NULL, NULL); if(sl->res_ptr != SL_RESULT_SUCCESS) goto error; /* Realizing the SL Engine in synchronous mode */ sl->res_ptr = (*sl->sl)->Realize(sl->sl, SL_BOOLEAN_FALSE); if(sl->res_ptr != SL_RESULT_SUCCESS) goto error; /* Get interface for IID_ENGINE */ sl->res_ptr = (*sl->sl)->GetInterface(sl->sl, SL_IID_ENGINE, (void*)&sl->EngineItf); if(sl->res_ptr != SL_RESULT_SUCCESS) goto error; /* VOLUME interface */ /* NOTES by Google: * Please see section "Supported features from OpenSL ES 1.0.1", * subsection "Objects and interfaces" in <NDKroot>/docs/opensles/index.html * You'll see that the cell for object Output mix interface Volume is white. * This means it is not a supported combination. * As a workaround, use the Volume interface on the Audio player object. */ /* This seems to fail right now: * libOpenSLES(19315): class OutputMix interface 0 requested but unavailable MPH=43 */ const SLInterfaceID ids[] = {SL_IID_VOLUME}; const SLboolean req[] = {SL_BOOLEAN_FALSE}; /* Create Output Mix object to be used by player */ sl->res_ptr = (*sl->EngineItf)->CreateOutputMix(sl->EngineItf, &sl->OutputMix, 1, ids, req); if(sl->res_ptr != SL_RESULT_SUCCESS) goto error; /* Realizing the Output Mix object in synchonous mode */ sl->res_ptr = (*sl->OutputMix)->Realize(sl->OutputMix, SL_BOOLEAN_FALSE); if(sl->res_ptr != SL_RESULT_SUCCESS) goto error; #if 0 /* Get interface for IID_VOLUME */ sl->res_ptr = (*sl->OutputMix)->GetInterface(sl->OutputMix, SL_IID_VOLUME, (void*)&sl->volumeItf); if(sl->res_ptr != SL_RESULT_SUCCESS) goto error; #endif /* TODO: hardcode for now, make this use the parameters in some way later */ SLuint32 rate_sl = SL_SAMPLINGRATE_48; SLuint8 bits_sl = 16; /* Setup the data source structure for the buffer queue */ sl->bufferQueue.locatorType = ISL_DATALOCATOR_BUFFERQUEUE; sl->bufferQueue.numBuffers = 2; /* Setup the format of the content in the buffer queue */ sl->pcm.formatType = SL_DATAFORMAT_PCM; sl->pcm.numChannels = 2; sl->pcm.samplesPerSec = rate_sl; sl->pcm.bitsPerSample = bits_sl; sl->pcm.containerSize = bits_sl; sl->pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; sl->pcm.endianness = SL_BYTEORDER_LITTLEENDIAN; sl->audioSource.pFormat = (void*)&sl->pcm; sl->audioSource.pLocator = (void*)&sl->bufferQueue; /* Setup the data sink structure */ sl->locator_outputmix.locatorType = SL_DATALOCATOR_OUTPUTMIX; sl->locator_outputmix.outputMix = sl->OutputMix; sl->audioSink.pLocator = (void*)&sl->locator_outputmix; sl->audioSink.pFormat = NULL; /* Initialize the context for buffer queue callbacks */ sl->cntxt.pDataBase = (void*)&pcmData; sl->cntxt.pData = sl->cntxt.pDataBase; sl->cntxt.size = sizeof(pcmData); /* Initialize audio data to silence */ memset(pcmData, 0, sizeof(pcmData)); const SLInterfaceID ids1[] = {ISL_IID_BUFFERQUEUE}; const SLboolean req1[] = {SL_BOOLEAN_TRUE}; /* Create the music player */ sl->res_ptr = (*sl->EngineItf)->CreateAudioPlayer(sl->EngineItf, &sl->player, &sl->audioSource, &sl->audioSink, 1, ids1, req1); if(sl->res_ptr != SL_RESULT_SUCCESS) goto error; /* Realizing the player in synchronous mode. */ sl->res_ptr = (*sl->player)->Realize(sl->player, SL_BOOLEAN_FALSE); if(sl->res_ptr != SL_RESULT_SUCCESS) goto error; /* Get interface for IID_PLAY */ sl->res_ptr = (*sl->player)->GetInterface(sl->player, SL_IID_PLAY, (void*)&sl->playItf); if(sl->res_ptr != SL_RESULT_SUCCESS) goto error; /* Get interface for IID_BUFFERQUEUE */ sl->res_ptr = (*sl->player)->GetInterface(sl->player, ISL_IID_BUFFERQUEUE, (void*)&sl->bufferQueueItf); if(sl->res_ptr != SL_RESULT_SUCCESS) goto error; /* Setup to receive buffer queue event callbacks */ sl->res_ptr = (*sl->bufferQueueItf)->RegisterCallback(sl->bufferQueueItf, BufferQueueCallback, NULL); if(sl->res_ptr != SL_RESULT_SUCCESS) goto error; #if 0 /* Before we start set volume to -3dB (-300mB) */ /* TODO: Necessary or not? Let's not do this for now */ sl->res_ptr = (*sl->volumeItf)->SetVolumeLevel(sl->volumeItf, -300); if(sl->res_ptr != SL_RESULT_SUCCESS) goto error; #endif /* Setup for audio playback */ /* As suggested by Google above as a replacement for OutputMix IID_VOLUME - see note */ sl->res_ptr = (*sl->player)->GetInterface(sl->player, SL_IID_VOLUME, &sl->volumeItf); if(sl->res_ptr != SL_RESULT_SUCCESS) goto error; sl->res_ptr = (*sl->playItf)->SetPlayState(sl->playItf, SL_PLAYSTATE_PLAYING); if(sl->res_ptr != SL_RESULT_SUCCESS) goto error; return sl; error: RARCH_ERR("Couldn't initialize OpenSL ES driver, error code: [%d].\n", sl->res_ptr); if (sl) { (*sl->sl)->Destroy(sl->sl); free(sl); } return NULL; }
static int _impl_setup(rh_aout_api_itf self) { extern AAssetManager * __rh_hack_get_android_asset_manager(); static const SLEngineOption options[] = { { SL_ENGINEOPTION_THREADSAFE, SL_BOOLEAN_TRUE }, { SL_ENGINEOPTION_LOSSOFCONTROL, SL_BOOLEAN_FALSE }, }; struct sles_api_instance * instance = (struct sles_api_instance *)self; instance->asset_manager = __rh_hack_get_android_asset_manager(); if(!instance->asset_manager) goto bad; if (SL_RESULT_SUCCESS != slCreateEngine(&instance->engineObject, sizeof(options) / sizeof(options[0]), options, 0, NULL, NULL)) goto bad; if (SL_RESULT_SUCCESS != (*instance->engineObject)->Realize(instance->engineObject, SL_BOOLEAN_FALSE )) goto bad; if (SL_RESULT_SUCCESS != (*instance->engineObject)->GetInterface(instance->engineObject, SL_IID_ENGINE, &instance->engineItf)) goto bad; if (SL_RESULT_SUCCESS != (*instance->engineItf)->CreateOutputMix(instance->engineItf, &instance->outputMix, 0, NULL, NULL)) goto bad; if (SL_RESULT_SUCCESS != (*instance->outputMix)->Realize(instance->outputMix, SL_BOOLEAN_FALSE )) goto bad; if( pipe( &instance->cmd_pipe.read ) != 0 ) goto bad; if(fcntl( instance->cmd_pipe.read, F_SETFL, O_NONBLOCK) != 0) goto bad; if(bucket_create(&instance->aout_itf_bucket) != 0) goto bad; if(add_channels(self, 3) != 0) goto bad; { pthread_t thread; if(pthread_create(&thread, NULL, &api_main_loop, (void*)self) != 0) goto bad; instance->thread = thread; } pthread_detach( instance->thread ); good: return 0; bad: if( instance->outputMix ) (*instance->outputMix)->Destroy(instance->outputMix); if( instance->engineObject ) (*instance->engineObject)->Destroy(instance->engineObject); if(instance->aout_itf_bucket) { close_all_channels(self); bucket_free(instance->aout_itf_bucket); } if(instance->cmd_pipe.write) close(instance->cmd_pipe.write); if(instance->cmd_pipe.read) close(instance->cmd_pipe.read); return -1; }
static void *sl_init(const char *device, unsigned rate, unsigned latency) { unsigned i; SLInterfaceID id; SLboolean req; SLresult res; sl_t *sl; SLDataFormat_PCM fmt_pcm = {0}; SLDataSource audio_src = {0}; SLDataSink audio_sink = {0}; SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {0}; SLDataLocator_OutputMix loc_outmix = {0}; settings_t *settings = config_get_ptr(); (void)device; id = SL_IID_ANDROIDSIMPLEBUFFERQUEUE; req = SL_BOOLEAN_TRUE; res = 0; sl = (sl_t*)calloc(1, sizeof(sl_t)); if (!sl) goto error; RARCH_LOG("[SLES]: Requested audio latency: %u ms.", latency); GOTO_IF_FAIL(slCreateEngine(&sl->engine_object, 0, NULL, 0, NULL, NULL)); GOTO_IF_FAIL(SLObjectItf_Realize(sl->engine_object, SL_BOOLEAN_FALSE)); GOTO_IF_FAIL(SLObjectItf_GetInterface(sl->engine_object, SL_IID_ENGINE, &sl->engine)); GOTO_IF_FAIL(SLEngineItf_CreateOutputMix(sl->engine, &sl->output_mix, 0, NULL, NULL)); GOTO_IF_FAIL(SLObjectItf_Realize(sl->output_mix, SL_BOOLEAN_FALSE)); if (settings->audio.block_frames) sl->buf_size = settings->audio.block_frames * 4; else sl->buf_size = next_pow2(32 * latency); sl->buf_count = (latency * 4 * rate + 500) / 1000; sl->buf_count = (sl->buf_count + sl->buf_size / 2) / sl->buf_size; sl->buffer = (uint8_t**)calloc(sizeof(uint8_t*), sl->buf_count); if (!sl->buffer) goto error; sl->buffer_chunk = (uint8_t*)calloc(sl->buf_count, sl->buf_size); if (!sl->buffer_chunk) goto error; for (i = 0; i < sl->buf_count; i++) sl->buffer[i] = sl->buffer_chunk + i * sl->buf_size; RARCH_LOG("[SLES]: Setting audio latency: Block size = %u, Blocks = %u, Total = %u ...\n", sl->buf_size, sl->buf_count, sl->buf_size * sl->buf_count); fmt_pcm.formatType = SL_DATAFORMAT_PCM; fmt_pcm.numChannels = 2; fmt_pcm.samplesPerSec = rate * 1000; // Samplerate is in milli-Hz. fmt_pcm.bitsPerSample = 16; fmt_pcm.containerSize = 16; fmt_pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; fmt_pcm.endianness = SL_BYTEORDER_LITTLEENDIAN; /* Android only. */ audio_src.pLocator = &loc_bufq; audio_src.pFormat = &fmt_pcm; loc_bufq.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE; loc_bufq.numBuffers = sl->buf_count; loc_outmix.locatorType = SL_DATALOCATOR_OUTPUTMIX; loc_outmix.outputMix = sl->output_mix; audio_sink.pLocator = &loc_outmix; GOTO_IF_FAIL(SLEngineItf_CreateAudioPlayer(sl->engine, &sl->buffer_queue_object, &audio_src, &audio_sink, 1, &id, &req)); GOTO_IF_FAIL(SLObjectItf_Realize(sl->buffer_queue_object, SL_BOOLEAN_FALSE)); GOTO_IF_FAIL(SLObjectItf_GetInterface(sl->buffer_queue_object, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &sl->buffer_queue)); sl->cond = scond_new(); sl->lock = slock_new(); (*sl->buffer_queue)->RegisterCallback(sl->buffer_queue, opensl_callback, sl); /* Enqueue a bit to get stuff rolling. */ sl->buffered_blocks = sl->buf_count; sl->buffer_index = 0; for (i = 0; i < sl->buf_count; i++) (*sl->buffer_queue)->Enqueue(sl->buffer_queue, sl->buffer[i], sl->buf_size); GOTO_IF_FAIL(SLObjectItf_GetInterface(sl->buffer_queue_object, SL_IID_PLAY, &sl->player)); GOTO_IF_FAIL(SLPlayItf_SetPlayState(sl->player, SL_PLAYSTATE_PLAYING)); return sl; error: RARCH_ERR("Couldn't initialize OpenSL ES driver, error code: [%d].\n", (int)res); sl_free(sl); return NULL; }
/** * Initializes the audio device and creates sources. * * @warning: * * @return TRUE if initialization was successful, FALSE otherwise */ bool FSLESAudioDevice::InitializeHardware( void ) { UE_LOG( LogAndroidAudio, Warning, TEXT("SL Entered Init HW")); SLresult result; UE_LOG( LogAndroidAudio, Warning, TEXT("OpenSLES Initializing HW")); SLEngineOption EngineOption[] = { {(SLuint32) SL_ENGINEOPTION_THREADSAFE, (SLuint32) SL_BOOLEAN_TRUE} }; // create engine result = slCreateEngine( &SL_EngineObject, 1, EngineOption, 0, NULL, NULL); //check(SL_RESULT_SUCCESS == result); if (SL_RESULT_SUCCESS != result) { UE_LOG( LogAndroidAudio, Error, TEXT("Engine create failed %d"), int32(result)); } // realize the engine result = (*SL_EngineObject)->Realize(SL_EngineObject, SL_BOOLEAN_FALSE); check(SL_RESULT_SUCCESS == result); // get the engine interface, which is needed in order to create other objects result = (*SL_EngineObject)->GetInterface(SL_EngineObject, SL_IID_ENGINE, &SL_EngineEngine); check(SL_RESULT_SUCCESS == result); // create output mix, with environmental reverb specified as a non-required interface result = (*SL_EngineEngine)->CreateOutputMix( SL_EngineEngine, &SL_OutputMixObject, 0, NULL, NULL ); check(SL_RESULT_SUCCESS == result); // realize the output mix result = (*SL_OutputMixObject)->Realize(SL_OutputMixObject, SL_BOOLEAN_FALSE); check(SL_RESULT_SUCCESS == result); UE_LOG( LogAndroidAudio, Warning, TEXT("OpenSLES Initialized")); // ignore unsuccessful result codes for env // Default to sensible channel count. if( MaxChannels < 1 ) { MaxChannels = 12; } // Initialize channels. for( int32 i = 0; i < FMath::Min( MaxChannels, 12 ); i++ ) { FSLESSoundSource* Source = new FSLESSoundSource( this ); Sources.Add( Source ); FreeSources.Add( Source ); } if( Sources.Num() < 1 ) { UE_LOG( LogAndroidAudio, Warning, TEXT( "OpenSLAudio: couldn't allocate any sources" ) ); return false; } // Update MaxChannels in case we couldn't create enough sources. MaxChannels = Sources.Num(); UE_LOG( LogAndroidAudio, Warning, TEXT( "OpenSLAudioDevice: Allocated %i sources" ), MaxChannels ); // Set up a default (nop) effects manager Effects = new FAudioEffectsManager( this ); return true; }
int main(int argc, char **argv) { SLresult result; SLObjectItf engineObject; // create engine result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL); assert(SL_RESULT_SUCCESS == result); SLEngineItf engineEngine; result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); assert(SL_RESULT_SUCCESS == result); // create output mix SLObjectItf outputMixObject; result = (*engineEngine)->CreateOutputMix(engineEngine, &outputMixObject, 0, NULL, NULL); assert(SL_RESULT_SUCCESS == result); result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); // loop over all formats PCM *format; float hzLeft = 440.0; // A440 (Concert A) float hzRight = 440.0; for (format = formats; format->numChannels; ++format) { printf("Channels: %d, sample rate: %u, bits: %u\n", format->numChannels, format->milliHz / 1000, format->bitsPerSample); // configure audio source SLDataLocator_BufferQueue loc_bufq; loc_bufq.locatorType = SL_DATALOCATOR_BUFFERQUEUE; loc_bufq.numBuffers = 1; SLDataFormat_PCM format_pcm; format_pcm.formatType = SL_DATAFORMAT_PCM; format_pcm.numChannels = format->numChannels; format_pcm.samplesPerSec = format->milliHz; format_pcm.bitsPerSample = format->bitsPerSample; format_pcm.containerSize = format->bitsPerSample; format_pcm.channelMask = 0; format_pcm.endianness = SL_BYTEORDER_LITTLEENDIAN; SLDataSource audioSrc; audioSrc.pLocator = &loc_bufq; audioSrc.pFormat = &format_pcm; // configure audio sink SLDataLocator_OutputMix loc_outmix; loc_outmix.locatorType = SL_DATALOCATOR_OUTPUTMIX; loc_outmix.outputMix = outputMixObject; SLDataSink audioSnk; audioSnk.pLocator = &loc_outmix; audioSnk.pFormat = NULL; // create audio player SLuint32 numInterfaces = 1; SLInterfaceID ids[1]; SLboolean req[1]; ids[0] = SL_IID_BUFFERQUEUE; req[0] = SL_BOOLEAN_TRUE; SLObjectItf playerObject; result = (*engineEngine)->CreateAudioPlayer(engineEngine, &playerObject, &audioSrc, &audioSnk, numInterfaces, ids, req); if (SL_RESULT_SUCCESS != result) { printf("failed %u\n", result); continue; } // realize the player result = (*playerObject)->Realize(playerObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); // generate a sine wave buffer, ascending in half-steps for each format #define N (44100*4) static unsigned char buffer[N]; unsigned i; for (i = 0; i < N; ) { float seconds = (((i * 8) / (format->bitsPerSample * format->numChannels)) * 1000.0) / format->milliHz; short sampleLeft = sin(seconds * M_PI_2 * hzLeft) * 32767.0; short sampleRight = sin(seconds * M_PI_2 * hzRight) * 32767.0; if (2 == format->numChannels) { if (8 == format->bitsPerSample) { buffer[i++] = (sampleLeft + 32768) >> 8; buffer[i++] = (sampleRight + 32768) >> 8; } else { assert(16 == format->bitsPerSample); buffer[i++] = sampleLeft & 0xFF; buffer[i++] = sampleLeft >> 8; buffer[i++] = sampleRight & 0xFF; buffer[i++] = sampleRight >> 8; } } else {
int SNDOpenSLInit(int buffersize) { SLresult result; if(engineObject == NULL) { if(FAILED(result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL))) return -1; if(FAILED(result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE))) return -1; if(FAILED(result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine))) return -1; } const SLInterfaceID mixids[1] = {SL_IID_VOLUME}; const SLboolean mixreq[1] = {SL_BOOLEAN_FALSE}; if(FAILED(result = (*engineEngine)->CreateOutputMix(engineEngine, &outputMixObject, 1, mixids, mixreq))) return -1; if(FAILED(result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE))) return -1; SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2}; SLDataFormat_PCM format_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 audioSrc = {&loc_bufq, &format_pcm}; SLDataLocator_OutputMix loc_outmix = {SL_DATALOCATOR_OUTPUTMIX, outputMixObject}; SLDataSink audioSnk = {&loc_outmix, NULL}; const SLInterfaceID playerids[2] = {SL_IID_BUFFERQUEUE, SL_IID_VOLUME}; const SLboolean playerreq[2] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE}; if(FAILED(result = (*engineEngine)->CreateAudioPlayer(engineEngine, &bqPlayerObject, &audioSrc, &audioSnk, 2, playerids, playerreq))) return -1; if(FAILED(result = (*bqPlayerObject)->Realize(bqPlayerObject, SL_BOOLEAN_FALSE))) return -1; if(FAILED((*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_PLAY, &bqPlayerPlay))) return -1; if(FAILED(result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_BUFFERQUEUE, &bqPlayerBufferQueue))) return -1; if(FAILED((*bqPlayerBufferQueue)->RegisterCallback(bqPlayerBufferQueue, bqPlayerCallback, NULL))) return -1; if(FAILED(result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_VOLUME, &bqPlayerVolume))) return -1; if(FAILED(result = (*bqPlayerVolume)->GetMaxVolumeLevel(bqPlayerVolume, &maxVol))) return -1; if(FAILED(result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_PLAYING))) return -1; buffers[0].reset(); buffers[1].reset(); soundbufsize = buffersize; if ((buffers[0].data = new s16[soundbufsize / sizeof(s16)]) == NULL) return -1; if ((buffers[1].data = new s16[soundbufsize / sizeof(s16)]) == NULL) return -1; if ((empty.data = new s16[soundbufsize / sizeof(s16)]) == NULL) return -1; memset(buffers[0].data, 0, soundbufsize); memset(buffers[1].data, 0, soundbufsize); memset(empty.data, 0, soundbufsize); muted = false; currentlyPlaying = false; LOGI("OpenSL created (for audio output)"); return 0; }
static BOOL OSLES_Init(void) { short samplesize; int n; samplesize=1; if (md_mode&DMODE_STEREO) samplesize<<=1; if (md_mode&DMODE_16BITS) samplesize<<=1; SLresult result; // create engine result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL); if(SL_RESULT_SUCCESS != result) return 1; // realize the engine result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); if(SL_RESULT_SUCCESS != result) return 1; // get the engine interface, which is needed in order to create other objects result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); if(SL_RESULT_SUCCESS != result) return 1; // create output mix, with environmental reverb specified as a non-required interface const SLInterfaceID ids[1] = {SL_IID_ENVIRONMENTALREVERB}; const SLboolean req[1] = {SL_BOOLEAN_FALSE}; result = (*engineEngine)->CreateOutputMix(engineEngine, &outputMixObject, 0, ids, req); if(SL_RESULT_SUCCESS != result) return 1; // realize the output mix result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE); if(SL_RESULT_SUCCESS != result) return 1; /* // get the environmental reverb interface // this could fail if the environmental reverb effect is not available, // either because the feature is not present, excessive CPU load, or // the required MODIFY_AUDIO_SETTINGS permission was not requested and granted result = (*outputMixObject)->GetInterface(outputMixObject, SL_IID_ENVIRONMENTALREVERB, &outputMixEnvironmentalReverb); if (SL_RESULT_SUCCESS == result) { result = (*outputMixEnvironmentalReverb)->SetEnvironmentalReverbProperties( outputMixEnvironmentalReverb, &reverbSettings); } */ createBufferQueueAudioPlayer(); buffersize=md_mixfreq*samplesize*BUFFERSIZE/1000; for (n=0;n<NUMBUFFERS;n++) { buffer[n]=_mm_malloc(buffersize); if (!buffer[n]) { _mm_errno=MMERR_OUT_OF_MEMORY; return 1; } } md_mode|=DMODE_SOFT_MUSIC|DMODE_SOFT_SNDFX; buffersout=nextbuffer=0; return VC_Init(); }
SuperpoweredAndroidAudioIO::SuperpoweredAndroidAudioIO(int samplerate, int buffersize, bool enableInput, bool enableOutput, audioProcessingCallback callback, void *clientdata, int inputStreamType, int outputStreamType, int latencySamples) { static const SLboolean requireds[2] = { SL_BOOLEAN_TRUE, SL_BOOLEAN_FALSE }; internals = new SuperpoweredAndroidAudioIOInternals; memset(internals, 0, sizeof(SuperpoweredAndroidAudioIOInternals)); internals->samplerate = samplerate; internals->buffersize = buffersize; internals->clientdata = clientdata; internals->callback = callback; internals->hasInput = enableInput; internals->hasOutput = enableOutput; internals->foreground = true; internals->started = false; internals->silence = (short int *)malloc(buffersize * 4); memset(internals->silence, 0, buffersize * 4); if (latencySamples < 0) { // If latencySamples is negative, a separate processing thread is created for devices with badly configured/poorly written Android Audio HAL. It may help. internals->latencySamples = buffersize * 8; internals->separateAudioProcessingThread = true; internals->stopAudioProcessingThread = false; } else { internals->separateAudioProcessingThread = false; internals->latencySamples = latencySamples < buffersize ? buffersize : latencySamples; }; internals->numBuffers = (internals->latencySamples / buffersize) * 2; if (internals->numBuffers < 16) internals->numBuffers = 16; internals->bufferStep = (buffersize + 64) * 2; int fifoBufferSizeBytes = internals->numBuffers * internals->bufferStep * sizeof(short int); internals->fifobuffer = (short int *)malloc(fifoBufferSizeBytes); memset(internals->fifobuffer, 0, fifoBufferSizeBytes); // The separate processing thread operates using a signal, the mutex is not really blocking anything otherwise, so don't worry! if (internals->separateAudioProcessingThread) { pthread_mutex_init(&internals->audioProcessingThreadMutex, NULL); pthread_cond_init(&internals->audioProcessingThreadCondition, NULL); pthread_t thread; pthread_create(&thread, NULL, audioProcessingThread, internals); }; // Create the OpenSL ES engine. slCreateEngine(&internals->openSLEngine, 0, NULL, 0, NULL, NULL); (*internals->openSLEngine)->Realize(internals->openSLEngine, SL_BOOLEAN_FALSE); SLEngineItf openSLEngineInterface = NULL; (*internals->openSLEngine)->GetInterface(internals->openSLEngine, SL_IID_ENGINE, &openSLEngineInterface); // Create the output mix. (*openSLEngineInterface)->CreateOutputMix(openSLEngineInterface, &internals->outputMix, 0, NULL, NULL); (*internals->outputMix)->Realize(internals->outputMix, SL_BOOLEAN_FALSE); SLDataLocator_OutputMix outputMixLocator = { SL_DATALOCATOR_OUTPUTMIX, internals->outputMix }; if (enableInput) { // Create the audio input buffer queue. SLDataLocator_IODevice deviceInputLocator = { SL_DATALOCATOR_IODEVICE, SL_IODEVICE_AUDIOINPUT, SL_DEFAULTDEVICEID_AUDIOINPUT, NULL }; SLDataSource inputSource = { &deviceInputLocator, NULL }; SLDataLocator_AndroidSimpleBufferQueue inputLocator = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 1 }; SLDataFormat_PCM inputFormat = { SL_DATAFORMAT_PCM, 2, (SLuint32)samplerate * 1000, SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16, SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT, SL_BYTEORDER_LITTLEENDIAN }; SLDataSink inputSink = { &inputLocator, &inputFormat }; const SLInterfaceID inputInterfaces[2] = { SL_IID_ANDROIDSIMPLEBUFFERQUEUE, SL_IID_ANDROIDCONFIGURATION }; (*openSLEngineInterface)->CreateAudioRecorder(openSLEngineInterface, &internals->inputBufferQueue, &inputSource, &inputSink, 2, inputInterfaces, requireds); if (inputStreamType == -1) inputStreamType = (int)SL_ANDROID_RECORDING_PRESET_VOICE_RECOGNITION; // Configure the voice recognition preset which has no signal processing for lower latency. if (inputStreamType > -1) { SLAndroidConfigurationItf inputConfiguration; if ((*internals->inputBufferQueue)->GetInterface(internals->inputBufferQueue, SL_IID_ANDROIDCONFIGURATION, &inputConfiguration) == SL_RESULT_SUCCESS) { SLuint32 st = (SLuint32)inputStreamType; (*inputConfiguration)->SetConfiguration(inputConfiguration, SL_ANDROID_KEY_RECORDING_PRESET, &st, sizeof(SLuint32)); }; }; (*internals->inputBufferQueue)->Realize(internals->inputBufferQueue, SL_BOOLEAN_FALSE); }; if (enableOutput) { // Create the audio output buffer queue. SLDataLocator_AndroidSimpleBufferQueue outputLocator = { SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 1 }; SLDataFormat_PCM outputFormat = { SL_DATAFORMAT_PCM, 2, (SLuint32)samplerate * 1000, SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16, SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT, SL_BYTEORDER_LITTLEENDIAN }; SLDataSource outputSource = { &outputLocator, &outputFormat }; const SLInterfaceID outputInterfaces[2] = { SL_IID_BUFFERQUEUE, SL_IID_ANDROIDCONFIGURATION }; SLDataSink outputSink = { &outputMixLocator, NULL }; (*openSLEngineInterface)->CreateAudioPlayer(openSLEngineInterface, &internals->outputBufferQueue, &outputSource, &outputSink, 2, outputInterfaces, requireds); // Configure the stream type. if (outputStreamType > -1) { SLAndroidConfigurationItf outputConfiguration; if ((*internals->outputBufferQueue)->GetInterface(internals->outputBufferQueue, SL_IID_ANDROIDCONFIGURATION, &outputConfiguration) == SL_RESULT_SUCCESS) { SLint32 st = (SLint32)outputStreamType; (*outputConfiguration)->SetConfiguration(outputConfiguration, SL_ANDROID_KEY_STREAM_TYPE, &st, sizeof(SLint32)); }; }; (*internals->outputBufferQueue)->Realize(internals->outputBufferQueue, SL_BOOLEAN_FALSE); }; if (enableInput) { // Initialize the audio input buffer queue. (*internals->inputBufferQueue)->GetInterface(internals->inputBufferQueue, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &internals->inputBufferQueueInterface); (*internals->inputBufferQueueInterface)->RegisterCallback(internals->inputBufferQueueInterface, SuperpoweredAndroidAudioIO_InputCallback, internals); (*internals->inputBufferQueueInterface)->Enqueue(internals->inputBufferQueueInterface, internals->fifobuffer, buffersize * 4); }; if (enableOutput) { // Initialize the audio output buffer queue. (*internals->outputBufferQueue)->GetInterface(internals->outputBufferQueue, SL_IID_BUFFERQUEUE, &internals->outputBufferQueueInterface); (*internals->outputBufferQueueInterface)->RegisterCallback(internals->outputBufferQueueInterface, SuperpoweredAndroidAudioIO_OutputCallback, internals); (*internals->outputBufferQueueInterface)->Enqueue(internals->outputBufferQueueInterface, internals->fifobuffer, buffersize * 4); }; startQueues(internals); }
int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "usage: %s URI\n", argv[0]); return EXIT_FAILURE; } SLresult result; SLObjectItf engineObject; // create engine result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL); assert(SL_RESULT_SUCCESS == result); SLEngineItf engineEngine; result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); assert(SL_RESULT_SUCCESS == result); // create output mix SLObjectItf outputMixObject; result = (*engineEngine)->CreateOutputMix(engineEngine, &outputMixObject, 0, NULL, NULL); assert(SL_RESULT_SUCCESS == result); result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); // configure audio source SLDataLocator_URI loc_uri; loc_uri.locatorType = SL_DATALOCATOR_URI; loc_uri.URI = (SLchar *) argv[1]; SLDataFormat_MIME format_mime; format_mime.formatType = SL_DATAFORMAT_MIME; format_mime.mimeType = NULL; format_mime.containerType = SL_CONTAINERTYPE_UNSPECIFIED; SLDataSource audioSrc; audioSrc.pLocator = &loc_uri; audioSrc.pFormat = &format_mime; // configure audio sink SLDataLocator_OutputMix loc_outmix; loc_outmix.locatorType = SL_DATALOCATOR_OUTPUTMIX; loc_outmix.outputMix = outputMixObject; SLDataSink audioSnk; audioSnk.pLocator = &loc_outmix; audioSnk.pFormat = NULL; // create audio player, requesting a buffer queue interface SLuint32 numInterfaces = 1; SLInterfaceID ids[1]; SLboolean req[1]; ids[0] = SL_IID_BUFFERQUEUE; req[0] = SL_BOOLEAN_TRUE; SLObjectItf playerObject; result = (*engineEngine)->CreateAudioPlayer(engineEngine, &playerObject, &audioSrc, &audioSnk, numInterfaces, ids, req); assert(SL_RESULT_FEATURE_UNSUPPORTED == result); assert(NULL == playerObject); #ifdef ANDROID ids[0] = SL_IID_ANDROIDSIMPLEBUFFERQUEUE; result = (*engineEngine)->CreateAudioPlayer(engineEngine, &playerObject, &audioSrc, &audioSnk, numInterfaces, ids, req); assert(SL_RESULT_FEATURE_UNSUPPORTED == result); assert(NULL == playerObject); #endif // create audio player, without requesting a buffer queue interface result = (*engineEngine)->CreateAudioPlayer(engineEngine, &playerObject, &audioSrc, &audioSnk, 0, NULL, NULL); assert(SL_RESULT_SUCCESS == result); // realize the player result = (*playerObject)->Realize(playerObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); // get the play interface SLPlayItf playerPlay; result = (*playerObject)->GetInterface(playerObject, SL_IID_PLAY, &playerPlay); assert(SL_RESULT_SUCCESS == result); // get the buffer queue interface SLBufferQueueItf playerBufferQueue; result = (*playerObject)->GetInterface(playerObject, SL_IID_BUFFERQUEUE, &playerBufferQueue); assert(SL_RESULT_FEATURE_UNSUPPORTED == result); assert(NULL == playerBufferQueue); #ifdef ANDROID SLAndroidSimpleBufferQueueItf playerAndroidSimpleBufferQueue; result = (*playerObject)->GetInterface(playerObject, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &playerAndroidSimpleBufferQueue); assert(SL_RESULT_FEATURE_UNSUPPORTED == result); assert(NULL == playerAndroidSimpleBufferQueue); #endif // get the player duration SLmillisecond duration; result = (*playerPlay)->GetDuration(playerPlay, &duration); assert(SL_RESULT_SUCCESS == result); if (SL_TIME_UNKNOWN == duration) printf("Duration: unknown\n"); else printf("Duration: %.1f\n", duration / 1000.0f); // set the player's state to playing result = (*playerPlay)->SetPlayState(playerPlay, SL_PLAYSTATE_PLAYING); assert(SL_RESULT_SUCCESS == result); // wait for the playback to finish for (;;) { SLuint32 playState; result = (*playerPlay)->GetPlayState(playerPlay, &playState); assert(SL_RESULT_SUCCESS == result); if (SL_PLAYSTATE_PLAYING != playState) { break; } usleep(10000); } // get the player duration result = (*playerPlay)->GetDuration(playerPlay, &duration); assert(SL_RESULT_SUCCESS == result); if (SL_TIME_UNKNOWN == duration) printf("Duration: unknown\n"); else printf("Duration: %.1f\n", duration / 1000.0f); // destroy audio player (*playerObject)->Destroy(playerObject); // destroy output mix (*outputMixObject)->Destroy(outputMixObject); // destroy engine (*engineObject)->Destroy(engineObject); return EXIT_SUCCESS; }
bool OpenSLESPlayer::Initialize () { SLresult result; SLuint32 numSupportedInterfaces; LOG_OSL ("********************************"); LOG_OSL ("********************************"); LOG_OSL ("********************************"); LOG_OSL ("********************************"); LOG_OSL ("********************************"); LOG_OSL ("********************************"); LOG_OSL ("********************************"); LOG_OSL ("********************************"); LOG_OSL ("********************************"); LOG_OSL ("OpenSLESPlayer::Initialize ()"); slQueryNumSupportedEngineInterfaces (&numSupportedInterfaces); LOG_OSL (" %d supported engine interfaces:", numSupportedInterfaces); for (SLuint32 i = 0; i < numSupportedInterfaces; i ++) { SLInterfaceID interfaceId; slQuerySupportedEngineInterfaces (i, &interfaceId); LOG_OSL (" interface = %s: ", interfaceIdToString (interfaceId)); } LOG_OSL ("********************************"); LOG_OSL ("********************************"); LOG_OSL ("********************************"); LOG_OSL ("********************************"); LOG_OSL ("********************************"); LOG_OSL ("********************************"); LOG_OSL ("********************************"); LOG_OSL ("********************************"); LOG_OSL ("********************************"); #if 0 const SLInterfaceID ids[1] = {SL_IID_ENGINECAPABILITIES}; const SLboolean req[1] = {SL_BOOLEAN_TRUE}; result = slCreateEngine(&engineObject, 0, NULL, 1, ids, req); #else result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL); #endif CHECK_RESULT_BOOL ("slCreateEngine"); result = (*engineObject)->Realize (engineObject, SL_BOOLEAN_FALSE); CHECK_RESULT_BOOL ("engine->Realize"); result = (*engineObject)->GetInterface (engineObject, SL_IID_ENGINE, &engineEngine); CHECK_RESULT_BOOL ("engine->GetInterface (SL_IID_ENGINE)"); #if 0 { SLEngineCapabilitiesItf capabilities; SLuint16 profilesSupported; result = (*engineObject)->GetInterface (engineObject, SL_IID_ENGINECAPABILITIES, &capabilities); CHECK_RESULT_BOOL ("engineObject->GetInterface (SL_IID_ENGINECAPABILITIES)"); result = (*capabilities)->QuerySupportedProfiles (capabilities, &profilesSupported); CHECK_RESULT_BOOL ("capabilities->QuerySupportedProfiles"); g_debug ("supported profiles:"); if (profilesSupported & SL_PROFILES_PHONE) g_debug (" PHONE"); if (profilesSupported & SL_PROFILES_MUSIC) g_debug (" MUSIC"); if (profilesSupported & SL_PROFILES_GAME) g_debug (" GAME"); } #endif result = (*engineEngine)->CreateOutputMix (engineEngine, &outputMixObject, 0, NULL, NULL); CHECK_RESULT_BOOL ("engine->CreateOutputMix"); result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE); CHECK_RESULT_BOOL ("outputMixObject->Realize"); return true; }
qboolean SNDDMA_Init( void ) { int rc; int fmt; int tmp; int i; // char *s; // bk001204 - unused struct audio_buf_info info; int caps; extern uid_t saved_euid; if ( snd_inited ) { return 1; } dmapos = 0; dma.samplebits = 16; dma.channels = 2; dma.samples = 1024*16; dma.submission_chunk = 1024*2; //dma.submission_chunk = 1; dma.speed = 44100; dma.speed = 22050; dmasize = (dma.samples * (dma.samplebits/8)); dma.buffer = calloc(1, dmasize); SLresult result; // create engine result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL); myassert(SL_RESULT_SUCCESS == result,"slCreateEngine"); // realize the engine result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); myassert(SL_RESULT_SUCCESS == result,"Realize"); // get the engine interface, which is needed in order to create other objects result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); myassert(SL_RESULT_SUCCESS == result,"GetInterface"); // create output mix result = (*engineEngine)->CreateOutputMix(engineEngine, &outputMixObject, 0, NULL, NULL); myassert(SL_RESULT_SUCCESS == result,"CreateOutputMix"); // realize the output mix result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE); myassert(SL_RESULT_SUCCESS == result,"Realize output mix"); //CREATE THE PLAYER // configure audio source SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 1}; SLDataFormat_PCM format_pcm = {SL_DATAFORMAT_PCM, 2, SL_SAMPLINGRATE_22_05, SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16, SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT, SL_BYTEORDER_LITTLEENDIAN}; SLDataSource audioSrc = {&loc_bufq, &format_pcm}; // configure audio sink SLDataLocator_OutputMix loc_outmix = {SL_DATALOCATOR_OUTPUTMIX, outputMixObject}; SLDataSink audioSnk = {&loc_outmix, NULL}; // create audio player Com_Printf("create audio player"); const SLInterfaceID ids[1] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE}; const SLboolean req[1] = {SL_BOOLEAN_TRUE}; result = (*engineEngine)->CreateAudioPlayer(engineEngine, &bqPlayerObject, &audioSrc, &audioSnk, 1, ids, req); myassert(SL_RESULT_SUCCESS == result,"CreateAudioPlayer"); // realize the player result = (*bqPlayerObject)->Realize(bqPlayerObject, SL_BOOLEAN_FALSE); myassert(SL_RESULT_SUCCESS == result,"Realize AudioPlayer"); // get the play interface result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_PLAY, &bqPlayerPlay); myassert(SL_RESULT_SUCCESS == result,"GetInterface AudioPlayer"); // get the buffer queue interface result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_BUFFERQUEUE, &bqPlayerBufferQueue); myassert(SL_RESULT_SUCCESS == result,"GetInterface buffer queue"); // register callback on the buffer queue result = (*bqPlayerBufferQueue)->RegisterCallback(bqPlayerBufferQueue, bqPlayerCallback, NULL); myassert(SL_RESULT_SUCCESS == result,"RegisterCallback"); // set the player's state to playing result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_PLAYING); myassert(SL_RESULT_SUCCESS == result,"SetPlayState"); result = (*bqPlayerBufferQueue)->Enqueue(bqPlayerBufferQueue, "\0", 1); myassert(SL_RESULT_SUCCESS == result,"Enqueue first buffer"); snd_inited = 1; return 1; }
// create the engine and output mix objects extern "C" bool OpenSLWrap_Init(AndroidAudioCallback cb, int _FramesPerBuffer, int _SampleRate) { audioCallback = cb; framesPerBuffer = _FramesPerBuffer; if (framesPerBuffer == 0) framesPerBuffer = 256; if (framesPerBuffer < 32) framesPerBuffer = 32; sampleRate = _SampleRate; if (sampleRate != 44100 && sampleRate != 48000) { ELOG("Invalid sample rate %i - choosing 44100", sampleRate); sampleRate = 44100; } buffer[0] = new short[framesPerBuffer * 2]; buffer[1] = new short[framesPerBuffer * 2]; SLresult result; // create engine result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL); assert(SL_RESULT_SUCCESS == result); result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); assert(SL_RESULT_SUCCESS == result); result = (*engineEngine)->CreateOutputMix(engineEngine, &outputMixObject, 0, 0, 0); assert(SL_RESULT_SUCCESS == result); result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); SLuint32 sr = SL_SAMPLINGRATE_44_1; if (sampleRate == 48000) { sr = SL_SAMPLINGRATE_48; } SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2}; SLDataFormat_PCM format_pcm = { SL_DATAFORMAT_PCM, 2, sr, SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16, SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT, SL_BYTEORDER_LITTLEENDIAN }; SLDataSource audioSrc = {&loc_bufq, &format_pcm}; // configure audio sink SLDataLocator_OutputMix loc_outmix = {SL_DATALOCATOR_OUTPUTMIX, outputMixObject}; SLDataSink audioSnk = {&loc_outmix, NULL}; // create audio player const SLInterfaceID ids[2] = {SL_IID_BUFFERQUEUE, SL_IID_VOLUME}; const SLboolean req[2] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE}; result = (*engineEngine)->CreateAudioPlayer(engineEngine, &bqPlayerObject, &audioSrc, &audioSnk, 2, ids, req); assert(SL_RESULT_SUCCESS == result); result = (*bqPlayerObject)->Realize(bqPlayerObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_PLAY, &bqPlayerPlay); assert(SL_RESULT_SUCCESS == result); result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_BUFFERQUEUE, &bqPlayerBufferQueue); assert(SL_RESULT_SUCCESS == result); result = (*bqPlayerBufferQueue)->RegisterCallback(bqPlayerBufferQueue, bqPlayerCallback, NULL); assert(SL_RESULT_SUCCESS == result); result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_VOLUME, &bqPlayerVolume); assert(SL_RESULT_SUCCESS == result); result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_PLAYING); assert(SL_RESULT_SUCCESS == result); // Render and enqueue a first buffer. (or should we just play the buffer empty?) curBuffer = 0; audioCallback(buffer[curBuffer], framesPerBuffer); result = (*bqPlayerBufferQueue)->Enqueue(bqPlayerBufferQueue, buffer[curBuffer], sizeof(buffer[curBuffer])); if (SL_RESULT_SUCCESS != result) { return false; } curBuffer ^= 1; return true; }
int main(int argc, char **argv) { SLresult result; bool loop = false; // process command line parameters char *prog = argv[0]; int i; for (i = 1; i < argc; ++i) { char *arg = argv[i]; if (arg[0] != '-') break; bool bad = false; // whether the option string is invalid if (!strncmp(arg, "--mix-preset", 12)) { if ('\0' == arg[12]) { outputMixPresetItfRequested = true; } else if ('=' == arg[12]) { outputMixPresetNumber = atoi(&arg[13]); outputMixPresetItfRequested = true; } else { bad = true; } } else if (!strncmp(arg, "--mix-name", 10)) { if ('\0' == arg[10]) { outputMixEnvironmentalItfRequested = true; } else if ('=' == arg[10]) { outputMixEnvironmentalName = &arg[11]; outputMixEnvironmentalItfRequested = true; } else { bad = true; } } else if (!strncmp(arg, "--player-preset", 15)) { if ('\0' == arg[15]) { playerPresetItfRequested = true; } else if ('=' == arg[15]) { playerPresetNumber = atoi(&arg[16]); playerPresetItfRequested = true; } else { bad = true; } } else if (!strncmp(arg, "--player-name", 13)) { if ('\0' == arg[13]) { playerEnvironmentalItfRequested = true; } else if ('=' == arg[13]) { playerEnvironmentalName = &arg[14]; playerEnvironmentalItfRequested = true; } else { bad = true; } } else if (!strcmp(arg, "--loop")) { loop = true; } else { bad = true; } if (bad) { fprintf(stderr, "%s: unknown option %s ignored\n", prog, arg); } } if (argc - i != 1) { fprintf(stderr, "usage: %s --mix-preset=# --mix-name=I3DL2 --player-preset=# " "--player-name=I3DL2 --loop filename\n", prog); return EXIT_FAILURE; } char *pathname = argv[i]; const SLEnvironmentalReverbSettings *envSettings; if (NULL != outputMixEnvironmentalName) { envSettings = lookupEnvName(outputMixEnvironmentalName); if (NULL == envSettings) { fprintf(stderr, "%s: output mix environmental reverb name %s not found, " "available names are:\n", prog, outputMixEnvironmentalName); printEnvNames(); return EXIT_FAILURE; } outputMixEnvironmentalSettings = *envSettings; } if (NULL != playerEnvironmentalName) { envSettings = lookupEnvName(playerEnvironmentalName); if (NULL == envSettings) { fprintf(stderr, "%s: player environmental reverb name %s not found, " "available names are:\n", prog, playerEnvironmentalName); printEnvNames(); return EXIT_FAILURE; } playerEnvironmentalSettings = *envSettings; } // create engine SLObjectItf engineObject; result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL); assert(SL_RESULT_SUCCESS == result); result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); SLEngineItf engineEngine; result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); assert(SL_RESULT_SUCCESS == result); // create output mix SLInterfaceID mix_ids[2]; SLboolean mix_req[2]; SLuint32 count = 0; if (outputMixPresetItfRequested) { mix_req[count] = SL_BOOLEAN_TRUE; mix_ids[count++] = SL_IID_PRESETREVERB; } if (outputMixEnvironmentalItfRequested) { mix_req[count] = SL_BOOLEAN_TRUE; mix_ids[count++] = SL_IID_ENVIRONMENTALREVERB; } SLObjectItf mixObject; result = (*engineEngine)->CreateOutputMix(engineEngine, &mixObject, count, mix_ids, mix_req); assert(SL_RESULT_SUCCESS == result); result = (*mixObject)->Realize(mixObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); // configure preset reverb on output mix SLPresetReverbItf outputMixPresetReverb; if (outputMixPresetItfRequested) { result = (*mixObject)->GetInterface(mixObject, SL_IID_PRESETREVERB, &outputMixPresetReverb); assert(SL_RESULT_SUCCESS == result); SLuint16 getPresetReverb = 12345; result = (*outputMixPresetReverb)->GetPreset(outputMixPresetReverb, &getPresetReverb); assert(SL_RESULT_SUCCESS == result); printf("Output mix default preset reverb number = %u\n", getPresetReverb); if (outputMixPresetNumber != ((SLuint16) ~0)) { result = (*outputMixPresetReverb)->SetPreset(outputMixPresetReverb, outputMixPresetNumber); if (SL_RESULT_SUCCESS == result) { result = (*outputMixPresetReverb)->GetPreset(outputMixPresetReverb, &getPresetReverb); assert(SL_RESULT_SUCCESS == result); assert(getPresetReverb == outputMixPresetNumber); printf("Output mix preset reverb successfully changed to %u\n", outputMixPresetNumber); } else { printf("Unable to set output mix preset reverb to %u, result=%u\n", outputMixPresetNumber, result); } } } // configure environmental reverb on output mix SLEnvironmentalReverbItf outputMixEnvironmentalReverb; if (outputMixEnvironmentalItfRequested) { result = (*mixObject)->GetInterface(mixObject, SL_IID_ENVIRONMENTALREVERB, &outputMixEnvironmentalReverb); assert(SL_RESULT_SUCCESS == result); SLEnvironmentalReverbSettings getSettings; result = (*outputMixEnvironmentalReverb)->GetEnvironmentalReverbProperties( outputMixEnvironmentalReverb, &getSettings); assert(SL_RESULT_SUCCESS == result); printf("Output mix default environmental reverb settings\n"); printf("------------------------------------------------\n"); slesutPrintEnvironmentalReverbSettings(&getSettings); printf("\n"); if (outputMixEnvironmentalName != NULL) { result = (*outputMixEnvironmentalReverb)->SetEnvironmentalReverbProperties( outputMixEnvironmentalReverb, &outputMixEnvironmentalSettings); assert(SL_RESULT_SUCCESS == result); printf("Output mix new environmental reverb settings\n"); printf("--------------------------------------------\n"); slesutPrintEnvironmentalReverbSettings(&outputMixEnvironmentalSettings); printf("\n"); result = (*outputMixEnvironmentalReverb)->GetEnvironmentalReverbProperties( outputMixEnvironmentalReverb, &getSettings); assert(SL_RESULT_SUCCESS == result); printf("Output mix read environmental reverb settings\n"); printf("--------------------------------------------\n"); slesutPrintEnvironmentalReverbSettings(&getSettings); printf("\n"); if (!slesutCompareEnvironmentalReverbSettings(&getSettings, &outputMixEnvironmentalSettings)) { printf("Warning: new and read are different; check details above\n"); } else { printf("New and read match, life is good\n"); } } } // create audio player SLDataLocator_URI locURI = {SL_DATALOCATOR_URI, (SLchar *) pathname}; SLDataFormat_MIME dfMIME = {SL_DATAFORMAT_MIME, NULL, SL_CONTAINERTYPE_UNSPECIFIED}; SLDataSource audioSrc = {&locURI, &dfMIME}; SLDataLocator_OutputMix locOutputMix = {SL_DATALOCATOR_OUTPUTMIX, mixObject}; SLDataSink audioSnk = {&locOutputMix, NULL}; SLInterfaceID player_ids[5]; SLboolean player_req[5]; count = 0; if (playerPresetItfRequested) { player_req[count] = SL_BOOLEAN_TRUE; player_ids[count++] = SL_IID_PRESETREVERB; } if (playerEnvironmentalItfRequested) { player_req[count] = SL_BOOLEAN_TRUE; player_ids[count++] = SL_IID_ENVIRONMENTALREVERB; } if (outputMixPresetItfRequested || outputMixEnvironmentalItfRequested) { player_req[count] = SL_BOOLEAN_TRUE; player_ids[count++] = SL_IID_EFFECTSEND; } if (loop) { player_req[count] = SL_BOOLEAN_TRUE; player_ids[count++] = SL_IID_SEEK; } player_req[count] = SL_BOOLEAN_TRUE; player_ids[count++] = SL_IID_PREFETCHSTATUS; SLObjectItf playerObject; result = (*engineEngine)->CreateAudioPlayer(engineEngine, &playerObject, &audioSrc, &audioSnk, count, player_ids, player_req); assert(SL_RESULT_SUCCESS == result); // realize audio player result = (*playerObject)->Realize(playerObject, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == result); // if reverb is on output mix (aux effect), then enable it for this player if (outputMixPresetItfRequested || outputMixEnvironmentalItfRequested) { SLEffectSendItf playerEffectSend; result = (*playerObject)->GetInterface(playerObject, SL_IID_EFFECTSEND, &playerEffectSend); assert(SL_RESULT_SUCCESS == result); SLboolean enabled; SLmillibel directLevel; SLmillibel sendLevel; if (outputMixPresetItfRequested) { result = (*playerEffectSend)->IsEnabled(playerEffectSend, outputMixPresetReverb, &enabled); assert(SL_RESULT_SUCCESS == result); printf("Output mix preset reverb: player effect send default enabled = %s\n", enabled ? "true" : "false"); directLevel = 12345; result = (*playerEffectSend)->GetDirectLevel(playerEffectSend, &directLevel); assert(SL_RESULT_SUCCESS == result); printf("Output mix preset reverb: player effect send default direct level = %d\n", directLevel); sendLevel = 12345; result = (*playerEffectSend)->GetSendLevel(playerEffectSend, outputMixPresetReverb, &sendLevel); assert(SL_RESULT_SUCCESS == result); printf("Output mix preset reverb: player effect send default send level = %d\n", sendLevel); if (outputMixPresetNumber != ((SLuint16) ~0)) { result = (*playerEffectSend)->EnableEffectSend(playerEffectSend, outputMixPresetReverb, SL_BOOLEAN_TRUE, (SLmillibel) 0); assert(SL_RESULT_SUCCESS == result); result = (*playerEffectSend)->IsEnabled(playerEffectSend, outputMixPresetReverb, &enabled); assert(SL_RESULT_SUCCESS == result); directLevel = 12345; result = (*playerEffectSend)->GetDirectLevel(playerEffectSend, &directLevel); assert(SL_RESULT_SUCCESS == result); sendLevel = 12345; result = (*playerEffectSend)->GetSendLevel(playerEffectSend, outputMixPresetReverb, &sendLevel); assert(SL_RESULT_SUCCESS == result); printf("Output mix preset reverb: player effect send new enabled = %s, direct level" " = %d, send level = %d\n", enabled ? "true" : "false", directLevel, sendLevel); } } if (outputMixEnvironmentalItfRequested) { if (outputMixEnvironmentalName != NULL) { result = (*playerEffectSend)->IsEnabled(playerEffectSend, outputMixEnvironmentalReverb, &enabled); assert(SL_RESULT_SUCCESS == result); printf("Output mix environmental reverb: player effect send default enabled = %s\n", enabled ? "true" : "false"); directLevel = 12345; result = (*playerEffectSend)->GetDirectLevel(playerEffectSend, &directLevel); assert(SL_RESULT_SUCCESS == result); printf("Output mix environmental reverb: player effect send default direct level" " = %d\n", directLevel); sendLevel = 12345; result = (*playerEffectSend)->GetSendLevel(playerEffectSend, outputMixEnvironmentalReverb, &sendLevel); assert(SL_RESULT_SUCCESS == result); printf("Output mix environmental reverb: player effect send default send level" " = %d\n", sendLevel); result = (*playerEffectSend)->EnableEffectSend(playerEffectSend, outputMixEnvironmentalReverb, SL_BOOLEAN_TRUE, (SLmillibel) 0); assert(SL_RESULT_SUCCESS == result); result = (*playerEffectSend)->IsEnabled(playerEffectSend, outputMixEnvironmentalReverb, &enabled); assert(SL_RESULT_SUCCESS == result); directLevel = 12345; result = (*playerEffectSend)->GetDirectLevel(playerEffectSend, &directLevel); assert(SL_RESULT_SUCCESS == result); sendLevel = 12345; result = (*playerEffectSend)->GetSendLevel(playerEffectSend, outputMixEnvironmentalReverb, &sendLevel); assert(SL_RESULT_SUCCESS == result); printf("Output mix environmental reverb: player effect send new enabled = %s, " "direct level = %d, send level = %d\n", enabled ? "true" : "false", directLevel, sendLevel); } } } // configure preset reverb on player SLPresetReverbItf playerPresetReverb; if (playerPresetItfRequested) { result = (*playerObject)->GetInterface(playerObject, SL_IID_PRESETREVERB, &playerPresetReverb); assert(SL_RESULT_SUCCESS == result); SLuint16 getPresetReverb = 12345; result = (*playerPresetReverb)->GetPreset(playerPresetReverb, &getPresetReverb); if (SL_RESULT_SUCCESS == result) { printf("Player default preset reverb %u\n", getPresetReverb); if (playerPresetNumber != ((SLuint16) ~0)) { result = (*playerPresetReverb)->SetPreset(playerPresetReverb, playerPresetNumber); if (SL_RESULT_SUCCESS == result) { result = (*playerPresetReverb)->GetPreset(playerPresetReverb, &getPresetReverb); assert(SL_RESULT_SUCCESS == result); assert(getPresetReverb == playerPresetNumber); printf("Player preset reverb successfully changed to %u\n", playerPresetNumber); } else { printf("Unable to set player preset reverb to %u, result=%u\n", playerPresetNumber, result); } } } else { printf("Unable to get player default preset reverb, result=%u\n", result); } } // configure environmental reverb on player SLEnvironmentalReverbItf playerEnvironmentalReverb; if (playerEnvironmentalItfRequested) { result = (*playerObject)->GetInterface(playerObject, SL_IID_ENVIRONMENTALREVERB, &playerEnvironmentalReverb); assert(SL_RESULT_SUCCESS == result); SLEnvironmentalReverbSettings getSettings; memset(&getSettings, 0, sizeof(getSettings)); result = (*playerEnvironmentalReverb)->GetEnvironmentalReverbProperties( playerEnvironmentalReverb, &getSettings); if (SL_RESULT_SUCCESS == result) { printf("Player default environmental reverb settings\n"); printf("--------------------------------------------\n"); slesutPrintEnvironmentalReverbSettings(&getSettings); printf("\n"); if (playerEnvironmentalName != NULL) { result = (*playerEnvironmentalReverb)->SetEnvironmentalReverbProperties( playerEnvironmentalReverb, &playerEnvironmentalSettings); assert(SL_RESULT_SUCCESS == result); printf("Player new environmental reverb settings\n"); printf("----------------------------------------\n"); slesutPrintEnvironmentalReverbSettings(&playerEnvironmentalSettings); printf("\n"); result = (*playerEnvironmentalReverb)->GetEnvironmentalReverbProperties( playerEnvironmentalReverb, &getSettings); assert(SL_RESULT_SUCCESS == result); printf("Player read environmental reverb settings\n"); printf("-----------------------------------------\n"); slesutPrintEnvironmentalReverbSettings(&getSettings); printf("\n"); if (!slesutCompareEnvironmentalReverbSettings(&getSettings, &playerEnvironmentalSettings)) { printf("Warning: new and read are different; check details above\n"); } else { printf("New and read match, life is good\n"); } } } else { printf("Unable to get player default environmental reverb properties, result=%u\n", result); } } // get the play interface SLPlayItf playerPlay; result = (*playerObject)->GetInterface(playerObject, SL_IID_PLAY, &playerPlay); assert(SL_RESULT_SUCCESS == result); // get the prefetch status interface SLPrefetchStatusItf playerPrefetchStatus; result = (*playerObject)->GetInterface(playerObject, SL_IID_PREFETCHSTATUS, &playerPrefetchStatus); assert(SL_RESULT_SUCCESS == result); // enable prefetch status callbacks result = (*playerPrefetchStatus)->RegisterCallback(playerPrefetchStatus, prefetch_callback, NULL); assert(SL_RESULT_SUCCESS == result); result = (*playerPrefetchStatus)->SetCallbackEventsMask(playerPrefetchStatus, SL_PREFETCHEVENT_STATUSCHANGE | SL_PREFETCHEVENT_FILLLEVELCHANGE); assert(SL_RESULT_SUCCESS == result); // set play state to paused to enable pre-fetch so we can get a more reliable duration result = (*playerPlay)->SetPlayState(playerPlay, SL_PLAYSTATE_PAUSED); assert(SL_RESULT_SUCCESS == result); // wait for prefetch status callback to indicate either sufficient data or error pthread_mutex_lock(&mutex); while (prefetch_status == SL_PREFETCHSTATUS_UNKNOWN) { pthread_cond_wait(&cond, &mutex); } pthread_mutex_unlock(&mutex); if (prefetch_status == SL_PREFETCHSTATUS_ERROR) { fprintf(stderr, "Error during prefetch, exiting\n"); goto destroyRes; } // get the duration SLmillisecond duration; result = (*playerPlay)->GetDuration(playerPlay, &duration); assert(SL_RESULT_SUCCESS == result); if (SL_TIME_UNKNOWN == duration) { printf("duration: unknown\n"); } else { printf("duration: %.1f seconds\n", duration / 1000.0); } // enable looping if (loop) { SLSeekItf playerSeek; result = (*playerObject)->GetInterface(playerObject, SL_IID_SEEK, &playerSeek); assert(SL_RESULT_SUCCESS == result); result = (*playerSeek)->SetLoop(playerSeek, SL_BOOLEAN_TRUE, (SLmillisecond) 0, SL_TIME_UNKNOWN); assert(SL_RESULT_SUCCESS == result); } // start audio playing result = (*playerPlay)->SetPlayState(playerPlay, SL_PLAYSTATE_PLAYING); assert(SL_RESULT_SUCCESS == result); // wait for audio to finish playing SLuint32 state; for (;;) { result = (*playerPlay)->GetPlayState(playerPlay, &state); assert(SL_RESULT_SUCCESS == result); if (SL_PLAYSTATE_PLAYING != state) break; usleep(1000000); } assert(SL_PLAYSTATE_PAUSED == state); destroyRes: // cleanup objects (*playerObject)->Destroy(playerObject); (*mixObject)->Destroy(mixObject); (*engineObject)->Destroy(engineObject); return EXIT_SUCCESS; }
INT LcxSmd_AndDeviceOpen() { #if defined(__ANDROID__) INT hr = LC_OK; JNIEnv* pEnv = NULL; JavaVM* pJvm = LCSYS::g_pJavaVM; jclass clzz = LCSYS::g_JniClzz; if(NULL == pJvm || 0 > pJvm->AttachCurrentThread(&pEnv, NULL)) { LOGE("SndDeviceOpen::Err::AttachCurrentThread::\n"); return LC_EFAIL; } Jni_SndCreate = pEnv->GetStaticMethodID(clzz, "JniCB_MpCreate" , "(Ljava/lang/String;)I") ; if(0 == Jni_SndCreate ){ LOGE("GetStaticMethodID::Err::JniCB_MpCreate ----------\n"); return LC_EFAIL; } Jni_SndDestroy = pEnv->GetStaticMethodID(clzz, "JniCB_MpDestroy", "(I)I") ; if(0 == Jni_SndDestroy ){ LOGE("GetStaticMethodID::Err::JniCB_MpDestroy ----------\n"); return LC_EFAIL; } Jni_SndSetData = pEnv->GetStaticMethodID(clzz, "JniCB_MpSetData", "(III)I") ; if(0 == Jni_SndSetData ){ LOGE("GetStaticMethodID::Err::JniCB_MpSetData ----------\n"); return LC_EFAIL; } Jni_SndGetData = pEnv->GetStaticMethodID(clzz, "JniCB_MpGetData", "(II)I") ; if(0 == Jni_SndGetData ){ LOGE("GetStaticMethodID::Err::JniCB_MpGetData ----------\n"); return LC_EFAIL; } Jni_SndPlay = pEnv->GetStaticMethodID(clzz, "JniCB_MpPlay" , "(I)I") ; if(0 == Jni_SndPlay ){ LOGE("GetStaticMethodID::Err::JniCB_MpPlay ----------\n"); return LC_EFAIL; } Jni_SndStop = pEnv->GetStaticMethodID(clzz, "JniCB_MpStop" , "(I)I") ; if(0 == Jni_SndStop ){ LOGE("GetStaticMethodID::Err::JniCB_MpStop ----------\n"); return LC_EFAIL; } Jni_SndPause = pEnv->GetStaticMethodID(clzz, "JniCB_MpPause" , "(I)I") ; if(0 == Jni_SndPause ){ LOGE("GetStaticMethodID::Err::JniCB_MpPause ----------\n"); return LC_EFAIL; } Jni_SndReset = pEnv->GetStaticMethodID(clzz, "JniCB_MpReset" , "(I)I") ; if(0 == Jni_SndReset ){ LOGE("GetStaticMethodID::Err::JniCB_MpReset ----------\n"); return LC_EFAIL; } //LOGI("Play Sound Environemnt:: " // "Play-0x%X, Stop-0x%X, Pause-0x%X \n" // , (int)Jni_SndPlay, (int)Jni_SndStop, (int)Jni_SndPause); if( CLcxSndSL::g_slEngObj && CLcxSndSL::g_slEngDev && CLcxSndSL::g_slMixObj && CLcxSndSL::g_slMixEnv) return LC_OK; // create engine hr = slCreateEngine(&CLcxSndSL::g_slEngObj, 0, NULL, 0, NULL, NULL); assert(SL_RESULT_SUCCESS == hr); // realize the engine hr = (*CLcxSndSL::g_slEngObj)->Realize(CLcxSndSL::g_slEngObj, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == hr); // get the engine interface, which is needed in order to create other objects hr = (*CLcxSndSL::g_slEngObj)->GetInterface(CLcxSndSL::g_slEngObj, SL_IID_ENGINE, &CLcxSndSL::g_slEngDev); assert(SL_RESULT_SUCCESS == hr); // create output mix, with environmental reverb specified as a non-required interface const SLInterfaceID ids[1] = {SL_IID_ENVIRONMENTALREVERB}; const SLboolean req[1] = {SL_BOOLEAN_FALSE}; hr = (*CLcxSndSL::g_slEngDev)->CreateOutputMix(CLcxSndSL::g_slEngDev, &CLcxSndSL::g_slMixObj, 1, ids, req); assert(SL_RESULT_SUCCESS == hr); // realize the output mix hr = (*CLcxSndSL::g_slMixObj)->Realize(CLcxSndSL::g_slMixObj, SL_BOOLEAN_FALSE); assert(SL_RESULT_SUCCESS == hr); // get the environmental reverb interface // this could fail if the environmental reverb effect is not available, // either because the feature is not present, excessive CPU load, or // the required MODIFY_AUDIO_SETTINGS permission was not requested and granted hr = (*CLcxSndSL::g_slMixObj)->GetInterface(CLcxSndSL::g_slMixObj, SL_IID_ENVIRONMENTALREVERB, &CLcxSndSL::g_slMixEnv); if (SL_RESULT_SUCCESS == hr) { hr = (*CLcxSndSL::g_slMixEnv)->SetEnvironmentalReverbProperties( CLcxSndSL::g_slMixEnv, &CLcxSndSL::g_slMixRev); } // ignore unsuccessful hr codes for environmental reverb, as it is optional for this example LOGI("OpenSL Success\n"); return LC_OK; #endif return LC_EFAIL; }
static void InitializeAudio(uint32_t freq) { WriteTrace(TraceAudioInitShutdown, TraceDebug, "Start (freq: %d)",freq); if (freq < 4000) { WriteTrace(TraceAudioInitShutdown, TraceInfo, "Sometimes a bad frequency is requested so ignore it (freq: %d)",freq); WriteTrace(TraceAudioInitShutdown, TraceDebug, "Done"); return; } if (g_GameFreq == freq && g_primaryBuffer != NULL) { WriteTrace(TraceAudioInitShutdown, TraceInfo, "we are already using this frequency, so ignore it (freq: %d)",freq); WriteTrace(TraceAudioInitShutdown, TraceDebug, "Done"); return; } if (g_critical_failure) { WriteTrace(TraceAudioInitShutdown, TraceInfo, "had a critical failure in setting up plugin, so ignore init"); WriteTrace(TraceAudioInitShutdown, TraceDebug, "Done"); return; } /* This is important for the sync */ g_GameFreq = freq; #ifdef ANDROID SLuint32 sample_rate; if((freq/1000) <= 11) { g_OutputFreq = 11025; sample_rate = SL_SAMPLINGRATE_11_025; } else if((freq/1000) <= 22) { g_OutputFreq = 22050; sample_rate = SL_SAMPLINGRATE_22_05; } else if((freq/1000) <= 32) { g_OutputFreq = 32000; sample_rate = SL_SAMPLINGRATE_32; } else { g_OutputFreq = 44100; sample_rate = SL_SAMPLINGRATE_44_1; } #endif WriteTrace(TraceAudioInitShutdown, TraceInfo, "Requesting frequency: %iHz.", g_OutputFreq); /* reload these because they gets re-assigned from data below, and InitializeAudio can be called more than once */ g_PrimaryBufferSize = GetSetting(Buffer_PrimarySize); g_SecondaryBufferSize = GetSetting(Buffer_SecondarySize); g_SecondaryBufferNbr = GetSetting(Buffer_SecondaryNbr); /* Close everything because InitializeAudio can be called more than once */ CloseAudio(); /* Create primary buffer */ if(!CreatePrimaryBuffer()) { WriteTrace(TraceAudioInitShutdown, TraceError, "CreatePrimaryBuffer failed"); CloseAudio(); g_critical_failure = true; WriteTrace(TraceAudioInitShutdown, TraceDebug, "Done"); return; } /* Create secondary buffers */ if(!CreateSecondaryBuffers()) { WriteTrace(TraceAudioInitShutdown, TraceError, "CreateSecondaryBuffers failed"); CloseAudio(); g_critical_failure = true; WriteTrace(TraceAudioInitShutdown, TraceDebug, "Done"); return; } #ifdef ANDROID /* Create thread Locks to ensure synchronization between callback and processing code */ if (pthread_mutex_init(&(g_lock.mutex), (pthread_mutexattr_t*) NULL) != 0) { WriteTrace(TraceAudioInitShutdown, TraceError, "pthread_mutex_init failed"); CloseAudio(); g_critical_failure = true; WriteTrace(TraceAudioInitShutdown, TraceDebug, "Done"); return; } if (pthread_cond_init(&(g_lock.cond), (pthread_condattr_t*) NULL) != 0) { WriteTrace(TraceAudioInitShutdown, TraceError, "pthread_cond_init failed"); CloseAudio(); g_critical_failure = true; WriteTrace(TraceAudioInitShutdown, TraceDebug, "Done"); return; } pthread_mutex_lock(&(g_lock.mutex)); g_lock.value = g_lock.limit = g_SecondaryBufferNbr; pthread_mutex_unlock(&(g_lock.mutex)); /* Engine object */ SLresult result = slCreateEngine(&g_engineObject, 0, NULL, 0, NULL, NULL); if(result != SL_RESULT_SUCCESS) { WriteTrace(TraceAudioInitShutdown, TraceError, "slCreateEngine failed (result: %d)",result); } if(result == SL_RESULT_SUCCESS) { result = (*g_engineObject)->Realize(g_engineObject, SL_BOOLEAN_FALSE); if(result != SL_RESULT_SUCCESS) { WriteTrace(TraceAudioInitShutdown, TraceError, "slCreateEngine->Realize failed (result: %d)",result); } } if(result == SL_RESULT_SUCCESS) { result = (*g_engineObject)->GetInterface(g_engineObject, SL_IID_ENGINE, &g_engineEngine); if(result != SL_RESULT_SUCCESS) { WriteTrace(TraceAudioInitShutdown, TraceError, "slCreateEngine->GetInterface failed (result: %d)",result); } } if(result == SL_RESULT_SUCCESS) { /* Output mix object */ result = (*g_engineEngine)->CreateOutputMix(g_engineEngine, &g_outputMixObject, 0, NULL, NULL); if(result != SL_RESULT_SUCCESS) { WriteTrace(TraceAudioInitShutdown, TraceError, "slCreateEngine->CreateOutputMix failed (result: %d)",result); } } if(result == SL_RESULT_SUCCESS) { result = (*g_outputMixObject)->Realize(g_outputMixObject, SL_BOOLEAN_FALSE); if(result != SL_RESULT_SUCCESS) { WriteTrace(TraceAudioInitShutdown, TraceError, "g_outputMixObject->Realize failed (result: %d)",result); } } if(result == SL_RESULT_SUCCESS) { SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, g_SecondaryBufferNbr}; SLDataFormat_PCM format_pcm = {SL_DATAFORMAT_PCM,2, sample_rate, SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16, (SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT), SL_BYTEORDER_LITTLEENDIAN}; SLDataSource audioSrc = {&loc_bufq, &format_pcm}; /* Configure audio sink */ SLDataLocator_OutputMix loc_outmix = {SL_DATALOCATOR_OUTPUTMIX, g_outputMixObject}; SLDataSink audioSnk = {&loc_outmix, NULL}; /* Create audio player */ const SLInterfaceID ids1[] = {SL_IID_ANDROIDSIMPLEBUFFERQUEUE}; const SLboolean req1[] = {SL_BOOLEAN_TRUE}; result = (*g_engineEngine)->CreateAudioPlayer(g_engineEngine, &(g_playerObject), &audioSrc, &audioSnk, 1, ids1, req1); if(result != SL_RESULT_SUCCESS) { WriteTrace(TraceAudioInitShutdown, TraceError, "g_engineEngine->CreateAudioPlayer failed (result: %d)",result); } } /* Realize the player */ if(result == SL_RESULT_SUCCESS) { result = (*g_playerObject)->Realize(g_playerObject, SL_BOOLEAN_FALSE); if(result != SL_RESULT_SUCCESS) { WriteTrace(TraceAudioInitShutdown, TraceError, "g_playerObject->Realize failed (result: %d)",result); } } /* Get the play interface */ if(result == SL_RESULT_SUCCESS) { result = (*g_playerObject)->GetInterface(g_playerObject, SL_IID_PLAY, &(g_playerPlay)); if(result != SL_RESULT_SUCCESS) { WriteTrace(TraceAudioInitShutdown, TraceError, "g_playerObject->GetInterface(SL_IID_PLAY) failed (result: %d)",result); } } /* Get the buffer queue interface */ if(result == SL_RESULT_SUCCESS) { result = (*g_playerObject)->GetInterface(g_playerObject, SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &(g_bufferQueue)); if(result != SL_RESULT_SUCCESS) { WriteTrace(TraceAudioInitShutdown, TraceError, "g_playerObject->GetInterface(SL_IID_ANDROIDSIMPLEBUFFERQUEUE) failed (result: %d)",result); } } /* register callback on the buffer queue */ if(result == SL_RESULT_SUCCESS) { result = (*g_bufferQueue)->RegisterCallback(g_bufferQueue, queueCallback, &g_lock); if(result != SL_RESULT_SUCCESS) { WriteTrace(TraceAudioInitShutdown, TraceError, "bufferQueue->RegisterCallback() failed (result: %d)",result); } } /* set the player's state to playing */ if(result == SL_RESULT_SUCCESS) { result = (*g_playerPlay)->SetPlayState(g_playerPlay, SL_PLAYSTATE_PLAYING); if(result != SL_RESULT_SUCCESS) { WriteTrace(TraceAudioInitShutdown, TraceError, "g_playerPlay->SetPlayState(SL_PLAYSTATE_PLAYING) failed (result: %d)",result); } } if(result != SL_RESULT_SUCCESS) { WriteTrace(TraceAudioInitShutdown, TraceNotice, "Couldn't open OpenSLES audio"); CloseAudio(); g_critical_failure = true; } #endif WriteTrace(TraceAudioInitShutdown, TraceNotice, "Done"); }